Skip to content

Commit df0b86d

Browse files
authored
Merge pull request #103 from awslabs/amirkaws/fix-example-issues
fix: Examples issues & Cleanup
2 parents 7df1e54 + d1d58a6 commit df0b86d

File tree

11 files changed

+198
-90
lines changed

11 files changed

+198
-90
lines changed

Diff for: examples/Logging/src/HelloWorld/Function.cs

+17-6
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ public class Function
2121
private static HttpClient? _httpClient;
2222
private static IDynamoDBContext? _dynamoDbContext;
2323

24-
public Function()
24+
/// <summary>
25+
/// Function constructor
26+
/// </summary>
27+
public Function()
2528
{
2629
_httpClient = new HttpClient();
2730

@@ -36,6 +39,15 @@ public Function()
3639
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
3740
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
3841
}
42+
43+
/// <summary>
44+
/// Test constructor
45+
/// </summary>
46+
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
47+
{
48+
_httpClient = httpClient;
49+
_dynamoDbContext = dynamoDbContext;
50+
}
3951

4052
[Logging(LogEvent = true)]
4153
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigwProxyEvent,
@@ -108,17 +120,16 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques
108120
}
109121

110122
/// <summary>
111-
/// Saves the loopup record in DynamoDB
123+
/// Saves the lookup record in DynamoDB
112124
/// </summary>
113125
/// <param name="lookupRecord"></param>
114-
/// <returns></returns>
115-
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
126+
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
127+
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
116128
{
117129
try
118130
{
119131
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
120-
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
121-
return Task.FromResult(lookupRecord);
132+
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
122133
}
123134
catch (AmazonDynamoDBException e)
124135
{

Diff for: examples/Logging/test/HelloWorld.Test/FunctionTest.cs

+38-19
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,71 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Net;
34
using System.Net.Http;
45
using System.Text.Json;
6+
using System.Threading;
57
using System.Threading.Tasks;
8+
using Amazon.DynamoDBv2.DataModel;
69
using Xunit;
710
using Amazon.Lambda.APIGatewayEvents;
811
using Amazon.Lambda.TestUtilities;
12+
using Moq;
13+
using Moq.Protected;
914
using Xunit.Abstractions;
1015

1116
namespace HelloWorld.Tests
1217
{
1318
public class FunctionTest
1419
{
1520
private readonly ITestOutputHelper _testOutputHelper;
16-
private static readonly HttpClient Client = new HttpClient();
1721

1822
public FunctionTest(ITestOutputHelper testOutputHelper)
1923
{
2024
_testOutputHelper = testOutputHelper;
2125
}
2226

23-
private static async Task<string> GetCallingIP()
24-
{
25-
Client.DefaultRequestHeaders.Accept.Clear();
26-
Client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");
27-
28-
var stringTask = Client.GetStringAsync("http://checkip.amazonaws.com/")
29-
.ConfigureAwait(continueOnCapturedContext: false);
30-
31-
var msg = await stringTask;
32-
return msg.Replace("\n", "");
33-
}
34-
3527
[Fact]
3628
public async Task TestHelloWorldFunctionHandler()
3729
{
30+
// Arrange
3831
var requestId = Guid.NewGuid().ToString("D");
39-
var request = new APIGatewayProxyRequest()
40-
{ RequestContext = new APIGatewayProxyRequest.ProxyRequestContext() { RequestId = requestId } };
41-
var context = new TestLambdaContext()
32+
var accountId = Guid.NewGuid().ToString("D");
33+
var location = "192.158. 1.38";
34+
35+
var dynamoDbContext = new Mock<IDynamoDBContext>();
36+
var handlerMock = new Mock<HttpMessageHandler>();
37+
handlerMock
38+
.Protected()
39+
.Setup<Task<HttpResponseMessage>>(
40+
"SendAsync",
41+
ItExpr.IsAny<HttpRequestMessage>(),
42+
ItExpr.IsAny<CancellationToken>()
43+
)
44+
.ReturnsAsync(new HttpResponseMessage
45+
{
46+
StatusCode = HttpStatusCode.OK,
47+
Content = new StringContent(location)
48+
})
49+
.Verifiable();
50+
51+
var request = new APIGatewayProxyRequest
52+
{
53+
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
54+
{
55+
RequestId = requestId,
56+
AccountId = accountId
57+
}
58+
};
59+
60+
var context = new TestLambdaContext
4261
{
4362
FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1",
4463
FunctionVersion = "1",
4564
MemoryLimitInMB = 215,
4665
AwsRequestId = Guid.NewGuid().ToString("D")
4766
};
48-
string location = GetCallingIP().Result;
49-
Dictionary<string, string> body = new Dictionary<string, string>
67+
68+
var body = new Dictionary<string, string>
5069
{
5170
{ "LookupId", requestId },
5271
{ "Greeting", "Hello AWS Lambda Powertools for .NET" },
@@ -60,7 +79,7 @@ public async Task TestHelloWorldFunctionHandler()
6079
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
6180
};
6281

63-
var function = new Function();
82+
var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object));
6483
var response = await function.FunctionHandler(request, context);
6584

6685
_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);

Diff for: examples/Logging/test/HelloWorld.Test/HelloWorld.Tests.csproj

+2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
77
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
88
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.2.0" />
9+
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.2.20" />
910
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
11+
<PackageReference Include="Moq" Version="4.16.1"/>
1012
<PackageReference Include="xunit" Version="2.4.1" />
1113
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
1214
</ItemGroup>

Diff for: examples/Metrics/src/HelloWorld/Function.cs

+13-5
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ public Function()
4141
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
4242
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
4343
}
44+
45+
/// <summary>
46+
/// Test constructor
47+
/// </summary>
48+
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
49+
{
50+
_httpClient = httpClient;
51+
_dynamoDbContext = dynamoDbContext;
52+
}
4453

4554
/// <summary>
4655
/// Lambda Handler
@@ -141,17 +150,16 @@ public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyReques
141150
}
142151

143152
/// <summary>
144-
/// Saves the LookupRecord record in DynamoDB
153+
/// Saves the lookup record in DynamoDB
145154
/// </summary>
146155
/// <param name="lookupRecord">Instance of LookupRecord</param>
147-
/// <returns>LookupRecord</returns>
148-
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
156+
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
157+
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
149158
{
150159
try
151160
{
152161
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
153-
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
154-
return Task.FromResult(lookupRecord);
162+
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
155163
}
156164
catch (AmazonDynamoDBException e)
157165
{

Diff for: examples/Metrics/test/HelloWorld.Test/FunctionTest.cs

+37-18
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,71 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Net;
34
using System.Net.Http;
45
using System.Text.Json;
6+
using System.Threading;
57
using System.Threading.Tasks;
8+
using Amazon.DynamoDBv2.DataModel;
69
using Xunit;
710
using Amazon.Lambda.APIGatewayEvents;
811
using Amazon.Lambda.TestUtilities;
12+
using Moq;
13+
using Moq.Protected;
914
using Xunit.Abstractions;
1015

1116
namespace HelloWorld.Tests
1217
{
1318
public class FunctionTest
1419
{
1520
private readonly ITestOutputHelper _testOutputHelper;
16-
private static readonly HttpClient Client = new HttpClient();
1721

1822
public FunctionTest(ITestOutputHelper testOutputHelper)
1923
{
2024
_testOutputHelper = testOutputHelper;
2125
}
2226

23-
private static async Task<string> GetCallingIP()
24-
{
25-
Client.DefaultRequestHeaders.Accept.Clear();
26-
Client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");
27-
28-
var stringTask = Client.GetStringAsync("http://checkip.amazonaws.com/")
29-
.ConfigureAwait(continueOnCapturedContext: false);
30-
31-
var msg = await stringTask;
32-
return msg.Replace("\n", "");
33-
}
34-
3527
[Fact]
3628
public async Task TestHelloWorldFunctionHandler()
3729
{
3830
var requestId = Guid.NewGuid().ToString("D");
39-
var request = new APIGatewayProxyRequest()
40-
{ RequestContext = new APIGatewayProxyRequest.ProxyRequestContext() { RequestId = requestId } };
31+
var accountId = Guid.NewGuid().ToString("D");
32+
var location = "192.158. 1.38";
33+
Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE","AWSLambdaPowertools");
34+
35+
var dynamoDbContext = new Mock<IDynamoDBContext>();
36+
var handlerMock = new Mock<HttpMessageHandler>();
37+
handlerMock
38+
.Protected()
39+
.Setup<Task<HttpResponseMessage>>(
40+
"SendAsync",
41+
ItExpr.IsAny<HttpRequestMessage>(),
42+
ItExpr.IsAny<CancellationToken>()
43+
)
44+
.ReturnsAsync(new HttpResponseMessage
45+
{
46+
StatusCode = HttpStatusCode.OK,
47+
Content = new StringContent(location)
48+
})
49+
.Verifiable();
50+
51+
var request = new APIGatewayProxyRequest
52+
{
53+
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
54+
{
55+
RequestId = requestId,
56+
AccountId = accountId
57+
}
58+
};
59+
4160
var context = new TestLambdaContext()
4261
{
4362
FunctionName = "PowertoolsLoggingSample-HelloWorldFunction-Gg8rhPwO7Wa1",
4463
FunctionVersion = "1",
4564
MemoryLimitInMB = 215,
4665
AwsRequestId = Guid.NewGuid().ToString("D")
4766
};
48-
string location = GetCallingIP().Result;
49-
Dictionary<string, string> body = new Dictionary<string, string>
67+
68+
var body = new Dictionary<string, string>
5069
{
5170
{ "LookupId", requestId },
5271
{ "Greeting", "Hello AWS Lambda Powertools for .NET" },
@@ -60,7 +79,7 @@ public async Task TestHelloWorldFunctionHandler()
6079
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
6180
};
6281

63-
var function = new Function();
82+
var function = new Function(dynamoDbContext.Object, new HttpClient(handlerMock.Object));
6483
var response = await function.FunctionHandler(request, context);
6584

6685
_testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);

Diff for: examples/Metrics/test/HelloWorld.Test/HelloWorld.Tests.csproj

+2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
77
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
88
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.2.0" />
9+
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.2.20" />
910
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
11+
<PackageReference Include="Moq" Version="4.16.1"/>
1012
<PackageReference Include="xunit" Version="2.4.1" />
1113
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
1214
</ItemGroup>

Diff for: examples/Tracing/src/HelloWorld/Function.cs

+14-7
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ public Function()
4242
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
4343
_dynamoDbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
4444
}
45+
46+
/// <summary>
47+
/// Test constructor
48+
/// </summary>
49+
public Function(IDynamoDBContext dynamoDbContext, HttpClient httpClient)
50+
{
51+
_httpClient = httpClient;
52+
_dynamoDbContext = dynamoDbContext;
53+
}
4554

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

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

61-
62-
var location = await GetCallingIp();
70+
var location = await GetCallingIp().ConfigureAwait(false);
6371

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

126134
/// <summary>
127-
/// Saves the LookupRecord record in DynamoDB
135+
/// Saves the lookup record in DynamoDB
128136
/// </summary>
129137
/// <param name="lookupRecord">Instance of LookupRecord</param>
130-
/// <returns>LookupRecord</returns>
138+
/// <returns>A Task that can be used to poll or wait for results, or both.</returns>
131139
[Tracing(SegmentName = "DynamoDB")]
132-
private static Task<LookupRecord> SaveRecordInDynamo(LookupRecord lookupRecord)
140+
private static async Task SaveRecordInDynamo(LookupRecord lookupRecord)
133141
{
134142
try
135143
{
136144
Logger.LogInformation($"Saving record with id {lookupRecord.LookupId}");
137-
_dynamoDbContext?.SaveAsync(lookupRecord).Wait();
138-
return Task.FromResult(lookupRecord);
145+
await _dynamoDbContext?.SaveAsync(lookupRecord)!;
139146
}
140147
catch (AmazonDynamoDBException e)
141148
{

0 commit comments

Comments
 (0)