From daa7219197028532b89d67ad2989ad3e84a2694a Mon Sep 17 00:00:00 2001
From: Henrique Graca <999396+hjgraca@users.noreply.github.com>
Date: Tue, 4 Jul 2023 18:30:11 +0100
Subject: [PATCH] Refactor example to be simpler and with a comparable
Idempotent example Guid. Update dependencies.
---
.../Idempotency/src/HelloWorld/Function.cs | 67 +++----------------
.../src/HelloWorld/HelloWorld.csproj | 6 +-
.../test/HelloWorld.Test/FunctionTest.cs | 42 ++----------
.../HelloWorld.Test/HelloWorld.Tests.csproj | 6 +-
4 files changed, 24 insertions(+), 97 deletions(-)
diff --git a/examples/Idempotency/src/HelloWorld/Function.cs b/examples/Idempotency/src/HelloWorld/Function.cs
index 8b4dac91..a204081e 100644
--- a/examples/Idempotency/src/HelloWorld/Function.cs
+++ b/examples/Idempotency/src/HelloWorld/Function.cs
@@ -15,16 +15,13 @@
using System;
using System.Collections.Generic;
-using System.Net.Http;
using System.Text.Json;
-using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Amazon.DynamoDBv2;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using AWS.Lambda.Powertools.Idempotency;
-using AWS.Lambda.Powertools.Idempotency.Persistence;
using AWS.Lambda.Powertools.Logging;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
@@ -34,7 +31,6 @@ namespace HelloWorld;
public class Function
{
- private static HttpClient? _httpClient;
private static AmazonDynamoDBClient? _dynamoDbClient;
///
@@ -42,26 +38,23 @@ public class Function
///
public Function()
{
- _httpClient = new HttpClient();
_dynamoDbClient = new AmazonDynamoDBClient();
- Init(_dynamoDbClient, _httpClient);
+ Init(_dynamoDbClient);
}
///
/// Test constructor
///
- public Function(AmazonDynamoDBClient amazonDynamoDb, HttpClient httpClient)
+ public Function(AmazonDynamoDBClient amazonDynamoDb)
{
- _httpClient = httpClient;
_dynamoDbClient = amazonDynamoDb;
- Init(amazonDynamoDb, httpClient);
+ Init(amazonDynamoDb);
}
-
- private void Init(AmazonDynamoDBClient amazonDynamoDb, HttpClient httpClient)
+
+ private void Init(AmazonDynamoDBClient amazonDynamoDb)
{
ArgumentNullException.ThrowIfNull(amazonDynamoDb);
- ArgumentNullException.ThrowIfNull(httpClient);
var tableName = Environment.GetEnvironmentVariable("TABLE_NAME");
ArgumentNullException.ThrowIfNull(tableName);
@@ -92,29 +85,13 @@ private void Init(AmazonDynamoDBClient amazonDynamoDb, HttpClient httpClient)
[Logging(LogEvent = true)]
public async Task FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, ILambdaContext context)
{
- var serializationOptions = new JsonSerializerOptions
- {
- PropertyNameCaseInsensitive = true
- };
- var request = JsonSerializer.Deserialize(apigwProxyEvent.Body, serializationOptions);
- if (request is null)
- {
- return new APIGatewayProxyResponse
- {
- Body = "Invalid request",
- StatusCode = 403,
- Headers = new Dictionary { { "Content-Type", "application/json" } }
- };
- }
-
- var location = await GetCallingIp(request.Address);
-
var requestContextRequestId = apigwProxyEvent.RequestContext.RequestId;
var response = new
{
RequestId = requestContextRequestId,
Greeting = "Hello Powertools for AWS Lambda (.NET)",
- IpAddress = location
+ MethodGuid = GenerateGuid(), // Guid generated by the GenerateGuid method. used to compare Method output
+ HandlerGuid = Guid.NewGuid().ToString() // Guid generated in the Handler. used to compare Handler output
};
try
@@ -138,33 +115,11 @@ public async Task FunctionHandler(APIGatewayProxyReques
}
///
- /// Calls location api to return IP address
+ /// Generates a new Guid to check if value is the same between calls (should be when idempotency enabled)
///
- /// Uri of the service providing the calling IP
- /// IP address string
- private static async Task GetCallingIp(string address)
- {
- if (_httpClient == null) return "0.0.0.0";
- _httpClient.DefaultRequestHeaders.Accept.Clear();
- _httpClient.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");
-
- var response = await _httpClient.GetStringAsync(address).ConfigureAwait(false);
- var ip = response.Replace("\n", "");
-
- return ip;
- }
-}
-
-///
-/// Record to represent the data structure of Lookup request
-///
-[Serializable]
-public class LookupRequest
-{
- public string Address { get; private set; }
-
- public LookupRequest(string address)
+ /// GUID
+ private static string GenerateGuid()
{
- Address = address;
+ return Guid.NewGuid().ToString();
}
}
\ No newline at end of file
diff --git a/examples/Idempotency/src/HelloWorld/HelloWorld.csproj b/examples/Idempotency/src/HelloWorld/HelloWorld.csproj
index 7929beb9..1038c0c9 100644
--- a/examples/Idempotency/src/HelloWorld/HelloWorld.csproj
+++ b/examples/Idempotency/src/HelloWorld/HelloWorld.csproj
@@ -6,10 +6,10 @@
-
-
+
+
-
+
diff --git a/examples/Idempotency/test/HelloWorld.Test/FunctionTest.cs b/examples/Idempotency/test/HelloWorld.Test/FunctionTest.cs
index 72c44608..c75e7e3f 100644
--- a/examples/Idempotency/test/HelloWorld.Test/FunctionTest.cs
+++ b/examples/Idempotency/test/HelloWorld.Test/FunctionTest.cs
@@ -53,28 +53,14 @@ public async Task TestHelloWorldFunctionHandler()
// arrange
var requestId = Guid.NewGuid().ToString("D");
var accountId = Guid.NewGuid().ToString("D");
- var location = "192.158.1.38";
+
Environment.SetEnvironmentVariable("POWERTOOLS_SERVICE_NAME","powertools-dotnet-idempotency-sample");
Environment.SetEnvironmentVariable("POWERTOOLS_LOG_LEVEL","INFO");
Environment.SetEnvironmentVariable("TABLE_NAME",_tableName);
- var handlerMock = new Mock();
- handlerMock
- .Protected()
- .Setup>(
- "SendAsync",
- ItExpr.IsAny(),
- ItExpr.IsAny()
- )
- .ReturnsAsync(new HttpResponseMessage
- {
- StatusCode = HttpStatusCode.OK,
- Content = new StringContent(location)
- });
-
var request = new APIGatewayProxyRequest
{
- Body = "{\"address\": \"https://checkip.amazonaws.com\"}",
+ Body = "{\"address\": \"Hello World\"}",
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
RequestId = requestId,
@@ -89,25 +75,11 @@ public async Task TestHelloWorldFunctionHandler()
MemoryLimitInMB = 215,
AwsRequestId = Guid.NewGuid().ToString("D")
};
-
- var body = new Dictionary
- {
- { "RequestId", requestId },
- { "Greeting", "Hello Powertools for AWS Lambda (.NET)" },
- { "IpAddress", location },
- };
- var expectedResponse = new APIGatewayProxyResponse
- {
- Body = JsonSerializer.Serialize(body),
- StatusCode = 200,
- Headers = new Dictionary { { "Content-Type", "application/json" } }
- };
-
// act
- var function = new Function(_client, new HttpClient(handlerMock.Object));
+ var function = new Function(_client);
+
var firstResponse = await function.FunctionHandler(request, context);
- await function.FunctionHandler(request, context);
var secondCallContext = new TestLambdaContext
{
@@ -116,6 +88,7 @@ public async Task TestHelloWorldFunctionHandler()
MemoryLimitInMB = 215,
AwsRequestId = Guid.NewGuid().ToString("D")
};
+
var secondResponse = await function.FunctionHandler(request, secondCallContext);
_testOutputHelper.WriteLine("First Response: \n" + firstResponse.Body);
@@ -123,9 +96,8 @@ public async Task TestHelloWorldFunctionHandler()
// assert
Assert.Equal(firstResponse.Body, secondResponse.Body);
- Assert.Equal(expectedResponse.Body, secondResponse.Body);
- Assert.Equal(expectedResponse.Headers, secondResponse.Headers);
- Assert.Equal(expectedResponse.StatusCode, secondResponse.StatusCode);
+ Assert.Equal(firstResponse.Headers, secondResponse.Headers);
+ Assert.Equal(firstResponse.StatusCode, secondResponse.StatusCode);
}
}
diff --git a/examples/Idempotency/test/HelloWorld.Test/HelloWorld.Tests.csproj b/examples/Idempotency/test/HelloWorld.Test/HelloWorld.Tests.csproj
index 544bd2b9..80aeda62 100644
--- a/examples/Idempotency/test/HelloWorld.Test/HelloWorld.Tests.csproj
+++ b/examples/Idempotency/test/HelloWorld.Test/HelloWorld.Tests.csproj
@@ -6,10 +6,10 @@
-
-
+
+
-
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive