Skip to content

Commit

Permalink
Merge pull request #103 from awslabs/amirkaws/fix-example-issues
Browse files Browse the repository at this point in the history
fix: Examples issues & Cleanup
  • Loading branch information
sliedig authored Feb 27, 2022
2 parents 7df1e54 + d1d58a6 commit df0b86d
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 90 deletions.
23 changes: 17 additions & 6 deletions examples/Logging/src/HelloWorld/Function.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ public class Function
private static HttpClient? _httpClient;
private static IDynamoDBContext? _dynamoDbContext;

public Function()
/// <summary>
/// Function constructor
/// </summary>
public Function()
{
_httpClient = new HttpClient();

Expand All @@ -36,6 +39,15 @@ public Function()
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}

/// <summary>
/// Test constructor
/// </summary>
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
{
_httpClient = httpClient;
_dynamoDbContext = dynamoDbContext;
}

[Logging(LogEvent = true)]
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigwProxyEvent,
Expand Down Expand Up @@ -108,17 +120,16 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques
}

/// <summary>
/// Saves the loopup record in DynamoDB
/// Saves the lookup record in DynamoDB
/// </summary>
/// <param name="lookupRecord"></param>
/// <returns></returns>
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
{
try
{
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
return Task.FromResult(lookupRecord);
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
}
catch (AmazonDynamoDBException e)
{
Expand Down
57 changes: 38 additions & 19 deletions examples/Logging/test/HelloWorld.Test/FunctionTest.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,71 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Xunit;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.TestUtilities;
using Moq;
using Moq.Protected;
using Xunit.Abstractions;

namespace HelloWorld.Tests
{
public class FunctionTest
{
private readonly ITestOutputHelper _testOutputHelper;
private static readonly HttpClient Client = new HttpClient();

public FunctionTest(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}

private static async Task<string> GetCallingIP()
{
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");

var stringTask = Client.GetStringAsync("http://checkip.amazonaws.com/")
.ConfigureAwait(continueOnCapturedContext: false);

var msg = await stringTask;
return msg.Replace("\n", "");
}

[Fact]
public async Task TestHelloWorldFunctionHandler()
{
// Arrange
var requestId = Guid.NewGuid().ToString("D");
var request = new APIGatewayProxyRequest()
{ RequestContext = new APIGatewayProxyRequest.ProxyRequestContext() { RequestId = requestId } };
var context = new TestLambdaContext()
var accountId = Guid.NewGuid().ToString("D");
var location = "192.158. 1.38";

var dynamoDbContext = new Mock<IDynamoDBContext>();
var handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(location)
})
.Verifiable();

var request = new APIGatewayProxyRequest
{
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
RequestId = requestId,
AccountId = accountId
}
};

var context = new TestLambdaContext
{
FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1",
FunctionVersion = "1",
MemoryLimitInMB = 215,
AwsRequestId = Guid.NewGuid().ToString("D")
};
string location = GetCallingIP().Result;
Dictionary<string, string> body = new Dictionary<string, string>

var body = new Dictionary<string, string>
{
{ "LookupId", requestId },
{ "Greeting", "Hello AWS Lambda Powertools for .NET" },
Expand All @@ -60,7 +79,7 @@ public async Task TestHelloWorldFunctionHandler()
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};

var function = new Function();
var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object));
var response = await function.FunctionHandler(request, context);

_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
Expand Down
2 changes: 2 additions & 0 deletions examples/Logging/test/HelloWorld.Test/HelloWorld.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.2.0" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.2.20" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="Moq" Version="4.16.1"/>
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
</ItemGroup>
Expand Down
18 changes: 13 additions & 5 deletions examples/Metrics/src/HelloWorld/Function.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ public Function()
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}

/// <summary>
/// Test constructor
/// </summary>
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
{
_httpClient = httpClient;
_dynamoDbContext = dynamoDbContext;
}

/// <summary>
/// Lambda Handler
Expand Down Expand Up @@ -141,17 +150,16 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques
}

/// <summary>
/// Saves the LookupRecord record in DynamoDB
/// Saves the lookup record in DynamoDB
/// </summary>
/// <param name="lookupRecord">Instance of LookupRecord</param>
/// <returns>LookupRecord</returns>
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
{
try
{
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
return Task.FromResult(lookupRecord);
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
}
catch (AmazonDynamoDBException e)
{
Expand Down
55 changes: 37 additions & 18 deletions examples/Metrics/test/HelloWorld.Test/FunctionTest.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,71 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Xunit;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.TestUtilities;
using Moq;
using Moq.Protected;
using Xunit.Abstractions;

namespace HelloWorld.Tests
{
public class FunctionTest
{
private readonly ITestOutputHelper _testOutputHelper;
private static readonly HttpClient Client = new HttpClient();

public FunctionTest(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}

private static async Task<string> GetCallingIP()
{
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");

var stringTask = Client.GetStringAsync("http://checkip.amazonaws.com/")
.ConfigureAwait(continueOnCapturedContext: false);

var msg = await stringTask;
return msg.Replace("\n", "");
}

[Fact]
public async Task TestHelloWorldFunctionHandler()
{
var requestId = Guid.NewGuid().ToString("D");
var request = new APIGatewayProxyRequest()
{ RequestContext = new APIGatewayProxyRequest.ProxyRequestContext() { RequestId = requestId } };
var accountId = Guid.NewGuid().ToString("D");
var location = "192.158. 1.38";
Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE","AWSLambdaPowertools");

var dynamoDbContext = new Mock<IDynamoDBContext>();
var handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(location)
})
.Verifiable();

var request = new APIGatewayProxyRequest
{
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
RequestId = requestId,
AccountId = accountId
}
};

var context = new TestLambdaContext()
{
FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1",
FunctionVersion = "1",
MemoryLimitInMB = 215,
AwsRequestId = Guid.NewGuid().ToString("D")
};
string location = GetCallingIP().Result;
Dictionary<string, string> body = new Dictionary<string, string>

var body = new Dictionary<string, string>
{
{ "LookupId", requestId },
{ "Greeting", "Hello AWS Lambda Powertools for .NET" },
Expand All @@ -60,7 +79,7 @@ public async Task TestHelloWorldFunctionHandler()
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};

var function = new Function();
var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object));
var response = await function.FunctionHandler(request, context);

_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
Expand Down
2 changes: 2 additions & 0 deletions examples/Metrics/test/HelloWorld.Test/HelloWorld.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.2.0" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.2.20" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="Moq" Version="4.16.1"/>
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
</ItemGroup>
Expand Down
21 changes: 14 additions & 7 deletions examples/Tracing/src/HelloWorld/Function.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ public Function()
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}

/// <summary>
/// Test constructor
/// </summary>
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
{
_httpClient = httpClient;
_dynamoDbContext = dynamoDbContext;
}

/// <summary>
/// Lambda Handler
Expand All @@ -58,8 +67,7 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques

Logger.LogInformation("Getting ip address from external service");


var location = await GetCallingIp();
var location = await GetCallingIp().ConfigureAwait(false);

var lookupRecord = new LookupRecord(lookupId: requestContextRequestId,
greeting: "Hello AWS Lambda Powertools for .NET", ipAddress: location);
Expand Down Expand Up @@ -124,18 +132,17 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques
}

/// <summary>
/// Saves the LookupRecord record in DynamoDB
/// Saves the lookup record in DynamoDB
/// </summary>
/// <param name="lookupRecord">Instance of LookupRecord</param>
/// <returns>LookupRecord</returns>
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
[Tracing(SegmentName = "DynamoDB")]
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
{
try
{
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
return Task.FromResult(lookupRecord);
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
}
catch (AmazonDynamoDBException e)
{
Expand Down
Loading

0 comments on commit df0b86d

Please sign in to comment.