repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Add_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Add_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse Add(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); var validationErrors = new List<string>(); var x = default(int); if (__request__.QueryStringParameters?.ContainsKey("x") == true) { try { x = (int)Convert.ChangeType(__request__.QueryStringParameters["x"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.QueryStringParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}"); } } var y = default(int); if (__request__.QueryStringParameters?.ContainsKey("y") == true) { try { y = (int)Convert.ChangeType(__request__.QueryStringParameters["y"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.QueryStringParameters["y"]} at 'y' failed to satisfy constraint: {e.Message}"); } } // return 400 Bad Request if there exists a validation error if (validationErrors.Any()) { var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}", Headers = new Dictionary<string, string> { {"Content-Type", "application/json"}, {"x-amzn-ErrorType", "ValidationException"} }, StatusCode = 400 }; return errorResult; } var response = simpleCalculator.Add(x, y); var body = response.ToString(); return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = body, Headers = new Dictionary<string, string> { {"Content-Type", "application/json"} }, StatusCode = 200 }; } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
111
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_DivideAsync_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_DivideAsync_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public async System.Threading.Tasks.Task<Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse> DivideAsync(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); var validationErrors = new List<string>(); var first = default(int); if (__request__.PathParameters?.ContainsKey("x") == true) { try { first = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}"); } } var second = default(int); if (__request__.PathParameters?.ContainsKey("y") == true) { try { second = (int)Convert.ChangeType(__request__.PathParameters["y"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.PathParameters["y"]} at 'y' failed to satisfy constraint: {e.Message}"); } } // return 400 Bad Request if there exists a validation error if (validationErrors.Any()) { var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}", Headers = new Dictionary<string, string> { {"Content-Type", "application/json"}, {"x-amzn-ErrorType", "ValidationException"} }, StatusCode = 400 }; return errorResult; } var response = await simpleCalculator.DivideAsync(first, second); var body = System.Text.Json.JsonSerializer.Serialize(response); return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = body, Headers = new Dictionary<string, string> { {"Content-Type", "application/json"} }, StatusCode = 200 }; } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
111
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Multiply_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Multiply_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse Multiply(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); var validationErrors = new List<string>(); var x = default(int); if (__request__.PathParameters?.ContainsKey("x") == true) { try { x = (int)Convert.ChangeType(__request__.PathParameters["x"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.PathParameters["x"]} at 'x' failed to satisfy constraint: {e.Message}"); } } var y = default(int); if (__request__.PathParameters?.ContainsKey("y") == true) { try { y = (int)Convert.ChangeType(__request__.PathParameters["y"], typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.PathParameters["y"]} at 'y' failed to satisfy constraint: {e.Message}"); } } // return 400 Bad Request if there exists a validation error if (validationErrors.Any()) { var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}", Headers = new Dictionary<string, string> { {"Content-Type", "application/json"}, {"x-amzn-ErrorType", "ValidationException"} }, StatusCode = 400 }; return errorResult; } var response = simpleCalculator.Multiply(x, y); return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = response, Headers = new Dictionary<string, string> { {"Content-Type", "text/plain"} }, StatusCode = 200 }; } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
109
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Pi_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Pi_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public double Pi() { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); var simpleCalculatorService = scope.ServiceProvider.GetRequiredService<TestServerlessApp.Services.ISimpleCalculatorService>(); return simpleCalculator.Pi(simpleCalculatorService); } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
56
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Randoms_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Randoms_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public System.Collections.Generic.IList<int> Randoms(TestServerlessApp.SimpleCalculator.RandomsInput input, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); return simpleCalculator.Randoms(input, __context__); } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
55
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Random_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Random_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public async System.Threading.Tasks.Task<int> Random(int maxValue, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); return await simpleCalculator.Random(maxValue, __context__); } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
55
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using Amazon.Lambda.Core; namespace TestServerlessApp { public class SimpleCalculator_Subtract_Generated { private readonly ServiceProvider serviceProvider; public SimpleCalculator_Subtract_Generated() { SetExecutionEnvironment(); var services = new ServiceCollection(); // By default, Lambda function class is added to the service container using the singleton lifetime // To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method. services.AddSingleton<SimpleCalculator>(); var startup = new TestServerlessApp.Startup(); startup.ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse Subtract(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__) { // Create a scope for every request, // this allows creating scoped dependencies without creating a scope manually. using var scope = serviceProvider.CreateScope(); var simpleCalculator = scope.ServiceProvider.GetRequiredService<SimpleCalculator>(); var validationErrors = new List<string>(); var x = default(int); if (__request__.Headers?.Any(x => string.Equals(x.Key, "x", StringComparison.OrdinalIgnoreCase)) == true) { try { x = (int)Convert.ChangeType(__request__.Headers.First(x => string.Equals(x.Key, "x", StringComparison.OrdinalIgnoreCase)).Value, typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.Headers.First(x => string.Equals(x.Key, "x", StringComparison.OrdinalIgnoreCase)).Value} at 'x' failed to satisfy constraint: {e.Message}"); } } var y = default(int); if (__request__.Headers?.Any(x => string.Equals(x.Key, "y", StringComparison.OrdinalIgnoreCase)) == true) { try { y = (int)Convert.ChangeType(__request__.Headers.First(x => string.Equals(x.Key, "y", StringComparison.OrdinalIgnoreCase)).Value, typeof(int)); } catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) { validationErrors.Add($"Value {__request__.Headers.First(x => string.Equals(x.Key, "y", StringComparison.OrdinalIgnoreCase)).Value} at 'y' failed to satisfy constraint: {e.Message}"); } } var simpleCalculatorService = scope.ServiceProvider.GetRequiredService<TestServerlessApp.Services.ISimpleCalculatorService>(); // return 400 Bad Request if there exists a validation error if (validationErrors.Any()) { var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse { Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}", Headers = new Dictionary<string, string> { {"Content-Type", "application/json"}, {"x-amzn-ErrorType", "ValidationException"} }, StatusCode = 400 }; return errorResult; } var response = simpleCalculator.Subtract(x, y, simpleCalculatorService); return response; } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
101
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Amazon.Lambda.Core; namespace TestServerlessApp { public class TaskExample_TaskReturn_Generated { private readonly TaskExample taskExample; public TaskExample_TaskReturn_Generated() { SetExecutionEnvironment(); taskExample = new TaskExample(); } public async System.Threading.Tasks.Task TaskReturn(string text, Amazon.Lambda.Core.ILambdaContext __context__) { await taskExample.TaskReturn(text, __context__); } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Amazon.Lambda.Core; namespace TestServerlessApp { public class VoidExample_VoidReturn_Generated { private readonly VoidExample voidExample; public VoidExample_VoidReturn_Generated() { SetExecutionEnvironment(); voidExample = new VoidExample(); } public void VoidReturn(string text, Amazon.Lambda.Core.ILambdaContext __context__) { voidExample.VoidReturn(text, __context__); } private static void SetExecutionEnvironment() { const string envName = "AWS_EXECUTION_ENV"; var envValue = new StringBuilder(); // If there is an existing execution environment variable add the annotations package as a suffix. if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) { envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); } envValue.Append("amazon-lambda-annotations_0.13.5.0"); Environment.SetEnvironmentVariable(envName, envValue.ToString()); } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.Annotations.SourceGenerator; using Amazon.Lambda.Annotations.SourceGenerator.Diagnostics; using Amazon.Lambda.Annotations.SourceGenerator.FileIO; using Amazon.Lambda.Annotations.SourceGenerator.Models; using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes; using Amazon.Lambda.Annotations.SourceGenerator.Writers; using Moq; using Newtonsoft.Json.Linq; using Xunit; namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.WriterTests { public class CloudFormationWriterTests { private readonly IDirectoryManager _directoryManager = new DirectoryManager(); private readonly IDiagnosticReporter _diagnosticReporter = new Mock<IDiagnosticReporter>().Object; private const string ProjectRootDirectory = "C:/CodeBase/MyProject"; private const string ServerlessTemplateFilePath = "C:/CodeBase/MyProject/serverless.template"; [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void AddSingletonFunctionToEmptyTemplate(CloudFormationTemplateFormat templateFormat) { // ARRANGE var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable>() {lambdaFunctionModel}); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); const string functionPath = "Resources.TestMethod"; const string propertiesPath = "Resources.TestMethod.Properties"; Assert.Equal("AWS::Serverless::Function", templateWriter.GetToken<string>($"{functionPath}.Type")); Assert.Equal("Amazon.Lambda.Annotations", templateWriter.GetToken<string>($"{functionPath}.Metadata.Tool")); Assert.Equal("MyAssembly::MyNamespace.MyType::Handler", templateWriter.GetToken<string>($"{propertiesPath}.Handler")); Assert.Equal(512, templateWriter.GetToken<int>($"{propertiesPath}.MemorySize")); Assert.Equal(45, templateWriter.GetToken<int>($"{propertiesPath}.Timeout")); Assert.Equal(new List<string> {"AWSLambdaBasicExecutionRole"}, templateWriter.GetToken<List<string>>($"{propertiesPath}.Policies")); Assert.Equal("Zip", templateWriter.GetToken<string>($"{propertiesPath}.PackageType")); Assert.Equal(".", templateWriter.GetToken<string>($"{propertiesPath}.CodeUri")); Assert.False(templateWriter.Exists("ImageUri")); Assert.False(templateWriter.Exists("ImageConfig")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void SwitchFromPolicyToRole(CloudFormationTemplateFormat templateFormat) { // ARRANGE var mockFileManager = GetMockFileManager(string.Empty); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); const string policiesPath = "Resources.TestMethod.Properties.Policies"; const string rolePath = "Resources.TestMethod.Properties.Role"; //ACT - USE POLICY var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, "Policy1, Policy2, Policy3"); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal(new List<string> {"Policy1", "Policy2", "Policy3"}, templateWriter.GetToken<List<string>>(policiesPath)); Assert.False(templateWriter.Exists(rolePath)); // ACT - SWITCH TO ROLE lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, "Basic", null); report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal("Basic", templateWriter.GetToken<string>(rolePath)); Assert.False(templateWriter.Exists(policiesPath)); // ACT - SWITCH BACK TO POLICY lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, "Policy1, Policy2, Policy3"); report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal(new List<string> {"Policy1", "Policy2", "Policy3"}, templateWriter.GetToken<List<string>>(policiesPath)); Assert.False(templateWriter.Exists(rolePath)); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void UseRefForPolicies(CloudFormationTemplateFormat templateFormat) { // ARRANGE var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, "Policy1, @Policy2, Policy3"); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); const string policiesPath = "Resources.TestMethod.Properties.Policies"; // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); var policies = templateWriter.GetToken<List<object>>(policiesPath); Assert.Equal(3, policies.Count); Assert.Equal("Policy1", policies[0]); if (templateFormat == CloudFormationTemplateFormat.Json) Assert.Equal("Policy2", ((JObject)policies[1])["Ref"]); else Assert.Equal("Policy2", ((Dictionary<object, object>)policies[1])["Ref"]); Assert.Equal("Policy3", policies[2]); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void UseRefForRole(CloudFormationTemplateFormat templateFormat) { // ARRANGE const string jsonContent = @"{ 'Parameters':{ 'Basic':{ 'Type':'String', } } }"; const string yamlContent = @"Parameters: Basic: Type: String"; ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); var content = templateFormat == CloudFormationTemplateFormat.Json ? jsonContent : yamlContent; var mockFileManager = GetMockFileManager(content); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, "@Basic", null); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT const string rolePath = "Resources.TestMethod.Properties.Role.Ref"; templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal("Basic", templateWriter.GetToken<string>(rolePath)); Assert.False(templateWriter.Exists("Resources.TestMethod.Properties.Role.Fn::GetAtt")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void UseFnGetForRole(CloudFormationTemplateFormat templateFormat) { ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, "@Basic", null); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT const string rolePath = "Resources.TestMethod.Properties.Role.Fn::GetAtt"; templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal(new List<string>{"Basic", "Arn"}, templateWriter.GetToken<List<string>>(rolePath)); Assert.False(templateWriter.Exists("Resources.TestMethod.Properties.Role.Ref")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void RenameFunction(CloudFormationTemplateFormat templateFormat) { // ARRANGE var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "OldName", 45, 512, "@Basic", null); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.True(templateWriter.Exists("Resources.OldName")); Assert.Equal("MyAssembly::MyNamespace.MyType::Handler", templateWriter.GetToken<string>("Resources.OldName.Properties.Handler")); // ACT - CHANGE NAME lambdaFunctionModel.ResourceName = "NewName"; cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.False(templateWriter.Exists("Resources.OldName")); Assert.True(templateWriter.Exists("Resources.NewName")); Assert.Equal("MyAssembly::MyNamespace.MyType::Handler", templateWriter.GetToken<string>("Resources.NewName.Properties.Handler")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void RemoveOrphanedLambdaFunctions(CloudFormationTemplateFormat templateFormat) { // ARRANGE const string yamlContent = @" AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: ObsoleteMethod: Type: AWS::Serverless::Function Metadata: Tool: Amazon.Lambda.Annotations Properties: Handler: MyAssembly::MyNamespace.MyType::Handler MethodNotCreatedFromAnnotationsPackage: Type: AWS::Serverless::Function Properties: Handler: MyAssembly::MyNamespace.MyType::Handler "; const string jsonContent = @"{ 'AWSTemplateFormatVersion': '2010-09-09', 'Transform': 'AWS::Serverless-2016-10-31', 'Resources': { 'ObsoleteMethod': { 'Type': 'AWS::Serverless::Function', 'Metadata': { 'Tool': 'Amazon.Lambda.Annotations' }, 'Properties': { 'Handler': 'MyAssembly::MyNamespace.MyType::Handler' } }, 'MethodNotCreatedFromAnnotationsPackage': { 'Type': 'AWS::Serverless::Function', 'Properties': { 'Handler': 'MyAssembly::MyNamespace.MyType::Handler' } } } }"; var content = templateFormat == CloudFormationTemplateFormat.Json ? jsonContent : yamlContent; ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); var mockFileManager = GetMockFileManager(content); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "NewMethod", 45, 512, null, null); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.False(templateWriter.Exists("Resources.ObsoleteMethod")); Assert.True(templateWriter.Exists("Resources.NewMethod")); Assert.True(templateWriter.Exists("Resources.MethodNotCreatedFromAnnotationsPackage")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void DoNotModifyFunctionWithoutRequiredMetadata(CloudFormationTemplateFormat templateFormat) { // ARRANGE const string jsonContent = @"{ 'AWSTemplateFormatVersion': '2010-09-09', 'Transform': 'AWS::Serverless-2016-10-31', 'Resources': { 'MethodNotCreatedFromAnnotationsPackage': { 'Type': 'AWS::Serverless::Function', 'Properties': { 'Runtime': 'dotnetcore3.1', 'CodeUri': '', 'MemorySize': 128, 'Timeout': 100, 'Policies': [ 'AWSLambdaBasicExecutionRole' ], 'Handler': 'MyAssembly::MyNamespace.MyType::Handler' } } } }"; const string yamlContent = @" AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MethodNotCreatedFromAnnotationsPackage: Type: AWS::Serverless::Function Properties: Runtime: dotnetcore3.1 CodeUri: '' MemorySize: 128 Timeout: 100 Policies: - AWSLambdaBasicExecutionRole Handler: MyAssembly::MyNamespace.MyType::Handler "; var content = templateFormat == CloudFormationTemplateFormat.Json ? jsonContent : yamlContent; ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); var mockFileManager = GetMockFileManager(content); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "MethodNotCreatedFromAnnotationsPackage", 45, 512, null, "Policy1, Policy2, Policy3"); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); const string resourcePath = "Resources.MethodNotCreatedFromAnnotationsPackage"; Assert.True(templateWriter.Exists(resourcePath)); Assert.Equal(128, templateWriter.GetToken<int>($"{resourcePath}.Properties.MemorySize")); Assert.Equal(100, templateWriter.GetToken<int>($"{resourcePath}.Properties.Timeout"));// unchanged var policies = templateWriter.GetToken<List<string>>($"{resourcePath}.Properties.Policies"); Assert.Equal(new List<string>{"AWSLambdaBasicExecutionRole"}, policies); // unchanged } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void EventAttributesTest(CloudFormationTemplateFormat templateFormat) { // ARRANGE - USE A HTTP GET METHOD var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var httpAttributeModel = new AttributeModel<HttpApiAttribute>() { Data = new HttpApiAttribute(LambdaHttpMethod.Get, "/Calculator/Add") { Version = HttpApiVersion.V1 } }; lambdaFunctionModel.Attributes = new List<AttributeModel>() {httpAttributeModel}; var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable>() {lambdaFunctionModel}); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); const string rootGetPath = "Resources.TestMethod.Properties.Events.RootGet"; Assert.True(templateWriter.Exists(rootGetPath)); Assert.Equal("HttpApi", templateWriter.GetToken<string>($"{rootGetPath}.Type")); Assert.Equal("/Calculator/Add", templateWriter.GetToken<string>($"{rootGetPath}.Properties.Path")); Assert.Equal("GET", templateWriter.GetToken<string>($"{rootGetPath}.Properties.Method")); Assert.Equal("1.0", templateWriter.GetToken<string>($"{rootGetPath}.Properties.PayloadFormatVersion")); // ARRANGE - CHANGE TO A HTTP POST METHOD httpAttributeModel = new AttributeModel<HttpApiAttribute>() { Data = new HttpApiAttribute(LambdaHttpMethod.Post, "/Calculator/Add") }; lambdaFunctionModel.Attributes = new List<AttributeModel>() {httpAttributeModel}; // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); const string rootPostPath = "Resources.TestMethod.Properties.Events.RootPost"; Assert.True(templateWriter.Exists(rootPostPath)); Assert.Equal("HttpApi", templateWriter.GetToken<string>($"{rootPostPath}.Type")); Assert.Equal("/Calculator/Add", templateWriter.GetToken<string>($"{rootPostPath}.Properties.Path")); Assert.Equal("POST", templateWriter.GetToken<string>($"{rootPostPath}.Properties.Method")); Assert.False(templateWriter.Exists($"{rootPostPath}.Properties.PayloadFormatVersion")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void PackageTypePropertyTest(CloudFormationTemplateFormat templateFormat) { // ARRANGE - Set PackageType to Zip var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); lambdaFunctionModel.PackageType = LambdaPackageType.Zip; var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable>() {lambdaFunctionModel}); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); const string propertiesPath = "Resources.TestMethod.Properties"; Assert.Equal("Zip", templateWriter.GetToken<string>($"{propertiesPath}.PackageType")); Assert.Equal(".", templateWriter.GetToken<string>($"{propertiesPath}.CodeUri")); Assert.Equal("MyAssembly::MyNamespace.MyType::Handler", templateWriter.GetToken<string>($"{propertiesPath}.Handler")); // ARRANGE - Change PackageType to Image lambdaFunctionModel.PackageType = LambdaPackageType.Image; report = GetAnnotationReport(new List<ILambdaFunctionSerializable>() {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal("Image", templateWriter.GetToken<string>($"{propertiesPath}.PackageType")); Assert.Equal(".", templateWriter.GetToken<string>($"{propertiesPath}.ImageUri")); Assert.Equal(new List<string>{"MyAssembly::MyNamespace.MyType::Handler"}, templateWriter.GetToken<List<string>>($"{propertiesPath}.ImageConfig.Command")); Assert.False(templateWriter.Exists($"{propertiesPath}.CodeUri")); Assert.False(templateWriter.Exists($"{propertiesPath}.Handler")); // ARRANGE - Change PackageType back to Zip lambdaFunctionModel.PackageType = LambdaPackageType.Zip; report = GetAnnotationReport(new List<ILambdaFunctionSerializable>() {lambdaFunctionModel}); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.Equal("Zip", templateWriter.GetToken<string>($"{propertiesPath}.PackageType")); Assert.Equal(".", templateWriter.GetToken<string>($"{propertiesPath}.CodeUri")); Assert.Equal("MyAssembly::MyNamespace.MyType::Handler", templateWriter.GetToken<string>($"{propertiesPath}.Handler")); Assert.False(templateWriter.Exists($"{propertiesPath}.ImageUri")); Assert.False(templateWriter.Exists($"{propertiesPath}.ImageConfig")); } [Theory] [InlineData(CloudFormationTemplateFormat.Json)] [InlineData(CloudFormationTemplateFormat.Yaml)] public void CodeUriTest(CloudFormationTemplateFormat templateFormat) { // ARRANGE var mockFileManager = GetMockFileManager(string.Empty); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); lambdaFunctionModel.PackageType = LambdaPackageType.Zip; var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); // ARRANGE - CloudFormation template is inside project root directory var projectRoot = Path.Combine("C:", "src", "serverlessApp"); var cloudFormationTemplatePath = Path.Combine(projectRoot, "templates", "serverless.template"); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable>{lambdaFunctionModel}, projectRoot, cloudFormationTemplatePath); ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT - CodeUri is relative to CloudFormation template directory templateWriter.Parse(mockFileManager.ReadAllText(cloudFormationTemplatePath)); const string propertiesPath = "Resources.TestMethod.Properties"; Assert.Equal("..", templateWriter.GetToken<string>($"{propertiesPath}.CodeUri")); // ARRANGE - CloudFormation template is above project root directory projectRoot = Path.Combine("C:", "src", "serverlessApp"); cloudFormationTemplatePath = Path.Combine(projectRoot, "..", "serverless.template"); report = GetAnnotationReport(new List<ILambdaFunctionSerializable>{lambdaFunctionModel}, projectRoot, cloudFormationTemplatePath); // ACT cloudFormationWriter.ApplyReport(report); // ASSERT - CodeUri is relative to CloudFormation template directory templateWriter.Parse(mockFileManager.ReadAllText(cloudFormationTemplatePath)); Assert.Equal("serverlessApp", templateWriter.GetToken<string>($"{propertiesPath}.CodeUri")); } #region CloudFormation template description /// <summary> /// Tests that the CloudFormation template's "Description" field is set /// correctly for an entirely new template. /// </summary> [Theory] [InlineData(CloudFormationTemplateFormat.Json, false)] [InlineData(CloudFormationTemplateFormat.Json, true)] [InlineData(CloudFormationTemplateFormat.Yaml, false)] [InlineData(CloudFormationTemplateFormat.Yaml, true)] public void TemplateDescription_NewTemplate(CloudFormationTemplateFormat templateFormat, bool isTelemetrySuppressed) { ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); var mockFileManager = GetMockFileManager(string.Empty); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, templateFormat, _diagnosticReporter); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> { lambdaFunctionModel }, isTelemetrySuppressed: isTelemetrySuppressed); cloudFormationWriter.ApplyReport(report); templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); if (isTelemetrySuppressed) { Assert.False(templateWriter.Exists("Description")); } else { Assert.True(templateWriter.Exists("Description")); Assert.Equal(CloudFormationWriter.CurrentDescriptionSuffix, templateWriter.GetToken<string>("Description")); } } /// <summary> /// Tests that the CloudFormation template's "Description" field is set /// correctly for an existing template without a Description field. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TemplateDescription_ExistingTemplateNoDescription_Json(bool isTelemetrySuppressed) { const string content = @"{ 'AWSTemplateFormatVersion': '2010-09-09', 'Transform': 'AWS::Serverless-2016-10-31', 'Resources': { 'MethodNotCreatedFromAnnotationsPackage': { 'Type': 'AWS::Serverless::Function', 'Properties': { 'Runtime': 'dotnetcore3.1', 'CodeUri': '', 'MemorySize': 128, 'Timeout': 100, 'Policies': [ 'AWSLambdaBasicExecutionRole' ], 'Handler': 'MyAssembly::MyNamespace.MyType::Handler' } } } }"; var templateWriter = new JsonWriter(); var mockFileManager = GetMockFileManager(content); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, CloudFormationTemplateFormat.Json, _diagnosticReporter); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> { lambdaFunctionModel }, isTelemetrySuppressed: isTelemetrySuppressed); cloudFormationWriter.ApplyReport(report); templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); if (isTelemetrySuppressed) { Assert.False(templateWriter.Exists("Description")); } else { Assert.True(templateWriter.Exists("Description")); Assert.Equal(CloudFormationWriter.CurrentDescriptionSuffix, templateWriter.GetToken<string>("Description")); } } /// <summary> /// Tests that the CloudFormation template's "Description" field is set /// correctly for an existing template without a Description field. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TemplateDescription_ExistingTemplateNoDescription_Yaml(bool isTelemetrySuppressed) { const string content = @" AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MethodNotCreatedFromAnnotationsPackage: Type: AWS::Serverless::Function Properties: Runtime: dotnetcore3.1 CodeUri: '' MemorySize: 128 Timeout: 100 Policies: - AWSLambdaBasicExecutionRole Handler: MyAssembly::MyNamespace.MyType::Handler "; var templateWriter = new YamlWriter(); var mockFileManager = GetMockFileManager(content); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, CloudFormationTemplateFormat.Yaml, _diagnosticReporter); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> { lambdaFunctionModel }, isTelemetrySuppressed: isTelemetrySuppressed); cloudFormationWriter.ApplyReport(report); templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); if (isTelemetrySuppressed) { Assert.False(templateWriter.Exists("Description")); } else { Assert.True(templateWriter.Exists("Description")); Assert.Equal(CloudFormationWriter.CurrentDescriptionSuffix, templateWriter.GetToken<string>("Description")); } } /// <summary> /// Test cases for manipulating the CloudFormation template description if it already has a value /// </summary> public static IEnumerable<object[]> CloudFormationDescriptionCases => new List<object[]> { /* * This first set are without the opt-out flag */ // A blank description should be transformed to just our suffix new object[] { "", false, CloudFormationWriter.CurrentDescriptionSuffix }, // An existing description that is entirely our suffix should be replaced by the current version new object[] { "This template is partially managed by Amazon.Lambda.Annotations (v0.1).", false, CloudFormationWriter.CurrentDescriptionSuffix }, // An existing description should have our version appended to it new object[] { "Existing description before", false, $"Existing description before {CloudFormationWriter.CurrentDescriptionSuffix}" }, // An existing description with our version in the front should be replaced new object[] { "This template is partially managed by Amazon.Lambda.Annotations (v0.1). Existing description.", false, $"{CloudFormationWriter.CurrentDescriptionSuffix} Existing description." }, // An existing description with our version in the front should be replaced new object[] { "PREFIX This template is partially managed by Amazon.Lambda.Annotations (v0.1). SUFFIX", false, $"PREFIX {CloudFormationWriter.CurrentDescriptionSuffix} SUFFIX" }, // This would exceed CloudFormation's current limit on the description field, so should not be modified new object[] { new string('-', 1000), false, new string('-', 1000)}, /* * The remaining cases are with the opt-out flag set to true, which should remove any version descriptions */ // A blank description should be left alone new object[] { "", true, "" }, // A non-blank description without our version description should be left alone new object[] { "An AWS Serverless Application.", true, "An AWS Serverless Application." }, // An existing description that is entirely our suffix should be cleared new object[] { "This template is partially managed by Amazon.Lambda.Annotations (v0.1).", true, "" }, // An existing description with our version suffix should have it removed new object[] { "Existing description. This template is partially managed by Amazon.Lambda.Annotations (v0.1).", true, "Existing description. " }, // An existing description with our version in the front should have it removed new object[] { "This template is partially managed by Amazon.Lambda.Annotations (v0.1). Existing description.", true, " Existing description." }, // An existing description with our version in the front should be replaced new object[] { "PREFIX This template is partially managed by Amazon.Lambda.Annotations (v0.1). SUFFIX", true, $"PREFIX SUFFIX" } }; /// <summary> /// Tests that the CloudFormation template's "Description" field is set /// correctly for an existing template without a Description field. /// </summary> [Theory] [MemberData(nameof(CloudFormationDescriptionCases))] public void TemplateDescription_ExistingDescription_Json(string originalDescription, bool isTelemetrySuppressed, string expectedDescription) { string content = @"{ 'AWSTemplateFormatVersion': '2010-09-09', 'Transform': 'AWS::Serverless-2016-10-31', 'Description': '" + originalDescription + @"', 'Resources': { 'MethodNotCreatedFromAnnotationsPackage': { 'Type': 'AWS::Serverless::Function', 'Properties': { 'Runtime': 'dotnetcore3.1', 'CodeUri': '', 'MemorySize': 128, 'Timeout': 100, 'Policies': [ 'AWSLambdaBasicExecutionRole' ], 'Handler': 'MyAssembly::MyNamespace.MyType::Handler' } } } }"; var templateWriter = new JsonWriter(); var mockFileManager = GetMockFileManager(content); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, CloudFormationTemplateFormat.Json, _diagnosticReporter); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> { lambdaFunctionModel }, isTelemetrySuppressed: isTelemetrySuppressed); cloudFormationWriter.ApplyReport(report); templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.True(templateWriter.Exists("Description")); Assert.Equal(expectedDescription, templateWriter.GetToken<string>("Description")); } /// <summary> /// Tests that the CloudFormation template's "Description" field is set /// correctly for an existing template without a Description field. /// </summary> [Theory] [MemberData(nameof(CloudFormationDescriptionCases))] public void TemplateDescription_ExistingDescription_Yaml(string originalDescription, bool isTelemetrySuppressed, string expectedDescription) { // ARRANGE string content = @" AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: " + originalDescription + @" Resources: MethodNotCreatedFromAnnotationsPackage: Type: AWS::Serverless::Function Properties: Runtime: dotnetcore3.1 CodeUri: '' MemorySize: 128 Timeout: 100 Policies: - AWSLambdaBasicExecutionRole Handler: MyAssembly::MyNamespace.MyType::Handler "; var templateWriter = new YamlWriter(); var mockFileManager = GetMockFileManager(content); var cloudFormationWriter = GetCloudFormationWriter(mockFileManager, _directoryManager, CloudFormationTemplateFormat.Yaml, _diagnosticReporter); var lambdaFunctionModel = GetLambdaFunctionModel("MyAssembly::MyNamespace.MyType::Handler", "TestMethod", 45, 512, null, null); var report = GetAnnotationReport(new List<ILambdaFunctionSerializable> { lambdaFunctionModel }, isTelemetrySuppressed: isTelemetrySuppressed); cloudFormationWriter.ApplyReport(report); templateWriter.Parse(mockFileManager.ReadAllText(ServerlessTemplateFilePath)); Assert.True(templateWriter.Exists("Description")); Assert.Equal(expectedDescription, templateWriter.GetToken<string>("Description")); } #endregion private IFileManager GetMockFileManager(string originalContent) { var mockFileManager = new InMemoryFileManager(); mockFileManager.WriteAllText(ServerlessTemplateFilePath, originalContent); return mockFileManager; } private LambdaFunctionModelTest GetLambdaFunctionModel(string handler, string resourceName, uint? timeout, uint? memorySize, string role, string policies) { return new LambdaFunctionModelTest { Handler = handler, ResourceName = resourceName, MemorySize = memorySize, Timeout = timeout, Policies = policies, Role = role }; } private AnnotationReport GetAnnotationReport(List<ILambdaFunctionSerializable> lambdaFunctionModels, string projectRootDirectory = ProjectRootDirectory, string cloudFormationTemplatePath = ServerlessTemplateFilePath, bool isTelemetrySuppressed = false) { var annotationReport = new AnnotationReport { CloudFormationTemplatePath = cloudFormationTemplatePath, ProjectRootDirectory = projectRootDirectory, IsTelemetrySuppressed = isTelemetrySuppressed }; foreach (var model in lambdaFunctionModels) { annotationReport.LambdaFunctions.Add(model); } return annotationReport; } private CloudFormationWriter GetCloudFormationWriter(IFileManager fileManager, IDirectoryManager directoryManager, CloudFormationTemplateFormat templateFormat, IDiagnosticReporter diagnosticReporter) { ITemplateWriter templateWriter = templateFormat == CloudFormationTemplateFormat.Json ? new JsonWriter() : new YamlWriter(); return new CloudFormationWriter(fileManager, directoryManager, templateWriter, diagnosticReporter); } public class LambdaFunctionModelTest : ILambdaFunctionSerializable { public string Handler { get; set; } public string ResourceName { get; set; } public uint? Timeout { get; set; } public uint? MemorySize { get; set; } public string Role { get; set; } public string Policies { get; set; } public IList<AttributeModel> Attributes { get; set; } = new List<AttributeModel>(); public string SourceGeneratorVersion { get; set; } public LambdaPackageType PackageType { get; set; } = LambdaPackageType.Zip; } } }
836
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.IO; using Amazon.Lambda.Annotations.SourceGenerator.FileIO; namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.WriterTests { public class InMemoryFileManager : IFileManager { private readonly IDictionary<string, string> _cacheContent; public InMemoryFileManager() { _cacheContent = new Dictionary<string, string>(); } public string ReadAllText(string path) { return _cacheContent.TryGetValue(path, out var content) ? content : null; } public void WriteAllText(string path, string contents) => _cacheContent[path] = contents; public bool Exists(string path) => throw new System.NotImplementedException(); public FileStream Create(string path) => throw new System.NotImplementedException(); } }
27
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using Amazon.Lambda.Annotations.SourceGenerator.Writers; using Newtonsoft.Json.Linq; using Xunit; namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.WriterTests { public class JsonWriterTests { private const string SampleJsonString = @"{ 'Person':{ 'Name':{ 'FirstName':'John', 'LastName':'Smith' }, 'Gender':'male', 'Age':32, 'PhoneNumbers':[ '123', '456', '789' ] } }"; [Fact] public void Exists() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); jsonWriter.Parse(SampleJsonString); // ACT and ASSERT Assert.True(jsonWriter.Exists("Person.Name.FirstName")); Assert.True(jsonWriter.Exists("Person.PhoneNumbers")); Assert.True(jsonWriter.Exists("Person.Gender")); Assert.False(jsonWriter.Exists("Person.Weight")); Assert.False(jsonWriter.Exists("Person.Name.MiddleName")); Assert.Throws<InvalidDataException>(() => jsonWriter.Exists("Person..Name.FirstName")); Assert.Throws<InvalidDataException>(() => jsonWriter.Exists(" ")); Assert.Throws<InvalidDataException>(() => jsonWriter.Exists("...")); Assert.Throws<InvalidDataException>(() => jsonWriter.Exists("")); } [Fact] public void SetToken() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); // ACT jsonWriter.SetToken("Person.Name.FirstName", "ABC"); jsonWriter.SetToken("Person.Name.LastName", "XYZ"); jsonWriter.SetToken("Person.Age", 50); jsonWriter.SetToken("Person.DOB", new DateTime(2000, 1, 1)); jsonWriter.SetToken("Person.PhoneNumbers", new List<string> { "123", "456", "789" }, TokenType.List); // ASSERT var firstName = jsonWriter.GetToken<string>("Person.Name.FirstName"); var lastName = jsonWriter.GetToken<string>("Person.Name.LastName"); var age = jsonWriter.GetToken<int>("Person.Age"); var dob = jsonWriter.GetToken<DateTime>("Person.DOB"); var phoneNumbers = jsonWriter.GetToken<List<string>>("Person.PhoneNumbers"); Assert.Equal("ABC", firstName); Assert.Equal("XYZ", lastName); Assert.Equal(50, age); Assert.Equal(new DateTime(2000, 1, 1), dob); Assert.Equal(new List<string> { "123", "456", "789" }, phoneNumbers); Assert.Throws<InvalidOperationException>(() => jsonWriter.SetToken("Person.PhoneNumbers.Mobile", "789")); Assert.Throws<InvalidOperationException>(() => jsonWriter.SetToken("Person.Name.FirstName.MiddleName", "PQR")); } [Fact] public void GetToken() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); jsonWriter.Parse(SampleJsonString); // ACT var firstName = jsonWriter.GetToken<string>("Person.Name.FirstName"); var lastName = jsonWriter.GetToken<string>("Person.Name.LastName"); var gender = jsonWriter.GetToken<string>("Person.Gender"); var age = jsonWriter.GetToken<int>("Person.Age"); var phoneNumbers = jsonWriter.GetToken<List<string>>("Person.PhoneNumbers"); // ASSERT Assert.Equal("John", firstName); Assert.Equal("Smith", lastName); Assert.Equal("male", gender); Assert.Equal(32, age); Assert.Equal(new List<string> {"123", "456", "789"}, phoneNumbers); Assert.Throws<InvalidOperationException>(() => jsonWriter.GetToken("Person.Weight")); Assert.Throws<InvalidOperationException>(() => jsonWriter.GetToken("Person.Name.MiddleName")); } [Fact] public void RemoveToken() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); jsonWriter.Parse(SampleJsonString); // ACT jsonWriter.RemoveToken("Person.Name.LastName"); jsonWriter.RemoveToken("Person.Name.Age"); // ASSERT Assert.False(jsonWriter.Exists("Person.Name.LastName")); Assert.False(jsonWriter.Exists("Person.Name.Age")); Assert.True(jsonWriter.Exists("Person.Name.FirstName")); Assert.True(jsonWriter.Exists("Person.Gender")); Assert.True(jsonWriter.Exists("Person.PhoneNumbers")); } [Fact] public void GetContent() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); jsonWriter.SetToken("Person.Name.FirstName", "John"); jsonWriter.SetToken("Person.Name.LastName", "Smith"); jsonWriter.SetToken("Person.Age", 50); jsonWriter.SetToken("Person.PhoneNumbers", new List<int> { 1, 2, 3 }, TokenType.List); jsonWriter.SetToken("Person.Address", new Dictionary<string, string> { { "City", "AmazingCity" }, { "State", "AmazingState" } }, TokenType.KeyVal); jsonWriter.SetToken("Person.IsAlive", true); // ACT var actualSnapshot = jsonWriter.GetContent(); // ASSERT var expectedSnapshot = File.ReadAllText(Path.Combine("WriterTests", "snapshot.json")); actualSnapshot = SanitizeFileContents(actualSnapshot); expectedSnapshot = SanitizeFileContents(expectedSnapshot); Assert.Equal(expectedSnapshot, actualSnapshot); } [Fact] public void GetValueOrRef() { // ARRANGE ITemplateWriter jsonWriter = new JsonWriter(); // ACT var stringVal = jsonWriter.GetValueOrRef("Hello"); var refNode = (JObject)jsonWriter.GetValueOrRef("@Hello"); Assert.Equal("Hello", stringVal); Assert.Equal("Hello", refNode["Ref"]); } private string SanitizeFileContents(string content) { return content.Replace("\r\n", Environment.NewLine) .Replace("\n", Environment.NewLine) .Replace("\r\r\n", Environment.NewLine) .Trim(); } } }
164
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations.SourceGenerator; using Amazon.Lambda.Annotations.SourceGenerator.FileIO; using Moq; using Xunit; namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.WriterTests { /// <summary> /// Tests for <see cref="ProjectFileHandler"/> /// </summary> public class ProjectFileHandlerTests { /// <summary> /// Asserts that the project is not opted out of description modification when the element is not present /// </summary> [Fact] public void IsNotOptedOut() { var csprojContent = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> </Project>"; var mockFileManager = new Mock<IFileManager>(); mockFileManager.Setup(m => m.ReadAllText(It.IsAny<string>())).Returns(csprojContent); Assert.False(ProjectFileHandler.IsTelemetrySuppressed("test.csproj", mockFileManager.Object)); } /// <summary> /// Asserts that the project is opted out of description modification when the element is present and true /// </summary> [Fact] public void IsOptedOut() { var csprojContent = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <AWSSuppressLambdaAnnotationsTelemetry>true</AWSSuppressLambdaAnnotationsTelemetry> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> </Project>"; var mockFileManager = new Mock<IFileManager>(); mockFileManager.Setup(m => m.ReadAllText(It.IsAny<string>())).Returns(csprojContent); Assert.True(ProjectFileHandler.IsTelemetrySuppressed("test.csproj", mockFileManager.Object)); } /// <summary> /// Asserts that the project is not opted out of description modification when the element is present but has no inner text /// </summary> [Fact] public void IsNotOptedOut_PresentButEmpty() { var csprojContent = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <AWSSuppressLambdaAnnotationsTelemetry/> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> </Project>"; var mockFileManager = new Mock<IFileManager>(); mockFileManager.Setup(m => m.ReadAllText(It.IsAny<string>())).Returns(csprojContent); Assert.False(ProjectFileHandler.IsTelemetrySuppressed(csprojContent, mockFileManager.Object)); } /// <summary> /// Asserts that the project is not opted out of description modification when the element is present but is set to false /// </summary> [Fact] public void IsNotOptedOut_PresentButFalse() { var csprojContent = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <AWSProjectType>Lambda</AWSProjectType> <AWSSuppressLambdaAnnotationsTelemetry>false</AWSSuppressLambdaAnnotationsTelemetry> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> </Project>"; var mockFileManager = new Mock<IFileManager>(); mockFileManager.Setup(m => m.ReadAllText(It.IsAny<string>())).Returns(csprojContent); Assert.False(ProjectFileHandler.IsTelemetrySuppressed(csprojContent, mockFileManager.Object)); } } }
101
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using Amazon.Lambda.Annotations.SourceGenerator.Writers; using Xunit; using YamlDotNet.RepresentationModel; namespace Amazon.Lambda.Annotations.SourceGenerators.Tests.WriterTests { public class YamlWriterTests { const string yamlContent = @" Description: !Sub '${AWS::Region}' Person: Name: FirstName: John LastName: Smith Gender: male Age: 32 PhoneNumbers: - '123' - '456' - '789' "; [Fact] public void Exists() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.Parse(yamlContent); // ACT and ASSERT Assert.True(yamlWriter.Exists("Description")); Assert.True(yamlWriter.Exists("Person")); Assert.True(yamlWriter.Exists("Person.Name")); Assert.True(yamlWriter.Exists("Person.Name.LastName")); Assert.True(yamlWriter.Exists("Person.Age")); Assert.True(yamlWriter.Exists("Person.PhoneNumbers")); Assert.False(yamlWriter.Exists("description")); Assert.False(yamlWriter.Exists("person")); Assert.False(yamlWriter.Exists("Person.FirstName")); Assert.False(yamlWriter.Exists("Person.DOB")); Assert.False(yamlWriter.Exists("Person.Name.MiddleName")); Assert.Throws<InvalidDataException>(() => yamlWriter.Exists("Person..Name.FirstName")); Assert.Throws<InvalidDataException>(() => yamlWriter.Exists(" ")); Assert.Throws<InvalidDataException>(() => yamlWriter.Exists("...")); Assert.Throws<InvalidDataException>(() => yamlWriter.Exists("")); } [Fact] public void GetToken() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.Parse(yamlContent); // ACT var firstName = yamlWriter.GetToken<string>("Person.Name.FirstName"); var lastName = yamlWriter.GetToken<string>("Person.Name.LastName"); var gender = yamlWriter.GetToken<string>("Person.Gender"); var age = yamlWriter.GetToken<int>("Person.Age"); var phoneNumbers = yamlWriter.GetToken<List<string>>("Person.PhoneNumbers"); // ASSERT Assert.Equal("John", firstName); Assert.Equal("Smith", lastName); Assert.Equal("male", gender); Assert.Equal(32, age); Assert.Equal(new List<string> { "123", "456", "789" }, phoneNumbers); Assert.Throws<InvalidOperationException>(() => yamlWriter.GetToken("Person.Weight")); Assert.Throws<InvalidOperationException>(() => yamlWriter.GetToken("Person.Name.MiddleName")); } [Fact] public void SetToken() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.Parse(yamlContent); // ACT yamlWriter.SetToken("Person.Name.FirstName", "ABC"); yamlWriter.SetToken("Person.Name.MiddleName", "Blah"); yamlWriter.SetToken("Person.Name.LastName", "XYZ"); yamlWriter.SetToken("Person.Age", 50); yamlWriter.SetToken("Person.DOB", new DateTime(2000, 1, 1)); yamlWriter.SetToken("Person.PhoneNumbers", new List<int> { 1, 2, 3 }, TokenType.List); yamlWriter.SetToken("Person.Address", new Dictionary<string, string> { { "City", "AmazingCity" }, { "State", "AmazingState" } }, TokenType.KeyVal); yamlWriter.SetToken("Person.IsAlive", true); // ASSERT Assert.Equal("ABC", yamlWriter.GetToken<string>("Person.Name.FirstName")); Assert.Equal("Blah", yamlWriter.GetToken<string>("Person.Name.MiddleName")); Assert.Equal("XYZ", yamlWriter.GetToken<string>("Person.Name.LastName")); Assert.Equal(50, yamlWriter.GetToken<int>("Person.Age")); Assert.Equal(new DateTime(2000, 1, 1), yamlWriter.GetToken<DateTime>("Person.DOB")); Assert.Equal(new List<int> { 1, 2, 3 }, yamlWriter.GetToken<List<int>>("Person.PhoneNumbers")); Assert.True(yamlWriter.GetToken<bool>("Person.IsAlive")); Assert.Equal("AmazingCity", yamlWriter.GetToken<string>("Person.Address.City")); Assert.Equal("AmazingState", yamlWriter.GetToken<string>("Person.Address.State")); Assert.Throws<InvalidOperationException>(() => yamlWriter.SetToken("Person.PhoneNumbers.Mobile", 10)); Assert.Throws<InvalidOperationException>(() => yamlWriter.SetToken("Person.Name.FirstName.MiddleName", "PQR")); } [Fact] public void RemoveToken() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.Parse(yamlContent); // ACT yamlWriter.RemoveToken("Description"); yamlWriter.RemoveToken("Person.Name.LastName"); yamlWriter.RemoveToken("Person.Age"); // ASSERT Assert.False(yamlWriter.Exists("Description")); Assert.False(yamlWriter.Exists("Person.Name.LastName")); Assert.False(yamlWriter.Exists("Person.Age")); Assert.True(yamlWriter.Exists("Person.Name")); Assert.True(yamlWriter.Exists("Person.Name.FirstName")); } [Fact] public void GetContent() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.SetToken("Person.Name.FirstName", "John"); yamlWriter.SetToken("Person.Name.LastName", "Smith"); yamlWriter.SetToken("Person.Age", 50); yamlWriter.SetToken("Person.PhoneNumbers", new List<int> { 1, 2, 3 }, TokenType.List); yamlWriter.SetToken("Person.Address", new Dictionary<string, string> { { "City", "AmazingCity" }, { "State", "AmazingState" } }, TokenType.KeyVal); yamlWriter.SetToken("Person.IsAlive", true); // ACT var actualSnapshot = yamlWriter.GetContent(); // ASSERT var expectedSnapshot = File.ReadAllText(Path.Combine("WriterTests", "snapshot.yaml")); actualSnapshot = SanitizeFileContents(actualSnapshot); expectedSnapshot = SanitizeFileContents(expectedSnapshot); Assert.Equal(expectedSnapshot, actualSnapshot); } [Fact] public void GetValueOrRef() { // ARRANGE ITemplateWriter yamlWriter = new YamlWriter(); // ACT var stringVal = yamlWriter.GetValueOrRef("Hello"); var refNode = (YamlMappingNode)yamlWriter.GetValueOrRef("@Hello"); Assert.Equal("Hello", stringVal); Assert.Equal("Hello", refNode.Children["Ref"]); } private string SanitizeFileContents(string content) { return content.Replace("\r\n", Environment.NewLine) .Replace("\n", Environment.NewLine) .Replace("\r\r\n", Environment.NewLine) .Trim(); } [Fact] public void GetKeys() { // ARRANGE const string yamlContent = @" Resources: Function1: Description: Fn::Sub: - '${var1}' - var1: Test Function2: Description: !Sub '${AWS::Region}' "; ITemplateWriter yamlWriter = new YamlWriter(); yamlWriter.Parse(yamlContent); // ACT var functionNames = yamlWriter.GetKeys("Resources"); var function1Keys = yamlWriter.GetKeys("Resources.Function1"); // ASSERT Assert.NotEmpty(functionNames); Assert.Equal(2, functionNames.Count); Assert.Equal("Function1", functionNames[0]); Assert.Equal("Function2", functionNames[1]); Assert.NotEmpty(function1Keys); var description = Assert.Single(function1Keys); Assert.Equal("Description", description); Assert.Throws<InvalidOperationException>(() => { yamlWriter.GetKeys("Resources.Function2"); }); } } }
203
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TestWebApp; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class TestApiGatewayHttpApiV2Calls { [Fact] public async Task TestValuesGetAllFromBetaStage() { var context = new TestLambdaContext(); var response = await this.InvokeAPIGatewayRequest(context, "values-get-all-httpapi-v2-with-stage.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]); Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString()); } [Fact] public async Task TestGetBinaryContent() { var response = await this.InvokeAPIGatewayRequest("values-get-binary-httpapi-v2-request.json"); Assert.Equal((int)HttpStatusCode.OK, response.StatusCode); string contentType; Assert.True(response.Headers.TryGetValue("Content-Type", out contentType), "Content-Type response header exists"); Assert.Equal("application/octet-stream", contentType); Assert.NotNull(response.Body); Assert.True(response.Body.Length > 0, "Body content is not empty"); Assert.True(response.IsBase64Encoded, "Response IsBase64Encoded"); // Compute a 256-byte array, with values 0-255 var binExpected = new byte[byte.MaxValue].Select((val, index) => (byte)index).ToArray(); var binActual = Convert.FromBase64String(response.Body); Assert.Equal(binExpected, binActual); } [Fact] public async Task TestEncodePlusInResourcePath() { var response = await this.InvokeAPIGatewayRequest("encode-plus-in-resource-path-httpapi-v2.json"); Assert.Equal(200, response.StatusCode); var root = JObject.Parse(response.Body); Assert.Equal("/foo+bar", root["Path"]?.ToString()); } [Fact] public async Task TestGetQueryStringValueMV() { var response = await this.InvokeAPIGatewayRequest("values-get-querystring-httpapi-v2-mv-request.json"); Assert.Equal("value1,value2", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestGetEncodingQueryStringGateway() { var response = await this.InvokeAPIGatewayRequest("values-get-querystring-httpapi-v2-encoding-request.json"); var results = JsonConvert.DeserializeObject<TestWebApp.Controllers.RawQueryStringController.Results>(response.Body); Assert.Equal("http://www.google.com", results.Url); Assert.Equal(DateTimeOffset.Parse("2019-03-12T16:06:06.549817+00:00"), results.TestDateTimeOffset); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestPutWithBody() { var response = await this.InvokeAPIGatewayRequest("values-put-withbody-httpapi-v2-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("Agent, Smith", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestDefaultResponseErrorCode() { var response = await this.InvokeAPIGatewayRequest("values-get-error-httpapi-v2-request.json"); Assert.Equal(500, response.StatusCode); Assert.Equal(string.Empty, response.Body); } [Theory] [InlineData("values-get-aggregateerror-httpapi-v2-request.json", "AggregateException", true)] [InlineData("values-get-typeloaderror-httpapi-v2-request.json", "ReflectionTypeLoadException", true)] [InlineData("values-get-aggregateerror-httpapi-v2-request.json", "AggregateException", false)] [InlineData("values-get-typeloaderror-httpapi-v2-request.json", "ReflectionTypeLoadException", false)] public async Task TestEnhancedExceptions(string requestFileName, string expectedExceptionType, bool configureApiToReturnExceptionDetail) { var response = await this.InvokeAPIGatewayRequest(requestFileName, configureApiToReturnExceptionDetail); Assert.Equal(500, response.StatusCode); Assert.Equal(string.Empty, response.Body); if (configureApiToReturnExceptionDetail) { Assert.True(response.Headers.ContainsKey("ErrorType")); Assert.Equal(expectedExceptionType, response.Headers["ErrorType"]); } else { Assert.False(response.Headers.ContainsKey("ErrorType")); } } [Fact] public async Task TestGettingSwaggerDefinition() { var response = await this.InvokeAPIGatewayRequest("swagger-get-httpapi-v2-request.json"); Assert.Equal(200, response.StatusCode); Assert.True(response.Body.Length > 0); Assert.Equal("application/json", response.Headers["Content-Type"]); } [Fact] public async Task TestEncodeSpaceInResourcePath() { var response = await this.InvokeAPIGatewayRequest("encode-space-in-resource-path-httpapi-v2.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("value=tmh/file name.xml", response.Body); } [Fact] public async Task TestEncodeSlashInResourcePath() { var requestStr = GetRequestContent("encode-slash-in-resource-path-httpapi-v2.json"); var response = await this.InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr); Assert.Equal(200, response.StatusCode); Assert.Equal("{\"only\":\"a%2Fb\"}", response.Body); response = await this.InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr.Replace("a%2Fb", "a/b")); Assert.Equal(200, response.StatusCode); Assert.Equal("{\"first\":\"a\",\"second\":\"b\"}", response.Body); } [Fact] public async Task TestTrailingSlashInPath() { var response = await this.InvokeAPIGatewayRequest("trailing-slash-in-path-httpapi-v2.json"); Assert.Equal(200, response.StatusCode); var root = JObject.Parse(response.Body); Assert.Equal("/beta", root["PathBase"]?.ToString()); Assert.Equal("/foo/", root["Path"]?.ToString()); } [Theory] [InlineData("rawtarget-escaped-percent-in-path-httpapi-v2.json", "/foo%25bar")] [InlineData("rawtarget-escaped-percent-slash-in-path-httpapi-v2.json", "/foo%25%2Fbar")] [InlineData("rawtarget-escaped-reserved-in-query-httpapi-v2.json", "/foo/bar?foo=b%40r")] [InlineData("rawtarget-escaped-slash-in-path-httpapi-v2.json", "/foo%2Fbar")] public async Task TestRawTarget(string requestFileName, string expectedRawTarget) { var response = await this.InvokeAPIGatewayRequest(requestFileName); Assert.Equal(200, response.StatusCode); var root = JObject.Parse(response.Body); Assert.Equal(expectedRawTarget, root["RawTarget"]?.ToString()); } [Fact] public async Task TestAuthTestAccess() { var response = await this.InvokeAPIGatewayRequest("authtest-access-request-httpapi-v2.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("You Have Access", response.Body); } [Fact] public async Task TestAuthTestNoAccess() { var response = await this.InvokeAPIGatewayRequest("authtest-noaccess-request-httpapi-v2.json"); Assert.NotEqual(200, response.StatusCode); } [Fact] public async Task TestAuthMTls() { var response = await this.InvokeAPIGatewayRequest("mtls-request-httpapi-v2.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("O=Internet Widgits Pty Ltd, S=Some-State, C=AU", response.Body); } [Fact] public async Task TestReturningCookie() { var response = await this.InvokeAPIGatewayRequest("cookies-get-returned-httpapi-v2-request.json"); Assert.Collection(response.Cookies, actual => Assert.StartsWith("TestCookie=TestValue", actual)); } [Fact] public async Task TestReturningMultipleCookies() { var response = await this.InvokeAPIGatewayRequest("cookies-get-multiple-returned-httpapi-v2-request.json"); Assert.Collection(response.Cookies.OrderBy(s => s), actual => Assert.StartsWith("TestCookie1=TestValue1", actual), actual => Assert.StartsWith("TestCookie2=TestValue2", actual)); } [Fact] public async Task TestSingleCookie() { var response = await this.InvokeAPIGatewayRequest("cookies-get-single-httpapi-v2-request.json"); Assert.Equal("TestValue", response.Body); } [Fact] public async Task TestMultipleCookie() { var response = await this.InvokeAPIGatewayRequest("cookies-get-multiple-httpapi-v2-request.json"); Assert.Equal("TestValue3", response.Body); } [Fact] public async Task TestTraceIdSetFromLambdaContext() { try { Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "MyTraceId-1"); var response = await this.InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json"); Assert.Equal("MyTraceId-1", response.Body); Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "MyTraceId-2"); response = await this.InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json"); Assert.Equal("MyTraceId-2", response.Body); Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", null); response = await this.InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json"); Assert.True(!string.IsNullOrEmpty(response.Body) && !string.Equals(response.Body, "MyTraceId-2")); } finally { Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", null); } } private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequest(string fileName, bool configureApiToReturnExceptionDetail = false) { return await InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), GetRequestContent(fileName), configureApiToReturnExceptionDetail); } private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequest(TestLambdaContext context, string fileName, bool configureApiToReturnExceptionDetail = false) { return await InvokeAPIGatewayRequestWithContent(context, GetRequestContent(fileName), configureApiToReturnExceptionDetail); } private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent, bool configureApiToReturnExceptionDetail = false) { var lambdaFunction = new TestWebApp.HttpV2LambdaFunction(); if (configureApiToReturnExceptionDetail) lambdaFunction.IncludeUnhandledExceptionDetailInResponse = true; var requestStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent)); var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize<APIGatewayHttpApiV2ProxyRequest>(requestStream); return await lambdaFunction.FunctionHandlerAsync(request, context); } private string GetRequestContent(string fileName) { var filePath = Path.Combine(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), fileName); var requestStr = File.ReadAllText(filePath); return requestStr; } } }
314
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.ApplicationLoadBalancerEvents; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TestWebApp; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class TestApplicationLoadBalancerCalls { [Fact] public async Task TestGetAllValues() { var context = new TestLambdaContext(); var response = await this.InvokeApplicationLoadBalancerRequest(context, "values-get-all-alb-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]); Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString()); } [Fact] public async Task TestGetQueryStringValue() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-querystring-alb-request.json"); Assert.Equal("Lewis, Meriwether", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestGetNoQueryStringAlb() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-no-querystring-alb-request.json"); Assert.Equal(string.Empty, response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestGetNoQueryStringAlbMv() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-no-querystring-alb-mv-request.json"); Assert.Equal(string.Empty, response.Body); } [Fact] public async Task TestGetEncodingQueryStringAlb() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-querystring-alb-encoding-request.json"); var results = JsonConvert.DeserializeObject<TestWebApp.Controllers.RawQueryStringController.Results>(response.Body); Assert.Equal("http://www.gooogle.com", results.Url); Assert.Equal(DateTimeOffset.Parse("2019-03-12T16:06:06.549817+00:00"), results.TestDateTimeOffset); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestGetEncodingQueryStringAlbMv() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-querystring-alb-mv-encoding-request.json"); var results = JsonConvert.DeserializeObject<TestWebApp.Controllers.RawQueryStringController.Results>(response.Body); Assert.Equal("http://www.gooogle.com", results.Url); Assert.Equal(DateTimeOffset.Parse("2019-03-12T16:06:06.549817+00:00"), results.TestDateTimeOffset); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetQueryStringValueMV() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-querystring-alb-mv-request.json"); Assert.Equal("value1,value2", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"].FirstOrDefault()); } [Fact] public async Task TestPutWithBody() { var response = await this.InvokeApplicationLoadBalancerRequest("values-put-withbody-alb-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("Agent, Smith", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestPutWithBodyMV() { var response = await this.InvokeApplicationLoadBalancerRequest("values-put-withbody-alb-mv-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("Agent, Smith", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetSingleValue() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-single-alb-request.json"); Assert.Equal("value=5", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestGetBinaryContent() { var response = await this.InvokeApplicationLoadBalancerRequest("values-get-binary-alb-request.json"); Assert.Equal((int)HttpStatusCode.OK, response.StatusCode); string contentType; Assert.True(response.Headers.TryGetValue("Content-Type", out contentType), "Content-Type response header exists"); Assert.Equal("application/octet-stream", contentType); Assert.NotNull(response.Body); Assert.True(response.Body.Length > 0, "Body content is not empty"); Assert.True(response.IsBase64Encoded, "Response IsBase64Encoded"); // Compute a 256-byte array, with values 0-255 var binExpected = new byte[byte.MaxValue].Select((val, index) => (byte)index).ToArray(); var binActual = Convert.FromBase64String(response.Body); Assert.Equal(binExpected, binActual); } [Fact] public async Task TestPutBinaryContent() { var response = await this.InvokeApplicationLoadBalancerRequest("values-put-binary-alb-request.json"); Assert.Equal((int)HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Body); Assert.Equal("Greetings, programs!", response.Body); Assert.False(response.IsBase64Encoded, "Response IsBase64Encoded"); } [Fact] public async Task TestHealthCheck() { var response = await this.InvokeApplicationLoadBalancerRequest("alb-healthcheck.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]); } [Fact] public async Task TestContentLengthWithContent() { var response = await this.InvokeApplicationLoadBalancerRequest("check-content-length-withcontent-alb.json"); Assert.Equal("Request content length: 17", response.Body.Trim()); } [Fact] public async Task TestContentLengthNoContent() { var response = await this.InvokeApplicationLoadBalancerRequest("check-content-length-nocontent-alb.json"); Assert.Equal("Request content length: 0", response.Body.Trim()); } [Fact] public async Task TestGetCompressResponse() { var context = new TestLambdaContext(); var response = await this.InvokeApplicationLoadBalancerRequest(context, "compressresponse-get-alb-request.json"); Assert.Equal(200, response.StatusCode); var bytes = Convert.FromBase64String(response.Body); using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) { gs.CopyTo(mso); } var body = Encoding.UTF8.GetString(mso.ToArray()); Assert.Equal("[\"value1\",\"value2\"]", body); } Assert.True(response.Headers.ContainsKey("Content-Type")); Assert.Equal("application/json-compress", response.Headers["Content-Type"]); Assert.True(response.Headers.ContainsKey("Content-Encoding")); Assert.Equal("gzip", response.Headers["Content-Encoding"]); Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString()); } [Theory] [InlineData("rawtarget-escaped-percent-in-path-alb.json", "/foo%25bar")] [InlineData("rawtarget-escaped-percent-slash-in-path-alb.json", "/foo%25%2Fbar")] [InlineData("rawtarget-escaped-reserved-in-query-alb.json", "/foo/bar?foo=b%40r")] [InlineData("rawtarget-escaped-slash-in-path-alb.json", "/foo%2Fbar")] public async Task TestRawTarget(string requestFileName, string expectedRawTarget) { var response = await this.InvokeApplicationLoadBalancerRequest(requestFileName); Assert.Equal(200, response.StatusCode); var root = JObject.Parse(response.Body); Assert.Equal(expectedRawTarget, root["RawTarget"]?.ToString()); } private async Task<ApplicationLoadBalancerResponse> InvokeApplicationLoadBalancerRequest(string fileName) { return await InvokeApplicationLoadBalancerRequest(new TestLambdaContext(), fileName); } private async Task<ApplicationLoadBalancerResponse> InvokeApplicationLoadBalancerRequest(TestLambdaContext context, string fileName) { var lambdaFunction = new ALBLambdaFunction(); var filePath = Path.Combine(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), fileName); var requestStr = File.ReadAllText(filePath); var request = JsonConvert.DeserializeObject<ApplicationLoadBalancerRequest>(requestStr); return await lambdaFunction.FunctionHandlerAsync(request, context); } } }
254
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.TestUtilities; using Microsoft.AspNetCore.Http.Features; using TestWebApp; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class TestCallingWebAPI { public TestCallingWebAPI() { } [Fact] public async Task TestHttpApiGetAllValues() { var context = new TestLambdaContext(); var response = await this.InvokeAPIGatewayRequest(context, "values-get-all-httpapi-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString()); } [Fact] public async Task TestGetAllValues() { var context = new TestLambdaContext(); var response = await this.InvokeAPIGatewayRequest(context, "values-get-all-apigateway-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); Assert.Contains("OnStarting Called", ((TestLambdaLogger) context.Logger).Buffer.ToString()); } [Fact] public async Task TestGetAllValuesWithCustomPath() { var response = await this.InvokeAPIGatewayRequest("values-get-different-proxypath-apigateway-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetSingleValue() { var response = await this.InvokeAPIGatewayRequest("values-get-single-apigateway-request.json"); Assert.Equal("value=5", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetQueryStringValue() { var response = await this.InvokeAPIGatewayRequest("values-get-querystring-apigateway-request.json"); Assert.Equal("Lewis, Meriwether", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetNoQueryStringApiGateway() { var response = await this.InvokeAPIGatewayRequest("values-get-no-querystring-apigateway-request.json"); Assert.Equal(string.Empty, response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestGetEncodingQueryStringGateway() { var response = await this.InvokeAPIGatewayRequest("values-get-querystring-apigateway-encoding-request.json"); var results = JsonSerializer.Deserialize<TestWebApp.Controllers.RawQueryStringController.Results>(response.Body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); Assert.Equal("http://www.gooogle.com", results.Url); Assert.Equal(DateTimeOffset.Parse("2019-03-12T16:06:06.549817+00:00"), results.TestDateTimeOffset); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestPutWithBody() { var response = await this.InvokeAPIGatewayRequest("values-put-withbody-apigateway-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("Agent, Smith", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestDefaultResponseErrorCode() { var response = await this.InvokeAPIGatewayRequest("values-get-error-apigateway-request.json"); Assert.Equal(500, response.StatusCode); Assert.Equal(string.Empty, response.Body); } [Theory] [InlineData("values-get-aggregateerror-apigateway-request.json", "AggregateException", true)] [InlineData("values-get-typeloaderror-apigateway-request.json", "ReflectionTypeLoadException", true)] [InlineData("values-get-aggregateerror-apigateway-request.json", "AggregateException", false)] [InlineData("values-get-typeloaderror-apigateway-request.json", "ReflectionTypeLoadException", false)] public async Task TestEnhancedExceptions(string requestFileName, string expectedExceptionType, bool configureApiToReturnExceptionDetail) { var response = await this.InvokeAPIGatewayRequest(requestFileName, configureApiToReturnExceptionDetail); Assert.Equal(500, response.StatusCode); Assert.Equal(string.Empty, response.Body); if (configureApiToReturnExceptionDetail) { Assert.True(response.MultiValueHeaders.ContainsKey("ErrorType")); Assert.Equal(expectedExceptionType, response.MultiValueHeaders["ErrorType"][0]); } else { Assert.False(response.MultiValueHeaders.ContainsKey("ErrorType")); } } [Fact] public async Task TestGettingSwaggerDefinition() { var response = await this.InvokeAPIGatewayRequest("swagger-get-apigateway-request.json"); Assert.Equal(200, response.StatusCode); Assert.True(response.Body.Length > 0); Assert.Equal("application/json", response.MultiValueHeaders["Content-Type"][0]); } [Fact] public void TestGetCustomAuthorizerValue() { var requestStr = File.ReadAllText("values-get-customauthorizer-apigateway-request.json"); var request = JsonSerializer.Deserialize<APIGatewayProxyRequest>(requestStr, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); Assert.NotNull(request?.RequestContext.Authorizer); Assert.NotNull(request.RequestContext.Authorizer.StringKey); Assert.Equal(9, request.RequestContext.Authorizer.NumKey); Assert.True(request.RequestContext.Authorizer.BoolKey); Assert.NotEmpty(request.RequestContext.Authorizer.Claims); Assert.Equal("test-id", request.RequestContext.Authorizer.Claims["sub"]); } [Fact] public void TestCustomAuthorizerSerialization() { var response = new APIGatewayCustomAuthorizerResponse { PrincipalID = "com.amazon.someuser", Context = new APIGatewayCustomAuthorizerContextOutput { StringKey = "Hey I'm a string", BoolKey = true, NumKey = 9 }, PolicyDocument = new APIGatewayCustomAuthorizerPolicy { Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement> { new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Effect = "Allow", Action = new HashSet<string> {"execute-api:Invoke"}, Resource = new HashSet<string> {"arn:aws:execute-api:us-west-2:1234567890:apit123d45/Prod/GET/*"} } } } }; var json = JsonSerializer.Serialize(response, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); Assert.NotNull(json); var expected = "{\"principalId\":\"com.amazon.someuser\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"execute-api:Invoke\"],\"Resource\":[\"arn:aws:execute-api:us-west-2:1234567890:apit123d45/Prod/GET/*\"]}]},\"context\":{\"stringKey\":\"Hey I'm a string\",\"boolKey\":true,\"numKey\":9},\"usageIdentifierKey\":null}"; Assert.Equal(expected, json); } [Fact] public async Task TestGetBinaryContent() { var response = await this.InvokeAPIGatewayRequest("values-get-binary-apigateway-request.json"); Assert.Equal((int) HttpStatusCode.OK, response.StatusCode); IList<string> contentType; Assert.True(response.MultiValueHeaders.TryGetValue("Content-Type", out contentType), "Content-Type response header exists"); Assert.Equal("application/octet-stream", contentType[0]); Assert.NotNull(response.Body); Assert.True(response.Body.Length > 0, "Body content is not empty"); Assert.True(response.IsBase64Encoded, "Response IsBase64Encoded"); // Compute a 256-byte array, with values 0-255 var binExpected = new byte[byte.MaxValue].Select((val, index) => (byte) index).ToArray(); var binActual = Convert.FromBase64String(response.Body); Assert.Equal(binExpected, binActual); } [Fact] public async Task TestEncodePlusInResourcePath() { var response = await this.InvokeAPIGatewayRequest("encode-plus-in-resource-path.json"); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<IDictionary<string, object>>(response.Body); Assert.Equal("/foo+bar", root?["Path"]?.ToString()); } [Fact] public async Task TestEncodeSpaceInResourcePath() { var requestStr = GetRequestContent("encode-space-in-resource-path.json"); var response = await this.InvokeAPIGatewayRequest("encode-space-in-resource-path.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("value=tmh/file name.xml", response.Body); } [Fact] public async Task TestEncodeSlashInResourcePath() { var requestStr = GetRequestContent("encode-slash-in-resource-path.json"); var response = await this.InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr); Assert.Equal(200, response.StatusCode); Assert.Equal("{\"only\":\"a%2Fb\"}", response.Body); response = await this.InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr.Replace("a%2Fb", "a/b")); Assert.Equal(200, response.StatusCode); Assert.Equal("{\"first\":\"a\",\"second\":\"b\"}", response.Body); } [Fact] public async Task TestAdditionalPathParametersInProxyPath() { var response = await this.InvokeAPIGatewayRequest("additional-path-parameters-in-proxy-path.json"); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<JsonObject>(response.Body); Assert.Equal("/path/bar/api", root?["Path"]?.ToString()); } [Fact] public async Task TestAdditionalPathParametersInNonProxyPath() { var response = await this.InvokeAPIGatewayRequest("additional-path-parameters-in-non-proxy-path.json"); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<JsonObject>(response.Body); Assert.Equal("/path/bar/api", root?["Path"]?.ToString()); } [Fact] public async Task TestSpaceInResourcePathAndQueryString() { var response = await this.InvokeAPIGatewayRequest("encode-space-in-resource-path-and-query.json"); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<JsonObject>(response.Body); Assert.Equal("/foo%20bar", root?["Path"]?.ToString()); var query = root["QueryVariables"]["greeting"] as JsonArray; Assert.Equal("hello world", query[0].ToString()); } [Fact] public async Task TestTrailingSlashInPath() { var response = await this.InvokeAPIGatewayRequest("trailing-slash-in-path.json"); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<JsonObject>(response.Body); Assert.Equal("/Prod", root?["PathBase"]?.ToString()); Assert.Equal("/foo/", root?["Path"]?.ToString()); } [Theory] [InlineData("rawtarget-escaped-percent-in-path.json", "/foo%25bar")] [InlineData("rawtarget-escaped-percent-slash-in-path.json", "/foo%25%2Fbar")] [InlineData("rawtarget-escaped-reserved-in-query.json", "/foo/bar?foo=b%2540r")] [InlineData("rawtarget-escaped-slash-in-path.json", "/foo%2Fbar")] public async Task TestRawTarget(string requestFileName, string expectedRawTarget) { var response = await this.InvokeAPIGatewayRequest(requestFileName); Assert.Equal(200, response.StatusCode); var root = JsonSerializer.Deserialize<JsonObject>(response.Body); Assert.Equal(expectedRawTarget, root["RawTarget"]?.ToString()); } [Fact] public async Task TestAuthTestAccess() { var response = await this.InvokeAPIGatewayRequest("authtest-access-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("You Have Access", response.Body); } [Fact] public async Task TestAuthMTls() { var response = await this.InvokeAPIGatewayRequest("mtls-request.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("O=Internet Widgits Pty Ltd, S=Some-State, C=AU", response.Body); } [Fact] public async Task TestAuthMTlsWithTrailingNewLine() { var response = await this.InvokeAPIGatewayRequest("mtls-request-trailing-newline.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("O=Internet Widgits Pty Ltd, S=Some-State, C=AU", response.Body); } [Fact] public async Task TestAuthTestAccess_CustomLambdaAuthorizerClaims() { var response = await this.InvokeAPIGatewayRequest("authtest-access-request-custom-lambda-authorizer-output.json"); Assert.Equal(200, response.StatusCode); Assert.Equal("You Have Access", response.Body); } [Fact] public async Task TestAuthTestNoAccess() { var response = await this.InvokeAPIGatewayRequest("authtest-noaccess-request.json"); Assert.NotEqual(200, response.StatusCode); } // Covers the test case when using a custom proxy request, probably for testing, and doesn't specify the resource [Fact] public async Task TestMissingResourceInRequest() { var response = await this.InvokeAPIGatewayRequest("missing-resource-request.json"); Assert.Equal(200, response.StatusCode); Assert.True(response.Body.Length > 0); Assert.Contains("application/json", response.MultiValueHeaders["Content-Type"][0]); } // If there is no content-type we must make sure Content-Type is set to null in the headers collection so API Gateway doesn't return a default Content-Type. [Fact] public async Task TestDeleteNoContentContentType() { var response = await this.InvokeAPIGatewayRequest("values-delete-no-content-type-apigateway-request.json"); Assert.Equal(200, response.StatusCode); Assert.True(response.Body.Length == 0); Assert.Equal(1, response.MultiValueHeaders["Content-Type"].Count); Assert.Null(response.MultiValueHeaders["Content-Type"][0]); } [Fact] public async Task TestRedirectNoContentType() { var response = await this.InvokeAPIGatewayRequest("redirect-apigateway-request.json"); Assert.Equal(302, response.StatusCode); Assert.True(response.Body.Length == 0); Assert.Equal(1, response.MultiValueHeaders["Content-Type"].Count); Assert.Null(response.MultiValueHeaders["Content-Type"][0]); Assert.Equal("redirecttarget", response.MultiValueHeaders["Location"][0]); } [Fact] public async Task TestContentLengthWithContent() { var response = await this.InvokeAPIGatewayRequest("check-content-length-withcontent-apigateway.json"); Assert.Equal("Request content length: 17", response.Body.Trim()); } [Fact] public async Task TestContentLengthNoContent() { var response = await this.InvokeAPIGatewayRequest("check-content-length-nocontent-apigateway.json"); Assert.Equal("Request content length: 0", response.Body.Trim()); } [Fact] public async Task TestGetCompressResponse() { var context = new TestLambdaContext(); var response = await this.InvokeAPIGatewayRequest(context, "compressresponse-get-apigateway-request.json"); Assert.Equal(200, response.StatusCode); var bytes = Convert.FromBase64String(response.Body); using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) { gs.CopyTo(mso); } var body = UTF8Encoding.UTF8.GetString(mso.ToArray()); Assert.Equal("[\"value1\",\"value2\"]", body); } Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json-compress", response.MultiValueHeaders["Content-Type"][0]); Assert.Equal("gzip", response.MultiValueHeaders["Content-Encoding"][0]); Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString()); } [Fact] public async Task TestRequestServicesAreAvailable() { var requestStr = GetRequestContent("requestservices-get-apigateway-request.json"); var response = await this.InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr); Assert.Equal(200, response.StatusCode); Assert.Equal("Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope", response.Body); } /// <summary> /// This test is ensuring when we don't use the Lambda trace id and fallback to ASP.NET Core trace id generator /// logic we keep returning the same value each time. This was addressing a PR comment for the trace id PR. /// </summary> [Fact] public void EnsureTraceIdStaysTheSame() { var features = new InvokeFeatures() as IHttpRequestIdentifierFeature; var traceId1 = features.TraceIdentifier; var traceId2 = features.TraceIdentifier; Assert.Equal(traceId1, traceId2); } private async Task<APIGatewayProxyResponse> InvokeAPIGatewayRequest(string fileName, bool configureApiToReturnExceptionDetail = false) { return await InvokeAPIGatewayRequest(new TestLambdaContext(), fileName, configureApiToReturnExceptionDetail); } private async Task<APIGatewayProxyResponse> InvokeAPIGatewayRequest(TestLambdaContext context, string fileName, bool configureApiToReturnExceptionDetail = false) { return await InvokeAPIGatewayRequestWithContent(context, GetRequestContent(fileName), configureApiToReturnExceptionDetail); } private async Task<APIGatewayProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent, bool configureApiToReturnExceptionDetail = false) { var lambdaFunction = new ApiGatewayLambdaFunction(); if (configureApiToReturnExceptionDetail) lambdaFunction.IncludeUnhandledExceptionDetailInResponse = true; var requestStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent)); var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize<APIGatewayProxyRequest>(requestStream); return await lambdaFunction.FunctionHandlerAsync(request, context); } private string GetRequestContent(string fileName) { var filePath = Path.Combine(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), fileName); var requestStr = File.ReadAllText(filePath); return requestStr; } } }
518
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.Serialization.SystemTextJson; using Amazon.Lambda.APIGatewayEvents; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class TestMinimalAPI : IClassFixture<TestMinimalAPI.TestMinimalAPIAppFixture> { TestMinimalAPIAppFixture _fixture; public TestMinimalAPI(TestMinimalAPI.TestMinimalAPIAppFixture fixture) { this._fixture = fixture; } [Fact] public void TestMapPostComplexType() { var response = _fixture.ExecuteRequest<APIGatewayProxyResponse>("minimal-api-post.json"); Assert.Equal((int)HttpStatusCode.OK, response.StatusCode); Assert.Contains("works:string", response.Body); } public class TestMinimalAPIAppFixture : IDisposable { object lock_process = new object(); public TestMinimalAPIAppFixture() { } public void Dispose() { } public T ExecuteRequest<T>(string eventFilePath) { var requestFilePath = Path.Combine(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), eventFilePath); var responseFilePath = Path.GetTempFileName(); var comamndArgument = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/c" : $"-c"; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = GetSystemShell(); processStartInfo.Arguments = $"{comamndArgument} dotnet run \"{requestFilePath}\" \"{responseFilePath}\""; processStartInfo.WorkingDirectory = GetTestAppDirectory(); lock (lock_process) { using var process = Process.Start(processStartInfo); process.WaitForExit(15000); if(!File.Exists(responseFilePath)) { throw new Exception("No response file found"); } using var responseFileStream = File.OpenRead(responseFilePath); var serializer = new DefaultLambdaJsonSerializer(); var response = serializer.Deserialize<T>(responseFileStream); return response; } } private string GetTestAppDirectory() { var path = this.GetType().GetTypeInfo().Assembly.Location; while(!string.Equals(new DirectoryInfo(path).Name, "test")) { path = Directory.GetParent(path).FullName; } return Path.GetFullPath(Path.Combine(path, "TestMinimalAPIApp")); } private string GetSystemShell() { if (TryGetEnvironmentVariable("COMSPEC", out var comspec)) { return comspec!; } if (TryGetEnvironmentVariable("SHELL", out var shell)) { return shell!; } // fallback to defaults return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/sh"; } private bool TryGetEnvironmentVariable(string variable, out string? value) { value = Environment.GetEnvironmentVariable(variable); return !string.IsNullOrEmpty(value); } } } }
113
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TestWebApp; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class TestWhichBuilderIsUsed { [Theory] [InlineData(typeof(HostBuilderUsingGenericClass), true)] [InlineData(typeof(HostBuilderOverridingInit), true)] [InlineData(typeof(HostBuilderOverridingCreateWebHostBuilder), false)] [InlineData(typeof(HostBuilderOverridingCreateHostBuilder), true)] [InlineData(typeof(HostBuilderOverridingInitHostBuilderAndCallsConfigureWebHostDefaults), true)] [InlineData(typeof(HostBuilderOverridingInitHostBuilderAndCallsConfigureWebHostLambdaDefaults), true)] public async Task TestUsingGenericBaseClass(Type functionType, bool initHostCalled) { var methodsCalled = await InvokeAPIGatewayRequestWithContent(functionType); Assert.Equal(initHostCalled, methodsCalled.InitHostBuilder); Assert.True(methodsCalled.InitHostWebBuilder); } private async Task<IMethodsCalled> InvokeAPIGatewayRequestWithContent(Type functionType) { var context = new TestLambdaContext(); var filePath = Path.Combine(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), "values-get-all-apigateway-request.json"); var requestContent = File.ReadAllText(filePath); var lambdaFunction = Activator.CreateInstance(functionType) as APIGatewayProxyFunction; var requestStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent)); var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize<APIGatewayProxyRequest>(requestStream); var response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); return lambdaFunction as IMethodsCalled; } } }
57
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Lambda.AspNetCoreServer.Internal; using Microsoft.AspNetCore.Http.Features; using Xunit; namespace Amazon.Lambda.AspNetCoreServer.Test { public class UtilitiesTest { [Theory] [InlineData(null, null)] [InlineData("", null)] [InlineData("name=foo bar", "?name=foo bar")] [InlineData("name=foo+bar", "?name=foo+bar")] [InlineData("url=http://www.google.com&testDateTimeOffset=2019-03-12T16:06:06.549817+00:00", "?url=http://www.google.com&testDateTimeOffset=2019-03-12T16:06:06.549817+00:00")] public void TestHttpApiV2QueryStringEncoding(string starting, string expected) { var encoded = Utilities.CreateQueryStringParametersFromHttpApiV2(starting); Assert.Equal(expected, encoded); } // This test is ensure middleware will the status code at 200. [Fact] public void EnsureStatusCodeStartsAtIs200() { var feature = new InvokeFeatures() as IHttpResponseFeature; Assert.Equal(200, feature.StatusCode); } } }
34
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Lambda.AspNetCoreServer.Test")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5b48aea8-5702-45a8-9d89-ceb986e6dbc1")]
20
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using System.Linq; using Amazon.Lambda; namespace Amazon.Lambda.Tests { public class CoreTest { [Fact] public void TestLambdaLogger() { // verify that LambdaLogger logs to Console var message = "This is a message that should appear in console! ?_?"; var oldWriter = Console.Out; try { using (var writer = new StringWriter()) { Console.SetOut(writer); Lambda.Core.LambdaLogger.Log(message); var consoleText = writer.ToString(); Assert.Contains(message, consoleText); } } finally { Console.SetOut(oldWriter); } } } }
40
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Logging.AspNetCore.Tests; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Xunit; namespace Amazon.Lambda.Tests { public class LoggingTests { private const string SHOULD_APPEAR = "TextThatShouldAppear"; private const string SHOULD_NOT_APPEAR = "TextThatShouldNotAppear"; private const string SHOULD_APPEAR_EVENT = "EventThatShouldAppear"; private const string SHOULD_APPEAR_EXCEPTION = "ExceptionThatShouldAppear"; private static string APPSETTINGS_DIR = Directory.GetCurrentDirectory(); private static readonly Func<int, EventId> GET_SHOULD_APPEAR_EVENT = (id) => new EventId(451, SHOULD_APPEAR_EVENT + id); private static readonly EventId SHOULD_NOT_APPEAR_EVENT = new EventId(333, "EventThatShoulNotdAppear"); private static readonly Func<int, Exception> GET_SHOULD_APPEAR_EXCEPTION = (id) => new Exception(SHOULD_APPEAR_EXCEPTION + id); private static readonly Exception SHOULD_NOT_APPEAR_EXCEPTION = new Exception("ExceptionThatShouldNotAppear"); [Fact] public void TestConfiguration() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int count = 0; var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR + (count++)); defaultLogger.LogCritical(SHOULD_APPEAR + (count++)); defaultLogger = loggerfactory.CreateLogger(null); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR + (count++)); defaultLogger.LogCritical(SHOULD_APPEAR + (count++)); // change settings int countAtChange = count; loggerOptions.IncludeCategory = true; loggerOptions.IncludeLogLevel = true; loggerOptions.IncludeNewline = true; var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_APPEAR + (count++)); msLogger.LogCritical(SHOULD_APPEAR + (count++)); var sdkLogger = loggerfactory.CreateLogger("AWSSDK"); sdkLogger.LogTrace(SHOULD_NOT_APPEAR); sdkLogger.LogInformation(SHOULD_APPEAR + (count++)); sdkLogger.LogCritical(SHOULD_APPEAR + (count++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); // check that all expected strings are in the text for (int i = 0; i < count; i++) { var expected = SHOULD_APPEAR + i; Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'"); } // check extras that were added mid-way int numberOfExtraBits = count - countAtChange; // count levels var logLevelStrings = Enum.GetNames(typeof(LogLevel)).Select(ll => $"[{ll}").ToList(); Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, logLevelStrings)); // count categories var categoryStrings = new string[] { "Microsoft", "AWSSDK" }; Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, categoryStrings)); // count newlines Assert.Equal(numberOfExtraBits, CountOccurences(text, Environment.NewLine)); } } [Fact] public void TestWilcardConfiguration() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.wildcard.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int count = 0; // Should match: // "Foo.*": "Information" var foobarLogger = loggerfactory.CreateLogger("Foo.Bar"); foobarLogger.LogTrace(SHOULD_NOT_APPEAR); foobarLogger.LogDebug(SHOULD_NOT_APPEAR); foobarLogger.LogInformation(SHOULD_APPEAR + (count++)); foobarLogger.LogWarning(SHOULD_APPEAR + (count++)); foobarLogger.LogError(SHOULD_APPEAR + (count++)); foobarLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "Foo.Bar.Baz": "Critical" var foobarbazLogger = loggerfactory.CreateLogger("Foo.Bar.Baz"); foobarbazLogger.LogTrace(SHOULD_NOT_APPEAR); foobarbazLogger.LogDebug(SHOULD_NOT_APPEAR); foobarbazLogger.LogInformation(SHOULD_NOT_APPEAR); foobarbazLogger.LogWarning(SHOULD_NOT_APPEAR); foobarbazLogger.LogError(SHOULD_NOT_APPEAR); foobarbazLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "Foo.Bar.*": "Warning" var foobarbuzzLogger = loggerfactory.CreateLogger("Foo.Bar.Buzz"); foobarbuzzLogger.LogTrace(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogDebug(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogInformation(SHOULD_NOT_APPEAR); foobarbuzzLogger.LogWarning(SHOULD_APPEAR + (count++)); foobarbuzzLogger.LogError(SHOULD_APPEAR + (count++)); foobarbuzzLogger.LogCritical(SHOULD_APPEAR + (count++)); // Should match: // "*": "Error" var somethingLogger = loggerfactory.CreateLogger("something"); somethingLogger.LogTrace(SHOULD_NOT_APPEAR); somethingLogger.LogDebug(SHOULD_NOT_APPEAR); somethingLogger.LogInformation(SHOULD_NOT_APPEAR); somethingLogger.LogWarning(SHOULD_NOT_APPEAR); somethingLogger.LogError(SHOULD_APPEAR + (count++)); somethingLogger.LogCritical(SHOULD_APPEAR + (count++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); // check that all expected strings are in the text for (int i = 0; i < count; i++) { var expected = SHOULD_APPEAR + i; Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'"); } } } [Fact] public void TestOnlyOneWildcardSupported() { var dict = new Dictionary<string, string> { { "Lambda.Logging:LogLevel:*.*", "Information" } }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); ArgumentOutOfRangeException exception = null; try { var loggerOptions = new LambdaLoggerOptions(configuration); } catch (ArgumentOutOfRangeException ex) { exception = ex; } // check that there are no unexpected strings in the text Assert.NotNull(exception); Assert.Contains("only 1 wildcard is supported in a category", exception.Message); } [Fact] public void TestOnlyTerminatingWildcardsSupported() { var dict = new Dictionary<string, string> { { "Lambda.Logging:LogLevel:Foo.*.Bar", "Information" } }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); ArgumentException exception = null; try { var loggerOptions = new LambdaLoggerOptions(configuration); } catch (ArgumentException ex) { exception = ex; } // check that there are no unexpected strings in the text Assert.NotNull(exception); Assert.Contains("wilcards are only supported at the end of a category", exception.Message); } [Fact] public void TestConfigurationReadingForExceptionsEvents() { // Arrange var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.exceptions.json")) .Build(); // Act var loggerOptions = new LambdaLoggerOptions(configuration); // Assert Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); Assert.True(loggerOptions.IncludeEventId); Assert.True(loggerOptions.IncludeException); Assert.False(loggerOptions.IncludeScopes); } [Fact] public void TestConfigurationReadingForScopes() { // Arrange var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.scopes.json")) .Build(); // Act var loggerOptions = new LambdaLoggerOptions(configuration); // Assert Assert.False(loggerOptions.IncludeCategory); Assert.False(loggerOptions.IncludeLogLevel); Assert.False(loggerOptions.IncludeNewline); Assert.True(loggerOptions.IncludeEventId); Assert.True(loggerOptions.IncludeException); Assert.True(loggerOptions.IncludeScopes); } [Fact] public void TestLoggingExceptionsAndEvents() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); int countMessage = 0; int countEvent = 0; int countException = 0; var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger = loggerfactory.CreateLogger(null); defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++)); // change settings loggerOptions.IncludeCategory = true; loggerOptions.IncludeLogLevel = true; loggerOptions.IncludeNewline = true; loggerOptions.IncludeException = true; loggerOptions.IncludeEventId = true; var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR); msLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); msLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); var sdkLogger = loggerfactory.CreateLogger("AWSSDK"); sdkLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR); sdkLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); sdkLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++)); // get text and verify var text = writer.ToString(); // check that there are no unexpected strings in the text Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Id.ToString(), text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Name, text); Assert.DoesNotContain(SHOULD_NOT_APPEAR_EXCEPTION.Message, text); // check that all expected strings are in the text for (int i = 0; i < countMessage; i++) { var expectedMessages = SHOULD_APPEAR + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } for (int i = 0; i < countException; i++) { var expectedMessages = SHOULD_APPEAR_EXCEPTION + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } for (int i = 0; i < countEvent; i++) { var expectedMessages = SHOULD_APPEAR_EVENT + i; Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'"); } } } [Fact] public void TestLoggingScopesEvents() { // Arrange using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var loggerOptions = new LambdaLoggerOptions{ IncludeScopes = true }; var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); var defaultLogger = loggerfactory.CreateLogger("Default"); // Act using(defaultLogger.BeginScope("First {0}", "scope123")) { defaultLogger.LogInformation("Hello"); using(defaultLogger.BeginScope("Second {0}", "scope456")) { defaultLogger.LogError("In 2nd scope"); defaultLogger.LogInformation("that's enough"); } } // Assert // get text and verify var text = writer.ToString(); Assert.Contains("[Information] First scope123 => Default: Hello ", text); Assert.Contains("[Error] First scope123 Second scope456 => Default: In 2nd scope ", text); Assert.Contains("[Information] First scope123 Second scope456 => Default: that's enough ", text); } } [Fact] public void TestLoggingScopesEvents_When_ScopesDisabled() { // Arrange using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var loggerOptions = new LambdaLoggerOptions { IncludeScopes = false }; var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); var defaultLogger = loggerfactory.CreateLogger("Default"); // Act using (defaultLogger.BeginScope("First {0}", "scope123")) { defaultLogger.LogInformation("Hello"); using (defaultLogger.BeginScope("Second {0}", "scope456")) { defaultLogger.LogError("In 2nd scope"); defaultLogger.LogInformation("that's enough"); } } // Assert // get text and verify var text = writer.ToString(); Assert.Contains("[Information] Default: Hello ", text); Assert.Contains("[Error] Default: In 2nd scope ", text); Assert.Contains("[Information] Default: that's enough ", text); } } [Fact] public void TestLoggingWithTypeCategories() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); // arrange var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.nsprefix.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerFactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act var httpClientLogger = loggerFactory.CreateLogger<System.Net.HttpListener>(); var authMngrLogger = loggerFactory.CreateLogger<System.Net.AuthenticationManager>(); var arrayLogger = loggerFactory.CreateLogger<System.Array>(); httpClientLogger.LogTrace(SHOULD_NOT_APPEAR); httpClientLogger.LogDebug(SHOULD_APPEAR); httpClientLogger.LogInformation(SHOULD_APPEAR); httpClientLogger.LogWarning(SHOULD_APPEAR); httpClientLogger.LogError(SHOULD_APPEAR); httpClientLogger.LogCritical(SHOULD_APPEAR); authMngrLogger.LogTrace(SHOULD_NOT_APPEAR); authMngrLogger.LogDebug(SHOULD_NOT_APPEAR); authMngrLogger.LogInformation(SHOULD_APPEAR); authMngrLogger.LogWarning(SHOULD_APPEAR); authMngrLogger.LogError(SHOULD_APPEAR); authMngrLogger.LogCritical(SHOULD_APPEAR); arrayLogger.LogTrace(SHOULD_NOT_APPEAR); arrayLogger.LogDebug(SHOULD_NOT_APPEAR); arrayLogger.LogInformation(SHOULD_NOT_APPEAR); arrayLogger.LogWarning(SHOULD_APPEAR); arrayLogger.LogError(SHOULD_APPEAR); arrayLogger.LogCritical(SHOULD_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } } [Fact] public void TestDefaultLogLevel() { using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act // creating named logger, `Default` category is set to "Debug" // (Default category has special treatment - it's not actually stored, named logger just falls to default) var defaultLogger = loggerfactory.CreateLogger("Default"); defaultLogger.LogTrace(SHOULD_NOT_APPEAR); defaultLogger.LogDebug(SHOULD_APPEAR); defaultLogger.LogInformation(SHOULD_APPEAR); // `Dummy` category is not specified, we should use `Default` category instead var dummyLogger = loggerfactory.CreateLogger("Dummy"); dummyLogger.LogTrace(SHOULD_NOT_APPEAR); dummyLogger.LogDebug(SHOULD_APPEAR); dummyLogger.LogInformation(SHOULD_APPEAR); // `Microsoft` category is specified, log accordingly var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogDebug(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } } [Fact] public void TestDefaultLogLevelIfNotConfigured() { // arrange using (var writer = new StringWriter()) { ConnectLoggingActionToLogger(message => writer.Write(message)); var configuration = new ConfigurationBuilder() .AddJsonFile(GetAppSettingsPath("appsettings.without_default.json")) .Build(); var loggerOptions = new LambdaLoggerOptions(configuration); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(loggerOptions); // act // `Dummy` category is not specified, we should stick with default: min level = INFO var dummyLogger = loggerfactory.CreateLogger("Dummy"); dummyLogger.LogTrace(SHOULD_NOT_APPEAR); dummyLogger.LogDebug(SHOULD_NOT_APPEAR); dummyLogger.LogInformation(SHOULD_APPEAR); // `Microsoft` category is specified, log accordingly var msLogger = loggerfactory.CreateLogger("Microsoft"); msLogger.LogTrace(SHOULD_NOT_APPEAR); msLogger.LogDebug(SHOULD_NOT_APPEAR); msLogger.LogInformation(SHOULD_NOT_APPEAR); // assert var text = writer.ToString(); Assert.DoesNotContain(SHOULD_NOT_APPEAR, text); } } private static string GetAppSettingsPath(string fileName) { return Path.Combine(APPSETTINGS_DIR, fileName); } private static void ConnectLoggingActionToLogger(Action<string> loggingAction) { var lambdaLoggerType = typeof(Amazon.Lambda.Core.LambdaLogger); Assert.NotNull(lambdaLoggerType); var loggingActionField = lambdaLoggerType .GetTypeInfo() .GetField("_loggingAction", BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(loggingActionField); loggingActionField.SetValue(null, loggingAction); } private static int CountOccurences(string text, string substring) { int occurences = 0; int index = 0; do { index = text.IndexOf(substring, index, StringComparison.Ordinal); if (index >= 0) { occurences++; index += substring.Length; } } while (index >= 0); return occurences; } private static int CountMultipleOccurences(string text, IEnumerable<string> substrings) { int total = 0; foreach (var substring in substrings) { total += CountOccurences(text, substring); } return total; } } }
582
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Lambda.Logging.AspNetCore.Tests { public class TestLoggerFactory : ILoggerFactory { private ILoggerProvider _provider; public void AddProvider(ILoggerProvider provider) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (_provider != null) { throw new InvalidOperationException("Provider is already set, cannot add another."); } _provider = provider; } public ILogger CreateLogger(string categoryName) { return _provider.CreateLogger(categoryName); } public void Dispose() { var provider = _provider; _provider = null; if (provider != null) { provider.Dispose(); } } } }
43
aws-lambda-dotnet
aws
C#
using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Lambda.Model; using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport.IntegrationTests { public class BaseCustomRuntimeTest { protected static readonly RegionEndpoint TestRegion = RegionEndpoint.USWest2; protected static readonly string LAMBDA_ASSUME_ROLE_POLICY = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""lambda.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" } ] } ".Trim(); protected string Handler { get; } protected string FunctionName { get; } protected string DeploymentZipKey { get; } protected string DeploymentPackageZipRelativePath { get; } protected string TestBucketRoot { get; } = "customruntimetest-"; protected string ExecutionRoleName { get; } protected string ExecutionRoleArn { get; set; } private const string TestsProjectDirectoryName = "Amazon.Lambda.RuntimeSupport.Tests"; protected BaseCustomRuntimeTest(string functionName, string deploymentZipKey, string deploymentPackageZipRelativePath, string handler) { FunctionName = functionName; ExecutionRoleName = FunctionName; Handler = handler; DeploymentZipKey = deploymentZipKey; DeploymentPackageZipRelativePath = deploymentPackageZipRelativePath; } /// <summary> /// Clean up all test resources. /// Also cleans up any resources that might be left from previous failed/interrupted tests. /// </summary> /// <param name="s3Client"></param> /// <param name="lambdaClient"></param> /// <returns></returns> protected async Task CleanUpTestResources(AmazonS3Client s3Client, AmazonLambdaClient lambdaClient, AmazonIdentityManagementServiceClient iamClient, bool roleAlreadyExisted) { await DeleteFunctionIfExistsAsync(lambdaClient); var listBucketsResponse = await s3Client.ListBucketsAsync(); foreach (var bucket in listBucketsResponse.Buckets) { if (bucket.BucketName.StartsWith(TestBucketRoot)) { await DeleteDeploymentZipAndBucketAsync(s3Client, bucket.BucketName); } } if (!roleAlreadyExisted) { try { var deleteRoleRequest = new DeleteRoleRequest { RoleName = ExecutionRoleName }; await iamClient.DeleteRoleAsync(deleteRoleRequest); } catch (Exception) { // no problem - it's best effort } } } protected async Task<bool> PrepareTestResources(IAmazonS3 s3Client, IAmazonLambda lambdaClient, AmazonIdentityManagementServiceClient iamClient) { var roleAlreadyExisted = await ValidateAndSetIamRoleArn(iamClient); var testBucketName = TestBucketRoot + Guid.NewGuid().ToString(); await CreateBucketWithDeploymentZipAsync(s3Client, testBucketName); await CreateFunctionAsync(lambdaClient, testBucketName); return roleAlreadyExisted; } /// <summary> /// Create the role if it's not there already. /// Return true if it already existed. /// </summary> /// <returns></returns> private async Task<bool> ValidateAndSetIamRoleArn(IAmazonIdentityManagementService iamClient) { var getRoleRequest = new GetRoleRequest { RoleName = ExecutionRoleName }; try { ExecutionRoleArn = (await iamClient.GetRoleAsync(getRoleRequest)).Role.Arn; return true; } catch (NoSuchEntityException) { // create the role var createRoleRequest = new CreateRoleRequest { RoleName = ExecutionRoleName, Description = "Test role for CustomRuntimeTests.", AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY }; ExecutionRoleArn = (await iamClient.CreateRoleAsync(createRoleRequest)).Role.Arn; // Wait for role to propagate. await Task.Delay(10000); await iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AWSLambdaExecute", RoleName = ExecutionRoleName, }); return false; } } private async Task CreateBucketWithDeploymentZipAsync(IAmazonS3 s3Client, string bucketName) { // create bucket if it doesn't exist var listBucketsResponse = await s3Client.ListBucketsAsync(); if (listBucketsResponse.Buckets.Find((bucket) => bucket.BucketName == bucketName) == null) { var putBucketRequest = new PutBucketRequest { BucketName = bucketName }; await s3Client.PutBucketAsync(putBucketRequest); await Task.Delay(10000); } // write or overwrite deployment package var putObjectRequest = new PutObjectRequest { BucketName = bucketName, Key = DeploymentZipKey, FilePath = GetDeploymentZipPath() }; await s3Client.PutObjectAsync(putObjectRequest); // Wait for bucket to propagate. await Task.Delay(5000); } private async Task DeleteDeploymentZipAndBucketAsync(IAmazonS3 s3Client, string bucketName) { try { await Amazon.S3.Util.AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } catch (AmazonS3Exception e) { // If it's just telling us the bucket's not there then continue, otherwise throw. if (!e.Message.Contains("The specified bucket does not exist")) { throw; } } } protected async Task<InvokeResponse> InvokeFunctionAsync(IAmazonLambda lambdaClient, string payload) { var request = new InvokeRequest { FunctionName = FunctionName, Payload = payload, LogType = LogType.Tail }; return await lambdaClient.InvokeAsync(request); } protected async Task UpdateHandlerAsync(IAmazonLambda lambdaClient, string handler, Dictionary<string, string> environmentVariables = null) { if(environmentVariables == null) { environmentVariables = new Dictionary<string, string>(); } environmentVariables["TEST_HANDLER"] = handler; var updateFunctionConfigurationRequest = new UpdateFunctionConfigurationRequest { FunctionName = FunctionName, Environment = new Model.Environment { IsVariablesSet = true, Variables = environmentVariables } }; await lambdaClient.UpdateFunctionConfigurationAsync(updateFunctionConfigurationRequest); // Wait for eventual consistency of function change. var getConfigurationRequest = new GetFunctionConfigurationRequest { FunctionName = FunctionName }; GetFunctionConfigurationResponse getConfigurationResponse = null; do { await Task.Delay(1000); getConfigurationResponse = await lambdaClient.GetFunctionConfigurationAsync(getConfigurationRequest); } while (getConfigurationResponse.State == State.Pending); await Task.Delay(1000); } protected async Task CreateFunctionAsync(IAmazonLambda lambdaClient, string bucketName) { await DeleteFunctionIfExistsAsync(lambdaClient); var createRequest = new CreateFunctionRequest { FunctionName = FunctionName, Code = new FunctionCode { S3Bucket = bucketName, S3Key = DeploymentZipKey }, Handler = this.Handler, MemorySize = 512, Timeout = 30, Runtime = Runtime.Dotnet6, Role = ExecutionRoleArn }; var startTime = DateTime.Now; var created = false; while (DateTime.Now < startTime.AddSeconds(30)) { try { await lambdaClient.CreateFunctionAsync(createRequest); created = true; break; } catch (InvalidParameterValueException ipve) { // Wait for the role to be fully propagated through AWS if (ipve.Message == "The role defined for the function cannot be assumed by Lambda.") { await Task.Delay(2000); } else { throw; } } } await Task.Delay(5000); if (!created) { throw new Exception($"Timed out trying to create Lambda function {FunctionName}"); } } protected async Task DeleteFunctionIfExistsAsync(IAmazonLambda lambdaClient) { var request = new DeleteFunctionRequest { FunctionName = FunctionName }; try { var response = await lambdaClient.DeleteFunctionAsync(request); } catch (ResourceNotFoundException) { // no problem } } /// <summary> /// Get the path of the deployment package for testing the custom runtime. /// This assumes that the 'dotnet lambda package -c Release' command was run as part of the pre-build of this csproj. /// </summary> /// <returns></returns> private string GetDeploymentZipPath() { var testsProjectDirectory = FindUp(System.Environment.CurrentDirectory, TestsProjectDirectoryName, true); if (string.IsNullOrEmpty(testsProjectDirectory)) { throw new NoDeploymentPackageFoundException(); } var deploymentZipFile = Path.Combine(testsProjectDirectory, DeploymentPackageZipRelativePath.Replace('\\', Path.DirectorySeparatorChar)); if (!File.Exists(deploymentZipFile)) { throw new NoDeploymentPackageFoundException(); } return deploymentZipFile; } private static string FindUp(string path, string fileOrDirectoryName, bool combine) { var fullPath = Path.Combine(path, fileOrDirectoryName); if (File.Exists(fullPath) || Directory.Exists(fullPath)) { return combine ? fullPath : path; } else { var upDirectory = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(upDirectory)) { return null; } else { return FindUp(upDirectory, fileOrDirectoryName, combine); } } } protected class NoDeploymentPackageFoundException : Exception { } } }
347
aws-lambda-dotnet
aws
C#
using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Lambda.Model; using Amazon.S3; using Amazon.S3.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.APIGatewayEvents; using System.Text.Json; namespace Amazon.Lambda.RuntimeSupport.IntegrationTests { public class CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest : BaseCustomRuntimeTest { public CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest() : base("CustomRuntimeMinimalApiCustomSerializerTest-" + DateTime.Now.Ticks, "CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest.zip", @"CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest\bin\Release\net6.0\CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest.zip", "bootstrap") { } #if SKIP_RUNTIME_SUPPORT_INTEG_TESTS [Fact(Skip = "Skipped intentionally by setting the SkipRuntimeSupportIntegTests build parameter.")] #else [Fact] #endif public async Task TestMinimalApi() { // run all test cases in one test to ensure they run serially using (var lambdaClient = new AmazonLambdaClient(TestRegion)) using (var s3Client = new AmazonS3Client(TestRegion)) using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion)) { var roleAlreadyExisted = false; try { roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient); await InvokeSuccessToWeatherForecastController(lambdaClient); } catch (NoDeploymentPackageFoundException) { #if DEBUG // The CodePipeline for this project doesn't currently build the deployment in the stage that runs // this test. For now ignore this test in release mode if the deployment package can't be found. throw; #endif } finally { await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted); } } } #if SKIP_RUNTIME_SUPPORT_INTEG_TESTS [Fact(Skip = "Skipped intentionally by setting the SkipRuntimeSupportIntegTests build parameter.")] #else [Fact] #endif public async Task TestThreadingLogging() { // run all test cases in one test to ensure they run serially using (var lambdaClient = new AmazonLambdaClient(TestRegion)) using (var s3Client = new AmazonS3Client(TestRegion)) using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion)) { var roleAlreadyExisted = false; try { roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient); await InvokeLoggerTestController(lambdaClient); } catch (NoDeploymentPackageFoundException) { #if DEBUG // The CodePipeline for this project doesn't currently build the deployment in the stage that runs // this test. For now ignore this test in release mode if the deployment package can't be found. throw; #endif } finally { await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted); } } } private async Task InvokeSuccessToWeatherForecastController(IAmazonLambda lambdaClient) { var payload = File.ReadAllText("get-weatherforecast-request.json"); var response = await InvokeFunctionAsync(lambdaClient, payload); Assert.Equal(200, response.StatusCode); var apiGatewayResponse = System.Text.Json.JsonSerializer.Deserialize<APIGatewayHttpApiV2ProxyResponse>(response.Payload); Assert.Equal("application/json; charset=utf-8", apiGatewayResponse.Headers["Content-Type"]); Assert.Contains("temperatureC", apiGatewayResponse.Body); } private async Task InvokeLoggerTestController(IAmazonLambda lambdaClient) { var payload = File.ReadAllText("get-loggertest-request.json"); var response = await InvokeFunctionAsync(lambdaClient, payload); Assert.Equal(200, response.StatusCode); var apiGatewayResponse = System.Text.Json.JsonSerializer.Deserialize<APIGatewayHttpApiV2ProxyResponse>(response.Payload); Assert.Contains("90000", apiGatewayResponse.Body); } } }
119
aws-lambda-dotnet
aws
C#
using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Lambda.Model; using Amazon.S3; using Amazon.S3.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.APIGatewayEvents; using System.Text.Json; namespace Amazon.Lambda.RuntimeSupport.IntegrationTests { public class CustomRuntimeAspNetCoreMinimalApiTest : BaseCustomRuntimeTest { public CustomRuntimeAspNetCoreMinimalApiTest() : base("CustomRuntimeAspNetCoreMinimalApiTest-" + DateTime.Now.Ticks, "CustomRuntimeAspNetCoreMinimalApiTest.zip", @"CustomRuntimeAspNetCoreMinimalApiTest\bin\Release\net6.0\CustomRuntimeAspNetCoreMinimalApiTest.zip", "bootstrap") { } #if SKIP_RUNTIME_SUPPORT_INTEG_TESTS [Fact(Skip = "Skipped intentionally by setting the SkipRuntimeSupportIntegTests build parameter.")] #else [Fact] #endif public async Task TestMinimalApi() { // run all test cases in one test to ensure they run serially using (var lambdaClient = new AmazonLambdaClient(TestRegion)) using (var s3Client = new AmazonS3Client(TestRegion)) using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion)) { var roleAlreadyExisted = false; try { roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient); await InvokeSuccessToWeatherForecastController(lambdaClient); } catch (NoDeploymentPackageFoundException) { #if DEBUG // The CodePipeline for this project doesn't currently build the deployment in the stage that runs // this test. For now ignore this test in release mode if the deployment package can't be found. throw; #endif } finally { await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted); } } } #if SKIP_RUNTIME_SUPPORT_INTEG_TESTS [Fact(Skip = "Skipped intentionally by setting the SkipRuntimeSupportIntegTests build parameter.")] #else [Fact] #endif public async Task TestThreadingLogging() { // run all test cases in one test to ensure they run serially using (var lambdaClient = new AmazonLambdaClient(TestRegion)) using (var s3Client = new AmazonS3Client(TestRegion)) using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion)) { var roleAlreadyExisted = false; try { roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient); await InvokeLoggerTestController(lambdaClient); } catch (NoDeploymentPackageFoundException) { #if DEBUG // The CodePipeline for this project doesn't currently build the deployment in the stage that runs // this test. For now ignore this test in release mode if the deployment package can't be found. throw; #endif } finally { await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted); } } } private async Task InvokeSuccessToWeatherForecastController(IAmazonLambda lambdaClient) { var payload = File.ReadAllText("get-weatherforecast-request.json"); var response = await InvokeFunctionAsync(lambdaClient, payload); Assert.Equal(200, response.StatusCode); var apiGatewayResponse = System.Text.Json.JsonSerializer.Deserialize<APIGatewayHttpApiV2ProxyResponse>(response.Payload); Assert.Equal("application/json; charset=utf-8", apiGatewayResponse.Headers["Content-Type"]); Assert.Contains("temperatureC", apiGatewayResponse.Body); } private async Task InvokeLoggerTestController(IAmazonLambda lambdaClient) { var payload = File.ReadAllText("get-loggertest-request.json"); var response = await InvokeFunctionAsync(lambdaClient, payload); Assert.Equal(200, response.StatusCode); var apiGatewayResponse = System.Text.Json.JsonSerializer.Deserialize<APIGatewayHttpApiV2ProxyResponse>(response.Payload); Assert.Contains("90000", apiGatewayResponse.Body); } } }
119
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Lambda.Model; using Amazon.S3; using Amazon.S3.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.Lambda.RuntimeSupport.IntegrationTests { public class CustomRuntimeTests : BaseCustomRuntimeTest { public CustomRuntimeTests() : base("CustomRuntimeFunctionTest-" + DateTime.Now.Ticks, "CustomRuntimeFunctionTest.zip", @"CustomRuntimeFunctionTest\bin\Release\net6.0\CustomRuntimeFunctionTest.zip", "CustomRuntimeFunctionTest") { } #if SKIP_RUNTIME_SUPPORT_INTEG_TESTS [Fact(Skip = "Skipped intentionally by setting the SkipRuntimeSupportIntegTests build parameter.")] #else [Fact] #endif public async Task TestAllHandlersAsync() { // run all test cases in one test to ensure they run serially using (var lambdaClient = new AmazonLambdaClient(TestRegion)) using (var s3Client = new AmazonS3Client(TestRegion)) using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion)) { var roleAlreadyExisted = false; try { roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient); await RunTestExceptionAsync(lambdaClient, "ExceptionNonAsciiCharacterUnwrappedAsync", "", "Exception", "Unhandled exception with non ASCII character: ♂"); await RunTestSuccessAsync(lambdaClient, "UnintendedDisposeTest", "not-used", "UnintendedDisposeTest-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "LoggingStressTest", "not-used", "LoggingStressTest-success"); await RunLoggingTestAsync(lambdaClient, "LoggingTest", null); await RunLoggingTestAsync(lambdaClient, "LoggingTest", "debug"); await RunUnformattedLoggingTestAsync(lambdaClient, "LoggingTest"); await RunTestSuccessAsync(lambdaClient, "ToUpperAsync", "message", "ToUpperAsync-MESSAGE"); await RunTestSuccessAsync(lambdaClient, "PingAsync", "ping", "PingAsync-pong"); await RunTestSuccessAsync(lambdaClient, "HttpsWorksAsync", "", "HttpsWorksAsync-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "CertificateCallbackWorksAsync", "", "CertificateCallbackWorksAsync-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "NetworkingProtocolsAsync", "", "NetworkingProtocolsAsync-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "HandlerEnvVarAsync", "", "HandlerEnvVarAsync-CustomRuntimeFunctionTest"); await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrappedAsync", "", "Exception", "Exception thrown from an async handler."); await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrapped", "", "Exception", "Exception thrown from a synchronous handler."); await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrappedAsync", "", "AggregateException", "AggregateException thrown from an async handler."); await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrapped", "", "AggregateException", "AggregateException thrown from a synchronous handler."); await RunTestExceptionAsync(lambdaClient, "TooLargeResponseBodyAsync", "", "Function.ResponseSizeTooLarge", "Response payload size exceeded maximum allowed payload size (6291556 bytes)."); await RunTestSuccessAsync(lambdaClient, "LambdaEnvironmentAsync", "", "LambdaEnvironmentAsync-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "LambdaContextBasicAsync", "", "LambdaContextBasicAsync-SUCCESS"); await RunTestSuccessAsync(lambdaClient, "GetTimezoneNameAsync", "", "GetTimezoneNameAsync-UTC"); } catch(NoDeploymentPackageFoundException) { #if DEBUG // The CodePipeline for this project doesn't currently build the deployment in the stage that runs // this test. For now ignore this test in release mode if the deployment package can't be found. throw; #endif } finally { await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted); } } } private async Task RunTestExceptionAsync(AmazonLambdaClient lambdaClient, string handler, string input, string expectedErrorType, string expectedErrorMessage) { await UpdateHandlerAsync(lambdaClient, handler); var invokeResponse = await InvokeFunctionAsync(lambdaClient, JsonConvert.SerializeObject(input)); Assert.True(invokeResponse.HttpStatusCode == System.Net.HttpStatusCode.OK); Assert.True(invokeResponse.FunctionError != null); using (var responseStream = invokeResponse.Payload) using (var sr = new StreamReader(responseStream)) { JObject exception = (JObject)JsonConvert.DeserializeObject(await sr.ReadToEndAsync()); Assert.Equal(expectedErrorType, exception["errorType"].ToString()); Assert.Equal(expectedErrorMessage, exception["errorMessage"].ToString()); var log = System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(invokeResponse.LogResult)); var logExpectedException = expectedErrorType != "Function.ResponseSizeTooLarge" ? expectedErrorType : "RuntimeApiClientException"; Assert.Contains(logExpectedException, log); } } private async Task RunLoggingTestAsync(AmazonLambdaClient lambdaClient, string handler, string logLevel) { var environmentVariables = new Dictionary<string, string>(); if(!string.IsNullOrEmpty(logLevel)) { environmentVariables["AWS_LAMBDA_HANDLER_LOG_LEVEL"] = logLevel; } await UpdateHandlerAsync(lambdaClient, handler, environmentVariables); var invokeResponse = await InvokeFunctionAsync(lambdaClient, JsonConvert.SerializeObject("")); Assert.True(invokeResponse.HttpStatusCode == System.Net.HttpStatusCode.OK); Assert.True(invokeResponse.FunctionError == null); var log = System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(invokeResponse.LogResult)); Assert.Contains("info\tA information log", log); Assert.Contains("warn\tA warning log", log); Assert.Contains("fail\tA error log", log); Assert.Contains("crit\tA critical log", log); Assert.Contains("info\tA stdout info message", log); Assert.Contains("fail\tA stderror error message", log); if (string.IsNullOrEmpty(logLevel)) { Assert.DoesNotContain($"a {logLevel} log".ToLower(), log.ToLower()); } else { Assert.Contains($"a {logLevel} log".ToLower(), log.ToLower()); } } private async Task RunUnformattedLoggingTestAsync(AmazonLambdaClient lambdaClient, string handler) { var environmentVariables = new Dictionary<string, string>(); environmentVariables["AWS_LAMBDA_HANDLER_LOG_FORMAT"] = "Unformatted"; await UpdateHandlerAsync(lambdaClient, handler, environmentVariables); var invokeResponse = await InvokeFunctionAsync(lambdaClient, JsonConvert.SerializeObject("")); Assert.True(invokeResponse.HttpStatusCode == System.Net.HttpStatusCode.OK); Assert.True(invokeResponse.FunctionError == null); var log = System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(invokeResponse.LogResult)); Assert.DoesNotContain("info\t", log); Assert.DoesNotContain("warn\t", log); Assert.DoesNotContain("fail\t", log); Assert.DoesNotContain("crit\t", log); Assert.Contains("A information log", log); Assert.Contains("A warning log", log); Assert.Contains("A error log", log); Assert.Contains("A critical log", log); } private async Task RunTestSuccessAsync(AmazonLambdaClient lambdaClient, string handler, string input, string expectedResponse) { await UpdateHandlerAsync(lambdaClient, handler); var invokeResponse = await InvokeFunctionAsync(lambdaClient, JsonConvert.SerializeObject(input)); Assert.True(invokeResponse.HttpStatusCode == System.Net.HttpStatusCode.OK); Assert.True(invokeResponse.FunctionError == null); using (var responseStream = invokeResponse.Payload) using (var sr = new StreamReader(responseStream)) { var responseString = JsonConvert.DeserializeObject<string>(await sr.ReadToEndAsync()); Assert.Equal(expectedResponse, responseString); } } } }
191
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Diagnostics; using System.IO; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public static class Common { public const string WorkingHandler = "HandlerTest::HandlerTest.CustomerType::PocoInPocoOut"; /// <summary> /// Recursively check the Exception and inner exceptions to see if any of them are AggregateExceptions. /// </summary> /// <param name="e"></param> /// <param name="expectAggregateException">true if AggregateException is expected, false if not expected, null to skip check</param> public static void CheckForAggregateException(Exception e, bool? expectAggregateException) { if (expectAggregateException.HasValue) { if (e is AggregateException) { // We came across an AggregateException. Make sure we were expecting it. Assert.True(expectAggregateException, "Didn't expect an AggregateException but got one"); } else if (e.InnerException == null) { // We didn't come across an AggregateException. Make sure we weren't expecting to. Assert.False(expectAggregateException, "Expected an AggregateException but didn't get one."); } else { // e isn't an AggregateException and there's an InnerException - call recursively. CheckForAggregateException(e.InnerException, expectAggregateException); } } } public static void CheckException(Exception e, string expectedPartialMessage) { if (!FindMatchingExceptionMessage(e, expectedPartialMessage)) { Assert.True(false, $"Unable to match up expected message '{expectedPartialMessage}' in exception: {GetAllMessages(e)}"); } } public static bool FindMatchingExceptionMessage(Exception e, string expectedPartialMessage) { var isMatch = e.Message.IndexOf(expectedPartialMessage) >= 0; if (isMatch) { return true; } if (e.InnerException != null) { return FindMatchingExceptionMessage(e.InnerException, expectedPartialMessage); } return false; } public static string GetAllMessages(Exception e) { using (var writer = new StringWriter()) { while (e != null) { writer.WriteLine("[{0}]", e.Message); e = e.InnerException; } return writer.ToString(); } } } }
92
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Amazon.Lambda.RuntimeSupport.Helpers; using Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class FileDescriptorLogStreamTests { private const int HeaderLength = FileDescriptorLogFactory.LambdaTelemetryLogHeaderLength; private const int LogEntryMaxLength = FileDescriptorLogFactory.MaxCloudWatchLogEventSize; private static readonly byte[] ExpectedMagicBytes = { 0xA5, 0x5A, 0x00, 0x03 }; [Fact] public void MultilineLoggingInSingleLogEntryWithTlvFormat() { var logs = new List<byte[]>(); var offsets = new List<int>(); var counts = new List<int>(); var stream = new TestFileStream((log, offset, count) => { logs.Add(log); offsets.Add(offset); counts.Add(count); }); TextWriter writer = FileDescriptorLogFactory.InitializeWriter(stream); // assert that initializing the stream does not result in UTF-8 preamble log entry Assert.Empty(counts); Assert.Empty(offsets); Assert.Empty(logs); const string logMessage = "hello world\nsomething else on a new line."; int logMessageLength = logMessage.Length; writer.Write(logMessage); Assert.Equal(2, offsets.Count); int headerLogEntryOffset = offsets[0]; int consoleLogEntryOffset = offsets[1]; Assert.Equal(0, headerLogEntryOffset); Assert.Equal(0, consoleLogEntryOffset); Assert.Equal(2, counts.Count); int headerLogEntrySize = counts[0]; int consoleLogEntrySize = counts[1]; Assert.Equal(HeaderLength, headerLogEntrySize); Assert.Equal(logMessageLength, consoleLogEntrySize); Assert.Equal(2, logs.Count); byte[] headerLogEntry = logs[0]; byte[] consoleLogEntry = logs[1]; Assert.Equal(HeaderLength, headerLogEntry.Length); Assert.Equal(logMessageLength, consoleLogEntry.Length); byte[] expectedLengthBytes = { 0x00, 0x00, 0x00, 0x29 }; AssertHeaderBytes(headerLogEntry, expectedLengthBytes); Assert.Equal(logMessage, Encoding.UTF8.GetString(consoleLogEntry)); } [Fact] public void MaxSizeProducesOneLogFrame() { var logs = new List<byte[]>(); var offsets = new List<int>(); var counts = new List<int>(); var stream = new TestFileStream((log, offset, count) => { logs.Add(log); offsets.Add(offset); counts.Add(count); }); TextWriter writer = FileDescriptorLogFactory.InitializeWriter(stream); // assert that initializing the stream does not result in UTF-8 preamble log entry Assert.Empty(counts); Assert.Empty(offsets); Assert.Empty(logs); string logMessage = new string('a', LogEntryMaxLength - 1) + "b"; writer.Write(logMessage); Assert.Equal(2, offsets.Count); int headerLogEntryOffset = offsets[0]; int consoleLogEntryOffset = offsets[1]; Assert.Equal(0, headerLogEntryOffset); Assert.Equal(0, consoleLogEntryOffset); Assert.Equal(2, counts.Count); int headerLogEntrySize = counts[0]; int consoleLogEntrySize = counts[1]; Assert.Equal(HeaderLength, headerLogEntrySize); Assert.Equal(LogEntryMaxLength, consoleLogEntrySize); Assert.Equal(2, logs.Count); byte[] headerLogEntry = logs[0]; byte[] consoleLogEntry = logs[1]; Assert.Equal(HeaderLength, headerLogEntry.Length); Assert.Equal(LogEntryMaxLength, consoleLogEntry.Length); byte[] expectedLengthBytes = { 0x00, 0x03, 0xFF, 0xE6 }; AssertHeaderBytes(headerLogEntry, expectedLengthBytes); Assert.Equal(logMessage, Encoding.UTF8.GetString(consoleLogEntry)); } [Fact] public void LogEntryAboveMaxSizeProducesMultipleLogFrames() { var logs = new List<byte[]>(); var offsets = new List<int>(); var counts = new List<int>(); var stream = new TestFileStream((log, offset, count) => { logs.Add(log); offsets.Add(offset); counts.Add(count); }); TextWriter writer = FileDescriptorLogFactory.InitializeWriter(stream); // assert that initializing the stream does not result in UTF-8 preamble log entry Assert.Empty(counts); Assert.Empty(offsets); Assert.Empty(logs); string logMessage = new string('a', LogEntryMaxLength) + "b"; writer.Write(logMessage); Assert.Equal(4, offsets.Count); int headerLogEntryOffset = offsets[0]; int consoleLogEntryOffset = offsets[1]; int headerLogSecondEntryOffset = offsets[2]; int consoleLogSecondEntryOffset = offsets[3]; Assert.Equal(0, headerLogEntryOffset); Assert.Equal(0, consoleLogEntryOffset); Assert.Equal(0, headerLogSecondEntryOffset); Assert.Equal(0, consoleLogSecondEntryOffset); Assert.Equal(4, counts.Count); int headerLogEntrySize = counts[0]; int consoleLogEntrySize = counts[1]; int headerLogSecondEntrySize = counts[2]; int consoleLogSecondEntrySize = counts[3]; Assert.Equal(HeaderLength, headerLogEntrySize); Assert.Equal(LogEntryMaxLength, consoleLogEntrySize); Assert.Equal(HeaderLength, headerLogSecondEntrySize); Assert.Equal(1, consoleLogSecondEntrySize); Assert.Equal(4, logs.Count); byte[] headerLogEntry = logs[0]; byte[] consoleLogEntry = logs[1]; byte[] headerLogSecondEntry = logs[2]; byte[] consoleLogSecondEntry = logs[3]; Assert.Equal(HeaderLength, headerLogEntry.Length); Assert.Equal(LogEntryMaxLength, consoleLogEntry.Length); Assert.Equal(HeaderLength, headerLogSecondEntry.Length); Assert.Single(consoleLogSecondEntry); byte[] expectedLengthBytes = { 0x00, 0x03, 0xFF, 0xE6 }; AssertHeaderBytes(headerLogEntry, expectedLengthBytes); byte[] expectedLengthBytesSecondEntry = { 0x00, 0x00, 0x00, 0x01 }; AssertHeaderBytes(headerLogSecondEntry, expectedLengthBytesSecondEntry); string expectedLogEntry = logMessage.Substring(0, LogEntryMaxLength); string expectedSecondLogEntry = logMessage.Substring(LogEntryMaxLength); Assert.Equal(expectedLogEntry, Encoding.UTF8.GetString(consoleLogEntry)); Assert.Equal(expectedSecondLogEntry, Encoding.UTF8.GetString(consoleLogSecondEntry)); } private static void AssertHeaderBytes(byte[] buf, byte[] expectedLengthBytes) { byte[] actualHeaderMagicBytes = buf.Take(4).ToArray(); byte[] actualHeaderLengthBytes = buf.Skip(4).Take(4).ToArray(); Assert.Equal(ExpectedMagicBytes, actualHeaderMagicBytes); Assert.Equal(expectedLengthBytes, actualHeaderLengthBytes); } } }
194
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Loader; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport.Bootstrap; using Amazon.Lambda.RuntimeSupport.ExceptionHandling; using Amazon.Lambda.RuntimeSupport.Helpers; using Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers; using Xunit; using Xunit.Abstractions; namespace Amazon.Lambda.RuntimeSupport.UnitTests { [Collection("Bootstrap")] public class HandlerTests { private const string AggregateExceptionTestMarker = "AggregateExceptionTesting"; private readonly InternalLogger _internalLogger; private readonly ITestOutputHelper _output; private const string ContextData = "==[Amazon.Lambda.RuntimeSupport.LambdaContext;Request1;Amazon.Lambda.RuntimeSupport.CognitoClientContext;" + "AppPackageName1;AppTitle1;AppVersionCode1;AppVersionName1;InstallationId1;CustomKey1, CustomKey2;" + "CustomValue1, CustomValue2;EnvironmentKey1, EnvironmentKey2;EnvironmentValue1, EnvironmentValue2;Name1;" + "Version1;Id1;Pool1;Arn1;Amazon.Lambda.RuntimeSupport.LambdaConsoleLogger;Group1;Stream1;42;420000000]=="; private static readonly Action<string> NoOpLoggingAction = message => { }; private readonly Dictionary<string, IEnumerable<string>> _headers; private readonly TestEnvironmentVariables _environmentVariables; // private readonly TestRuntimeApiClient _testRuntimeApiClient; public HandlerTests(ITestOutputHelper output) { // setup logger to write to optionally console _internalLogger = InternalLogger.GetCustomInternalLogger(output.WriteLine); _output = output; var testDateTimeHelper = new TestDateTimeHelper(); var cognitoClientContext = File.ReadAllText("CognitoClientContext.json"); var cognitoIdentity = File.ReadAllText("CognitoIdentity.json"); _headers = new Dictionary<string, IEnumerable<string>> { { RuntimeApiHeaders.HeaderAwsRequestId, new List<string> { "Request1" } }, { RuntimeApiHeaders.HeaderInvokedFunctionArn, new List<string> { "Arn1" } }, { RuntimeApiHeaders.HeaderClientContext, new List<string> { cognitoClientContext } }, { RuntimeApiHeaders.HeaderCognitoIdentity, new List<string> { cognitoIdentity } }, { RuntimeApiHeaders.HeaderDeadlineMs, new List<string> { $"{(testDateTimeHelper.UtcNow - LambdaContext.UnixEpoch + TimeSpan.FromSeconds(42)).TotalMilliseconds}" } } // (2020, 1, 1) + 42 seconds }; var env = new Dictionary<string, string> { { LambdaEnvironment.EnvVarFunctionName, "Name1" }, { LambdaEnvironment.EnvVarFunctionVersion, "Version1" }, { LambdaEnvironment.EnvVarLogGroupName, "Group1" }, { LambdaEnvironment.EnvVarLogStreamName, "Stream1" }, { LambdaEnvironment.EnvVarFunctionMemorySize, "42" }, }; _environmentVariables = new TestEnvironmentVariables(env); } [Fact] [Trait("Category", "UserCodeLoader")] public async Task PositiveHandlerTestsAsync() { const string testData = "Test data!"; var dataIn = $"\"{testData}\""; var pocoData = $"{{ \"Data\": \"{testData}\" }}"; await TestMethodAsync("ZeroInZeroOut"); await TestMethodAsync("StringInZeroOut", dataIn, testData); await TestMethodAsync("StreamInZeroOut", dataIn, dataIn); await TestMethodAsync("ContextInZeroOut"); await TestMethodAsync("ContextAndStringInZeroOut", dataIn, testData); await TestMethodAsync("ContextAndStreamInZeroOut", dataIn, dataIn); await TestMethodAsync("ContextAndPocoInZeroOut", pocoData, testData); await TestMethodAsync("ZeroInStringOut"); await TestMethodAsync("ZeroInStreamOut"); await TestMethodAsync("ZeroInMemoryStreamOut"); await TestMethodAsync("ZeroInPocoOut"); await TestMethodAsync("StringInStringOut", dataIn, testData); await TestMethodAsync("StreamInStreamOut", dataIn, dataIn); await TestMethodAsync("PocoInPocoOut", pocoData, testData); await TestMethodAsync("PocoInPocoOutStatic", pocoData, testData); await TestMethodAsync("ContextAndPocoInPocoOut", pocoData, testData); await TestMethodAsync("HandlerTest.CustomerPoco PocoInPocoOut(HandlerTest.CustomerPoco)", pocoData, testData); await TestMethodAsync("ZeroInTaskOut"); await TestMethodAsync("ZeroInTaskStringOut"); await TestMethodAsync("ZeroInTaskStreamOut"); await TestMethodAsync("ZeroInTaskPocoOut"); await TestMethodAsync("ZeroInTask2Out"); await TestMethodAsync("ZeroInTTask2Out"); await TestMethodAsync("ZeroInTTask3Out"); await TestMethodAsync("ZeroInTTask4Out"); await TestMethodAsync("ZeroInTTask5Out"); await TestMethodAsync("CustomSerializerMethod"); await TestHandlerAsync("HandlerTest::HandlerTest.AbstractCustomerType::NonAbstractMethodStringInStringOut", dataIn, testData); await TestHandlerAsync("HandlerTest::HandlerTest.SubclassOfGenericCustomerType::TInTOut", dataIn, testData); await TestHandlerAsync("HandlerTest::HandlerTest.StaticCustomerType::StaticCustomerMethodZeroOut", null, null, "StaticCustomerType static constructor has run."); await TestHandlerAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskOut", null, null, null); await TestHandlerAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskStringOut", null, null, null); var execInfo = await ExecMethodAsync("StreamInSameStreamOut_NonCommon", dataIn, null); Assert.Equal(dataIn, execInfo.DataIn); Assert.Equal(dataIn, execInfo.DataOut); } [Fact] [Trait("Category", "UserCodeLoader")] public async Task NegativeBootstrapInitTestsAsync() { var ucl = new UserCodeLoader("NonExistentAssembly::HandlerTest.CustomerType::ZeroInZeroOut", _internalLogger); var ex = Assert.Throws<LambdaValidationException>(() => ucl.Init(NoOpLoggingAction)); Assert.Contains("Could not find the specified handler", ex.Message); await TestHandlerFailAsync($"HandlerTest2::Type::Method", "Could not find the specified handler assembly with the file name"); await TestHandlerFailAsync("HandlerTest::HandlerTest.FakeCustomerType::PocoInPocoOut", "Unable to load type"); await TestHandlerFailAsync("HandlerTest::HandlerTest.GenericCustomerType`1::PocoInPocoOut", "Handler methods cannot be located in generic types."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::FakeMethod", "Found no methods matching method name 'FakeMethod'"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::HandlerTest.CustomerPoco FakeMethod(HandlerTest.CustomerPoco)", "Found no methods matching method name '"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::OverloadedMethod", "appears to have a number of overloads. To call this method please specify a complete method signature."); await TestHandlerFailAsync("HandlerTest::HandlerTest.AbstractCustomerType::AbstractMethod", "Please specify a non-abstract handler method."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::GenericMethod", "Handler methods cannot be generic."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::TwoInputsNoContextMethod", "is not supported: the method has 2 parameters, but the second parameter is not of type"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::TooManyInputsMethod", "is not supported: the method has more than 2 parameters."); await TestHandlerFailAsync("HandlerTestNoSerializer::HandlerTestNoSerializer.CustomerType::PocoInPocoOut", $"To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with {typeof(LambdaSerializerAttribute).FullName}."); await TestHandlerFailAsync("HandlerTestNoSerializer::HandlerTestNoSerializer.CustomerType::PocoInPocoOut", $"To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with {typeof(LambdaSerializerAttribute).FullName}."); var noZeroParamTypeEx = await TestHandlerFailAsync("HandlerTest::HandlerTest.NoZeroParamConstructorCustomerType::SimpleMethod", "No parameterless constructor defined"); Assert.IsAssignableFrom<MissingMethodException>(noZeroParamTypeEx); var customerConstructorEx = TestHandlerFailAsync("HandlerTest::HandlerTest.ConstructorExceptionCustomerType::SimpleMethod", "An exception was thrown when the constructor for type"); Assert.NotNull(customerConstructorEx); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::NoZeroParameterConstructorCustomerTypeSerializerMethod", "does not define a public zero-parameter constructor"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::NoInterfaceCustomerTypeSerializerMethod", "it does not implement the 'ILambdaSerializer' interface."); await TestHandlerFailAsync("HandlerTest::HandlerTest.StaticCustomerTypeThrows::StaticCustomerMethodZeroOut", "StaticCustomerTypeThrows static constructor has thrown an exception."); } [Fact] [Trait("Category", "HandlerInfo")] public void NegativeHandlerInfoTests() { Assert.Throws<LambdaValidationException>(() => new HandlerInfo(null)); Assert.Throws<LambdaValidationException>(() => new HandlerInfo(" ::B::C")); Assert.Throws<LambdaValidationException>(() => new HandlerInfo("A:: ::C")); Assert.Throws<LambdaValidationException>(() => new HandlerInfo("A::B:: ")); var ucl = new HandlerInfo("A::B::C::D"); Assert.NotNull(ucl); Assert.Equal("A", ucl.AssemblyName.Name); Assert.Equal("B", ucl.TypeName); Assert.Equal("C::D", ucl.MethodName); } [Fact] [Trait("Category", "UserCodeLoader")] public async Task NegativeHandlerFailTestsAsync() { await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::Varargs", "Please specify a method that is not 'vararg'."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::Params", "Please specify a method that does not use 'params'."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::MethodThatDoesNotExist", "Found no methods matching method name"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::OverloadedMethod", "The method 'OverloadedMethod' in type 'HandlerTest.CustomerType' appears to have a number of overloads. To call this method please specify a complete method signature. Possible candidates are:\nSystem.String OverloadedMethod(System.String)\nSystem.IO.Stream OverloadedMethod(System.IO.Stream)"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::AsyncVoid", "Handler methods cannot be 'async void'. Please specify a method that is not 'async void'."); } [Fact] [Trait("Category", "UserCodeLoader")] public async Task UnwrapAggregateExceptionFailTestsAsync() { // unwrap AggregateException await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskOutThrowsException", AggregateExceptionTestMarker, false); // AggregateException thrown explicitly, won't get unwrapped whether we tell it to or not. await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskOutThrowsAggregateExceptionExplicitly", AggregateExceptionTestMarker, true); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskOutThrowsAggregateExceptionExplicitly", AggregateExceptionTestMarker, true); // unwrap AggregateException await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskStringOutThrowsException", AggregateExceptionTestMarker, false); // AggregateException thrown explicitly, won't get unwrapped whether we tell it to or not. await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskStringOutThrowsAggregateExceptionExplicitly", AggregateExceptionTestMarker, true); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::ZeroInTaskStringOutThrowsAggregateExceptionExplicitly", AggregateExceptionTestMarker, true); } [Fact] [Trait("Category", "UserCodeLoader")] public void NegativeILambdaSerializerTests() { TestILambdaSerializer(typeof(ILSClass), " is not an interface"); TestILambdaSerializer(typeof(ILSEmpty), "'Deserialize' method not found"); TestILambdaSerializer(typeof(ILSDeserializeNongeneric), "'Deserialize' method is not generic, expected to be generic"); TestILambdaSerializer(typeof(ILSDeserializeNoInputs), "'Deserialize' method has '0' parameters, expected '1'"); TestILambdaSerializer(typeof(ILSDeserializeWrongInput), "'Deserialize' method has parameter of type 'System.String', expected type 'System.IO.Stream'"); TestILambdaSerializer(typeof(ILSDeserializeWrongGenerics), "'Deserialize' method has '2' generic arguments, expected '1'"); TestILambdaSerializer(typeof(ILSDeserializeWrongOutput), "'Deserialize' method has return type of 'System.Object', expected 'T'"); TestILambdaSerializer(typeof(ILSSerializeMissing), "'Serialize' method not found"); TestILambdaSerializer(typeof(ILSSerializeNotGeneric), "'Serialize' method is not generic, expected to be generic"); TestILambdaSerializer(typeof(ILSSerializeNotVoid), "'Serialize' method has return type of 'System.Object', expected 'void'"); TestILambdaSerializer(typeof(ILSSerializeNoInputs), "'Serialize' method has '0' parameters, expected '2'"); TestILambdaSerializer(typeof(ILSSerializeWrongGenerics), "'Serialize' method has '2' generic arguments, expected '1'"); TestILambdaSerializer(typeof(ILSSerializeWrongFirstInput), "'Serialize' method's first parameter is of type 'System.Boolean', expected 'T'"); TestILambdaSerializer(typeof(ILSSerializeWrongSecondInput), "'Serialize' method's second parameter is of type 'System.String', expected 'System.IO.Stream'"); } private void TestILambdaSerializer(Type wrongType, string expectedPartialMessage) { _output.WriteLine($"Testing ILambdaSerializer {wrongType.FullName}"); var exception = Assert.ThrowsAny<Exception>(() => UserCodeValidator.ValidateILambdaSerializerType(wrongType)); Assert.NotNull(exception); Common.CheckException(exception, expectedPartialMessage); } private async Task<Exception> TestHandlerFailAsync(string handler, string expectedPartialMessage, bool? expectAggregateException = null) { _output.WriteLine($"Testing handler {handler}"); var testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables, _headers); var userCodeLoader = new UserCodeLoader(handler, _internalLogger); var initializer = new UserCodeInitializer(userCodeLoader, _internalLogger); var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke); var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync) { Client = testRuntimeApiClient }; using (var cancellationTokenSource = new CancellationTokenSource()) { var exceptionWaiterTask = Task.Run(() => { _output.WriteLine($"Waiting for an exception."); while (testRuntimeApiClient.LastRecordedException == null) { } _output.WriteLine($"Exception available."); cancellationTokenSource.Cancel(); return testRuntimeApiClient.LastRecordedException; }); await Record.ExceptionAsync(async () => { await bootstrap.RunAsync(cancellationTokenSource.Token); }); var exception = await exceptionWaiterTask; Assert.NotNull(exception); Common.CheckException(exception, expectedPartialMessage); Common.CheckForAggregateException(exception, expectAggregateException); return exception; } } private async Task<string> InvokeAsync(LambdaBootstrap bootstrap, string dataIn, TestRuntimeApiClient testRuntimeApiClient) { testRuntimeApiClient.FunctionInput = dataIn != null ? Encoding.UTF8.GetBytes(dataIn) : new byte[0]; using (var cancellationTokenSource = new CancellationTokenSource()) { var exceptionWaiterTask = Task.Run(async () => { _output.WriteLine($"Waiting for an output."); while (testRuntimeApiClient.LastOutputStream == null) { } _output.WriteLine($"Output available."); cancellationTokenSource.Cancel(); using (var reader = new StreamReader(testRuntimeApiClient.LastOutputStream)) { return await reader.ReadToEndAsync(); } }); await bootstrap.RunAsync(cancellationTokenSource.Token); return await exceptionWaiterTask; } } private Task<ExecutionInfo> TestMethodAsync(string methodName, string dataIn = null, string testData = null) { var handler = $"HandlerTest::HandlerTest.CustomerType::{methodName}"; return TestHandlerAsync(handler, dataIn, testData); } private async Task<ExecutionInfo> TestHandlerAsync(string handler, string dataIn, string testData, string assertLoggedByInitialize = null) { _output.WriteLine($"Testing handler '{handler}'"); var execInfo = await ExecHandlerAsync(handler, dataIn, assertLoggedByInitialize); var customerMethodInfo = execInfo.UserCodeLoader.CustomerMethodInfo; var trueMethodName = customerMethodInfo.Name; var isCommon = !trueMethodName.Contains("_NonCommon"); // Check logged data on common methods if (isCommon) { var fullMethodName = customerMethodInfo.ToString(); var isContextMethod = trueMethodName.Contains("Context"); var isVoidMethod = trueMethodName.Contains("ZeroOut") || trueMethodName.Contains("TaskOut") || trueMethodName.Equals("ZeroInTask2Out"); Assert.True(execInfo.LoggingActionText.Contains($">>[{trueMethodName}]>>") || execInfo.LoggingActionText.Contains($">>[{fullMethodName}]>>"), $"Can't find method name in console text for {trueMethodName}"); if (dataIn != null) { Assert.Contains($"<<[{testData}]<<", execInfo.LoggingActionText); } if (isContextMethod) { Assert.Contains(ContextData, execInfo.LoggingActionText); } if (!isVoidMethod) { Assert.NotNull(execInfo.DataOut); Assert.True(execInfo.DataOut.Contains($"(([{trueMethodName}]))") || execInfo.DataOut.Contains($"(([{fullMethodName}]))"), $"Expecting to find '{trueMethodName}' or '{fullMethodName}' in '{execInfo.DataOut}'"); } Assert.True(execInfo.LoggingActionText.Contains($"__[nullLogger-{trueMethodName}]__") || execInfo.LoggingActionText.Contains($"__[nullLogger-{fullMethodName}]__"), $"Can't find null logger output in action text for {trueMethodName}"); Assert.True(execInfo.LoggingActionText.Contains($"__[testLogger-{trueMethodName}]__") || execInfo.LoggingActionText.Contains($"__[testLogger-{fullMethodName}]__"), $"Can't find test logger output in action text for {trueMethodName}"); Assert.False(execInfo.LoggingActionText.Contains($"##[nullLogger-{trueMethodName}]##") || execInfo.LoggingActionText.Contains($"##[nullLogger-{fullMethodName}]##"), $"Found unexpected ILogger output in action text for {trueMethodName}: [{execInfo.LoggingActionText}]"); Assert.True(execInfo.LoggingActionText.Contains($"^^[{trueMethodName}]^^") || execInfo.LoggingActionText.Contains($"^^[{fullMethodName}]^^"), $"Can't find LambdaLogger output in action text for {trueMethodName}"); } return execInfo; } private Task<ExecutionInfo> ExecMethodAsync(string methodName, string dataIn, string assertLoggedByInitialize) { var handler = $"HandlerTest::HandlerTest.CustomerType::{methodName}"; return ExecHandlerAsync(handler, dataIn, assertLoggedByInitialize); } private async Task<ExecutionInfo> ExecHandlerAsync(string handler, string dataIn, string assertLoggedByInitialize) { // The actionWriter using (var actionWriter = new StringWriter()) { var testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables, _headers); var loggerAction = actionWriter.ToLoggingAction(); var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(UserCodeLoader.LambdaCoreAssemblyName)); UserCodeLoader.SetCustomerLoggerLogAction(assembly, loggerAction, _internalLogger); var userCodeLoader = new UserCodeLoader(handler, _internalLogger); var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke); var initializer = new UserCodeInitializer(userCodeLoader, _internalLogger); var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync) { Client = testRuntimeApiClient }; if (assertLoggedByInitialize != null) { Assert.False(actionWriter.ToString().Contains($"^^[{assertLoggedByInitialize}]^^")); } await bootstrap.InitializeAsync(); if (assertLoggedByInitialize != null) { Assert.True(actionWriter.ToString().Contains($"^^[{assertLoggedByInitialize}]^^")); } var dataOut = await InvokeAsync(bootstrap, dataIn, testRuntimeApiClient); var actionText = actionWriter.ToString(); return new ExecutionInfo(bootstrap, dataIn, dataOut, actionText, null, userCodeLoader); } } private class ExecutionInfo { public string DataIn { get; } public string DataOut { get; } public string LoggingActionText { get; } public LambdaBootstrap Bootstrap { get; } public Exception Exception { get; } public UserCodeLoader UserCodeLoader { get; } public ExecutionInfo(LambdaBootstrap bootstrap, string dataIn, string dataOut, string loggingActionTest, Exception exception, UserCodeLoader userCodeLoader) { Bootstrap = bootstrap; DataIn = dataIn; DataOut = dataOut; LoggingActionText = loggingActionTest; Exception = exception; UserCodeLoader = userCodeLoader; } } } }
438
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Core; using Amazon.Lambda.Serialization.Json; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class HandlerWrapperTests { private static readonly JsonSerializer Serializer = new JsonSerializer(); private static readonly byte[] EmptyBytes = null; private static readonly byte[] InputBytes = new byte[5] { 0, 1, 2, 3, 4 }; private static readonly byte[] OutputBytes = null; private const string StringInput = "mIxEd CaSe StRiNg"; private static readonly byte[] StringInputBytes = null; private const string StringOutput = "MIXED CASE STRING"; private static readonly byte[] StringOutputBytes = null; private static readonly PocoInput PocoInput = new PocoInput { InputInt = 0, InputString = "xyz" }; private static readonly byte[] PocoInputBytes = null; private static readonly PocoOutput PocoOutput = new PocoOutput { OutputInt = 10, OutputString = "XYZ" }; private static readonly byte[] PocoOutputBytes = null; static HandlerWrapperTests() { EmptyBytes = new byte[0]; OutputBytes = new byte[InputBytes.Length]; for (int i = 0; i < InputBytes.Length; i++) { OutputBytes[i] = (byte)(InputBytes[i] + 10); } MemoryStream tempStream; tempStream = new MemoryStream(); Serializer.Serialize(StringInput, tempStream); StringInputBytes = new byte[tempStream.Length]; tempStream.Position = 0; tempStream.Read(StringInputBytes, 0, StringInputBytes.Length); tempStream = new MemoryStream(); Serializer.Serialize(StringOutput, tempStream); StringOutputBytes = new byte[tempStream.Length]; tempStream.Position = 0; tempStream.Read(StringOutputBytes, 0, StringOutputBytes.Length); tempStream = new MemoryStream(); Serializer.Serialize(PocoInput, tempStream); PocoInputBytes = new byte[tempStream.Length]; tempStream.Position = 0; tempStream.Read(PocoInputBytes, 0, PocoInputBytes.Length); tempStream = new MemoryStream(); Serializer.Serialize(PocoOutput, tempStream); PocoOutputBytes = new byte[tempStream.Length]; tempStream.Position = 0; tempStream.Read(PocoOutputBytes, 0, PocoOutputBytes.Length); } private LambdaEnvironment _lambdaEnvironment; private RuntimeApiHeaders _runtimeApiHeaders; private Checkpoint _checkpoint; public HandlerWrapperTests() { var environmentVariables = new TestEnvironmentVariables(); _lambdaEnvironment = new LambdaEnvironment(environmentVariables); var headers = new Dictionary<string, IEnumerable<string>>(); headers.Add(RuntimeApiHeaders.HeaderAwsRequestId, new List<string>() { "request_id" }); headers.Add(RuntimeApiHeaders.HeaderInvokedFunctionArn, new List<string>() { "invoked_function_arn" }); _runtimeApiHeaders = new RuntimeApiHeaders(headers); _checkpoint = new Checkpoint(); } [Fact] public async Task TestTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async () => { await Task.Delay(0); _checkpoint.Check(); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false); } } [Fact] public async Task TestStreamTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, EmptyBytes, false); } } [Fact] public async Task TestPocoInputTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>(async (input) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, EmptyBytes, false); } } [Fact] public async Task TestILambdaContextTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (context) => { await Task.Delay(0); _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false); } } [Fact] public async Task TestStreamILambdaContextTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, EmptyBytes, false); } } [Fact] public async Task TestPocoInputILambdaContextTask() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, EmptyBytes, false); } } [Fact] public async Task TestTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async () => { await Task.Delay(0); _checkpoint.Check(); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, OutputBytes, true); } } [Fact] public async Task TestStreamTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, OutputBytes, true); } } [Fact] public async Task TestPocoInputTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>(async (input) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); return new MemoryStream(OutputBytes); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, OutputBytes, true); } } [Fact] public async Task TestContextTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (context) => { await Task.Delay(0); _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, OutputBytes, true); } } [Fact] public async Task TestStreamContextTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, OutputBytes, true); } } [Fact] public async Task TestPocoInputContextTaskOfStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, OutputBytes, true); } } [Fact] public async Task TestTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async () => { await Task.Delay(0); _checkpoint.Check(); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, PocoOutputBytes, false); } } [Fact] public async Task TestStreamTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, InputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestPocoInputTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput, PocoOutput>(async (input) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestILambdaContextTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (context) => { await Task.Delay(0); _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, PocoOutputBytes, false); } } [Fact] public async Task TestStreamILambdaContextTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, InputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestPocoInputILambdaContextTaskOfPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput, PocoOutput>(async (input, context) => { await Task.Delay(0); _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() => { _checkpoint.Check(); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false); } } [Fact] public async Task TestStreamVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input) => { _checkpoint.Check(); AssertEqual(InputBytes, input); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, EmptyBytes, false); } } [Fact] public async Task TestPocoInputVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>((input) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, EmptyBytes, false); } } [Fact] public async Task TestILambdaContextVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((context) => { _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, EmptyBytes, false); } } [Fact] public async Task TestStreamILambdaContextVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input, context) => { _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, EmptyBytes, false); } } [Fact] public async Task TestPocoInputILambdaContextVoid() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>((input, context) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, EmptyBytes, false); } } [Fact] public async Task TestVoidStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() => { _checkpoint.Check(); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, OutputBytes, true); } } [Fact] public async Task TestStreamStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input) => { _checkpoint.Check(); AssertEqual(InputBytes, input); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, OutputBytes, true); } } [Fact] public async Task TestPocoInputStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>((input) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); return new MemoryStream(OutputBytes); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, OutputBytes, true); } } [Fact] public async Task TestILambdaContextStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((context) => { _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, OutputBytes, true); } } [Fact] public async Task TestStreamILambdaContextStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input, context) => { _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); })) { await TestHandlerWrapper(handlerWrapper, InputBytes, OutputBytes, true); } } [Fact] public async Task TestPocoInputILambdaContextStream() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput>((input, context) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); return new MemoryStream(OutputBytes); }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, OutputBytes, true); } } [Fact] public async Task TestVoidPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(() => { _checkpoint.Check(); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, PocoOutputBytes, false); } } [Fact] public async Task TestStreamPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input) => { _checkpoint.Check(); AssertEqual(InputBytes, input); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, InputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestPocoInputPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput, PocoOutput>((input) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestILambdaContextPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((context) => { _checkpoint.Check(); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, EmptyBytes, PocoOutputBytes, false); } } [Fact] public async Task TestStreamILambdaContextPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper((input, context) => { _checkpoint.Check(); AssertEqual(InputBytes, input); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, InputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestPocoInputILambdaContextPocoOutput() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<PocoInput, PocoOutput>((input, context) => { _checkpoint.Check(); Assert.Equal(PocoInput, input); Assert.NotNull(context.AwsRequestId); return PocoOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, PocoInputBytes, PocoOutputBytes, false); } } [Fact] public async Task TestSerializtionOfString() { using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper<string, string>((input) => { _checkpoint.Check(); Assert.Equal(StringInput, input); return StringOutput; }, Serializer)) { await TestHandlerWrapper(handlerWrapper, StringInputBytes, StringOutputBytes, false); } } private async Task TestHandlerWrapper(HandlerWrapper handlerWrapper, byte[] input, byte[] expectedOutput, bool expectedDisposeOutputStream) { // run twice to make sure wrappers that reuse the output stream work correctly for (int i = 0; i < 2; i++) { var invocation = new InvocationRequest { InputStream = new MemoryStream(input ?? new byte[0]), LambdaContext = new LambdaContext(_runtimeApiHeaders, _lambdaEnvironment, new Helpers.SimpleLoggerWriter()) }; var invocationResponse = await handlerWrapper.Handler(invocation); Assert.True(_checkpoint.IsChecked); Assert.Equal(expectedDisposeOutputStream, invocationResponse.DisposeOutputStream); AssertEqual(expectedOutput, invocationResponse.OutputStream); } } private void AssertEqual(byte[] expected, Stream actual) { Assert.NotNull(actual); var actualBytes = new byte[actual.Length]; actual.Read(actualBytes, 0, actualBytes.Length); AssertEqual(expected, actualBytes); } private void AssertEqual(byte[] expected, byte[] actual) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.True(expected != null && actual != null); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } public class Checkpoint { public bool IsChecked { get; set; } public void Check() { IsChecked = true; } } } }
686
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.IO; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class ILSClass { } public interface ILSEmpty { } public interface ILSDeserializeNongeneric { void Deserialize(); } public interface ILSDeserializeNoInputs { void Deserialize<T>(); } public interface ILSDeserializeWrongInput { void Deserialize<T>(string input); } public interface ILSDeserializeWrongGenerics { void Deserialize<T, V>(Stream input); } public interface ILSDeserializeWrongOutput { object Deserialize<T>(Stream input); } public interface ILSSerializeMissing { T Deserialize<T>(Stream input); } public interface ILSSerializeNotGeneric { T Deserialize<T>(Stream input); void Serialize(); } public interface ILSSerializeNotVoid { T Deserialize<T>(Stream input); object Serialize<T>(); } public interface ILSSerializeNoInputs { T Deserialize<T>(Stream input); void Serialize<T>(); } public interface ILSSerializeWrongGenerics { T Deserialize<T>(Stream input); void Serialize<T, V>(T obj, Stream output); } public interface ILSSerializeWrongFirstInput { T Deserialize<T>(Stream input); void Serialize<T>(bool obj, Stream output); } public interface ILSSerializeWrongSecondInput { T Deserialize<T>(Stream input); void Serialize<T>(T obj, string output); } }
99
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.RuntimeSupport.Bootstrap; using static Amazon.Lambda.RuntimeSupport.Bootstrap.Constants; namespace Amazon.Lambda.RuntimeSupport.UnitTests { /// <summary> /// Tests to test LambdaBootstrap when it's constructed using its actual constructor. /// Tests of the static GetLambdaBootstrap methods can be found in LambdaBootstrapWrapperTests. /// </summary> public class LambdaBootstrapTests { TestHandler _testFunction; TestInitializer _testInitializer; TestRuntimeApiClient _testRuntimeApiClient; TestEnvironmentVariables _environmentVariables; HandlerWrapper _testWrapper; public LambdaBootstrapTests() { _environmentVariables = new TestEnvironmentVariables(); var headers = new Dictionary<string, IEnumerable<string>> { { RuntimeApiHeaders.HeaderAwsRequestId, new List<string> {"request_id"} }, { RuntimeApiHeaders.HeaderInvokedFunctionArn, new List<string> {"invoked_function_arn"} } }; _testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables, headers); _testInitializer = new TestInitializer(); _testFunction = new TestHandler(); _testWrapper = HandlerWrapper.GetHandlerWrapper(_testFunction.HandlerVoidVoidSync); } [Fact] public void ThrowsExceptionForNullHandler() { Assert.Throws<ArgumentNullException>("handler", () => { new LambdaBootstrap((LambdaBootstrapHandler)null); }); } [Fact] public void ThrowsExceptionForNullHttpClient() { Assert.Throws<ArgumentNullException>("httpClient", () => { new LambdaBootstrap((HttpClient)null, _testFunction.BaseHandlerAsync); }); Assert.Throws<ArgumentNullException>("httpClient", () => { new LambdaBootstrap((HttpClient)null, _testWrapper); }); } [Fact] public async Task NoInitializer() { _testFunction.CancellationSource.Cancel(); using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerAsync, null)) { bootstrap.Client = _testRuntimeApiClient; await bootstrap.RunAsync(_testFunction.CancellationSource.Token); } Assert.False(_testInitializer.InitializerWasCalled); Assert.False(_testFunction.HandlerWasCalled); } [Fact] public async Task InitializerThrowsException() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeThrowAsync)) { bootstrap.Client = _testRuntimeApiClient; var exception = await Assert.ThrowsAsync<Exception>(async () => { await bootstrap.RunAsync(); }); Assert.Equal(TestInitializer.InitializeExceptionMessage, exception.Message); } Assert.True(_testRuntimeApiClient.ReportInitializationErrorAsyncExceptionCalled); Assert.True(_testInitializer.InitializerWasCalled); Assert.False(_testFunction.HandlerWasCalled); } [Fact] public async Task InitializerReturnsFalse() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeFalseAsync)) { await bootstrap.RunAsync(); } Assert.True(_testInitializer.InitializerWasCalled); Assert.False(_testFunction.HandlerWasCalled); } [Fact] public async Task InitializerReturnsTrueAndHandlerLoopRuns() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeTrueAsync)) { bootstrap.Client = _testRuntimeApiClient; await bootstrap.RunAsync(_testFunction.CancellationSource.Token); } Assert.True(_testInitializer.InitializerWasCalled); Assert.True(_testFunction.HandlerWasCalled); } [Fact] public async Task TraceIdEnvironmentVariableIsSet() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerAsync, null)) { bootstrap.Client = _testRuntimeApiClient; Assert.Null(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarTraceId)); await bootstrap.InvokeOnceAsync(); Assert.NotNull(_testRuntimeApiClient.LastTraceId); Assert.Equal(_testRuntimeApiClient.LastTraceId, _environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarTraceId)); } Assert.False(_testInitializer.InitializerWasCalled); Assert.True(_testFunction.HandlerWasCalled); } [Fact] public async Task HandlerThrowsException() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerThrowsAsync, null)) { bootstrap.Client = _testRuntimeApiClient; Assert.Null(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarTraceId)); await bootstrap.InvokeOnceAsync(); } Assert.True(_testRuntimeApiClient.ReportInvocationErrorAsyncExceptionCalled); Assert.False(_testInitializer.InitializerWasCalled); Assert.True(_testFunction.HandlerWasCalled); } [Fact] public async Task HandlerInputAndOutputWork() { const string testInput = "a MiXeD cAsE sTrInG"; using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerToUpperAsync, null)) { _testRuntimeApiClient.FunctionInput = Encoding.UTF8.GetBytes(testInput); bootstrap.Client = _testRuntimeApiClient; Assert.Null(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarTraceId)); await bootstrap.InvokeOnceAsync(); } _testRuntimeApiClient.VerifyOutput(testInput.ToUpper()); Assert.False(_testInitializer.InitializerWasCalled); Assert.True(_testFunction.HandlerWasCalled); } [Fact] public async Task HandlerReturnsNull() { using (var bootstrap = new LambdaBootstrap(_testFunction.BaseHandlerReturnsNullAsync, null)) { _testRuntimeApiClient.FunctionInput = new byte[0]; bootstrap.Client = _testRuntimeApiClient; Assert.Null(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarTraceId)); await bootstrap.InvokeOnceAsync(); } _testRuntimeApiClient.VerifyOutput((byte[])null); Assert.False(_testInitializer.InitializerWasCalled); Assert.True(_testFunction.HandlerWasCalled); } [Fact] public void VerifyUserAgentStringSet() { var client = LambdaBootstrap.ConstructHttpClient(); var values = client.DefaultRequestHeaders.GetValues("User-Agent"); Assert.Single(values); var userAgent = values.First(); Assert.StartsWith("aws-lambda-dotnet", userAgent); var topLevelTokens = userAgent.Split('/'); Assert.Equal(2, topLevelTokens.Length); var versions = topLevelTokens[1].Split('-'); Assert.Equal(2, versions.Length); var dotnetVersion = Version.Parse(versions[0]); Assert.True(Version.Parse("2.0.0") < dotnetVersion); var runtimeLambdaSupportVersion = Version.Parse(versions[1]); Assert.True(Version.Parse("1.0.0") <= runtimeLambdaSupportVersion); } [Fact] public void IsCallPreJitTest() { Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "ProvisionedConcurrency"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, AWS_LAMBDA_INITIALIZATION_TYPE_PC); Assert.True(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "ProvisionedConcurrency"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, AWS_LAMBDA_INITIALIZATION_TYPE_ON_DEMAND); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "ProvisionedConcurrency"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, null); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "Always"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, null); Assert.True(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "Never"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, null); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, null); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, null); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, null); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, AWS_LAMBDA_INITIALIZATION_TYPE_ON_DEMAND); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, "Never"); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, null); Assert.False(UserCodeInit.IsCallPreJit()); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_DOTNET_PREJIT, null); Environment.SetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_LAMBDA_INITIALIZATION_TYPE, AWS_LAMBDA_INITIALIZATION_TYPE_PC); Assert.True(UserCodeInit.IsCallPreJit()); } } }
263
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class LambdaContextTests { private readonly TestEnvironmentVariables _environmentVariables; public LambdaContextTests() { _environmentVariables = new TestEnvironmentVariables(); } [Fact] public void RemainingTimeIsPositive() { var deadline = DateTimeOffset.UtcNow.AddHours(1); var deadlineMs = deadline.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); var headers = new Dictionary<string, IEnumerable<string>> { ["Lambda-Runtime-Aws-Request-Id"] = new[] { Guid.NewGuid().ToString() }, ["Lambda-Runtime-Deadline-Ms"] = new[] { deadlineMs }, ["Lambda-Runtime-Invoked-Function-Arn"] = new[] { "my-function-arn" } }; var runtimeApiHeaders = new RuntimeApiHeaders(headers); var lambdaEnvironment = new LambdaEnvironment(_environmentVariables); var context = new LambdaContext(runtimeApiHeaders, lambdaEnvironment, new Helpers.SimpleLoggerWriter()); Assert.True(context.RemainingTime >= TimeSpan.Zero, $"Remaining time is not a positive value: {context.RemainingTime}"); } } }
40
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Text.RegularExpressions; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class LambdaEnvironmentTests { private const string LambdaExecutionEnvironment = "AWS_Lambda_dotnet_custom"; TestEnvironmentVariables _environmentVariables; public LambdaEnvironmentTests() { _environmentVariables = new TestEnvironmentVariables(); } [Fact] public void SetsExecutionEnvironmentButNotTwice() { var expectedValueRegex = new Regex($"{LambdaExecutionEnvironment}_amazonlambdaruntimesupport_[0-9]+\\.[0-9]+\\.[0-9]+"); _environmentVariables.SetEnvironmentVariable(LambdaEnvironment.EnvVarExecutionEnvironment, LambdaExecutionEnvironment); var lambdaEnvironment = new LambdaEnvironment(_environmentVariables); Assert.True(expectedValueRegex.IsMatch(lambdaEnvironment.ExecutionEnvironment)); Assert.True(expectedValueRegex.IsMatch(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarExecutionEnvironment))); // Make sure that creating another LambdaEnvironment instance won't change the value. lambdaEnvironment = new LambdaEnvironment(_environmentVariables); Assert.True(expectedValueRegex.IsMatch(lambdaEnvironment.ExecutionEnvironment)); Assert.True(expectedValueRegex.IsMatch(_environmentVariables.GetEnvironmentVariable(LambdaEnvironment.EnvVarExecutionEnvironment))); } } }
49
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class LambdaExceptionHandlingTests { [Fact] public void WriteJsonForUserCodeException() { Exception exception = null; try { ThrowTest(); } catch (Exception ex) { exception = ex; } var exceptionInfo = ExceptionInfo.GetExceptionInfo(exception); var json = LambdaXRayExceptionWriter.WriteJson(exceptionInfo); Assert.NotNull(json); Assert.DoesNotMatch("\r\n", json); Assert.DoesNotMatch("\n", json); var jsonDocument = JsonDocument.Parse(json); JsonElement jsonElement; Assert.True(jsonDocument.RootElement.TryGetProperty("working_directory", out jsonElement)); Assert.Equal(JsonValueKind.String, jsonElement.ValueKind); Assert.True(jsonElement.GetString().Length > 0); Assert.True(jsonDocument.RootElement.TryGetProperty("exceptions", out jsonElement)); Assert.Equal(JsonValueKind.Array, jsonElement.ValueKind); jsonElement = jsonElement.EnumerateArray().First(); Assert.Equal("ApplicationException", jsonElement.GetProperty("type").GetString()); Assert.Equal("This is a fake Exception", jsonElement.GetProperty("message").GetString()); jsonElement = jsonElement.GetProperty("stack").EnumerateArray().First(); Assert.True(jsonElement.GetProperty("path").GetString().Length > 0); Assert.Equal("LambdaExceptionHandlingTests.ThrowTest", jsonElement.GetProperty("label").GetString()); Assert.True(jsonElement.GetProperty("line").GetInt32() > 0); Assert.True(jsonDocument.RootElement.TryGetProperty("paths", out jsonElement)); Assert.Equal(JsonValueKind.Array, jsonElement.ValueKind); var paths = jsonElement.EnumerateArray().ToArray(); Assert.Single(paths); Assert.Contains("LambdaExceptionHandlingTests.cs", paths[0].GetString()); } private void ThrowTest() { throw new ApplicationException("This is a fake Exception"); } } }
64
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class NonDisposingStreamWrapperTests { private const string TestString = "testing123"; [Fact] public async Task MakeSureDisposeWorks() { var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(TestString)); using (var streamWrapper = new NonDisposingStreamWrapper(memoryStream)) { var buffer = new byte[memoryStream.Length]; await streamWrapper.ReadAsync(buffer); Assert.Equal(TestString, Encoding.UTF8.GetString(buffer)); } // show that it's not disposed memoryStream.Position = 0; memoryStream.Dispose(); // show that it's disposed now var caughtException = false; try { memoryStream.Position = 0; } catch (ObjectDisposedException) { caughtException = true; } Assert.True(caughtException); } } }
56
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class PocoInput { public String InputString { get; set; } public int InputInt { get; set; } public override bool Equals(object value) { PocoInput pocoInput = value as PocoInput; return !Object.ReferenceEquals(null, pocoInput) && String.Equals(InputString, pocoInput.InputString) && int.Equals(InputInt, pocoInput.InputInt); } public override int GetHashCode() { unchecked { int hashBase = (int)2166136261; int hashMultiplier = 16777619; int hash = hashBase; hash = (hash * hashMultiplier) ^ (!Object.ReferenceEquals(null, InputString) ? InputString.GetHashCode() : 0); hash = (hash * hashMultiplier) ^ (!Object.ReferenceEquals(null, InputInt) ? InputInt.GetHashCode() : 0); return hash; } } } }
50
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class PocoOutput { public String OutputString { get; set; } public int OutputInt { get; set; } public override bool Equals(object value) { PocoOutput pocoOutput = value as PocoOutput; return !Object.ReferenceEquals(null, pocoOutput) && String.Equals(OutputString, pocoOutput.OutputString) && int.Equals(OutputInt, pocoOutput.OutputInt); } public override int GetHashCode() { unchecked { int hashBase = (int)2166136261; int hashMultiplier = 16777619; int hash = hashBase; hash = (hash * hashMultiplier) ^ (!Object.ReferenceEquals(null, OutputString) ? OutputString.GetHashCode() : 0); hash = (hash * hashMultiplier) ^ (!Object.ReferenceEquals(null, OutputInt) ? OutputInt.GetHashCode() : 0); return hash; } } } }
50
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit.Abstractions; namespace Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers { public static class StringWriterExtensions { public static void Clear(this StringWriter writer) { var sb = writer.GetStringBuilder(); sb.Remove(0, sb.Length); } private const double TicksPerMicrosecond = (TimeSpan.TicksPerMillisecond / 1000); public static string ToPrettyTime(this TimeSpan ts) { var times = new List<string>(); if (ts.Days > 0) times.Add($"{ts.Days} days"); if (ts.Hours > 0) times.Add($"{ts.Hours} hours"); if (ts.Minutes > 0) times.Add($"{ts.Minutes} minutes"); if (ts.Seconds > 0) times.Add($"{ts.Seconds} seconds"); if (ts.Milliseconds > 0) times.Add($"{ts.Milliseconds} ms"); var totalMicroseconds = ts.Ticks / TicksPerMicrosecond; var microseconds = totalMicroseconds % 1000; microseconds = Math.Round(microseconds, 3); if (microseconds > 0) times.Add($"{microseconds} microsecond"); if (times.Count == 0) return "No time!"; var text = string.Join(", ", times.Where(t => !string.IsNullOrEmpty(t))); return $"{text} ({ts.TotalMilliseconds}ms)"; } public static Lazy<T> ToLazy<T>(this T self) { return new Lazy<T>(() => self); } public static Action<string> ToLoggingAction(this TextWriter writer) { return writer.WriteLine; } public static Action<string> ToLoggingAction(this ITestOutputHelper writer) { return writer.WriteLine; } } }
75
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Lambda.RuntimeSupport.Helpers; namespace Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers { internal class TestDateTimeHelper : IDateTimeHelper { public DateTime UtcNow => new DateTime(2020, 1, 1); } }
26
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; namespace Amazon.Lambda.RuntimeSupport.UnitTests { class TestEnvironmentVariables : IEnvironmentVariables { Dictionary<string, string> environmentVariables = new Dictionary<string, string>(); public TestEnvironmentVariables(IDictionary<string, string> initialValues = null) { environmentVariables = initialValues == null ? new Dictionary<string, string>() : new Dictionary<string, string>(initialValues); } public string GetEnvironmentVariable(string variable) { environmentVariables.TryGetValue(variable, out var value); return value; } public IDictionary GetEnvironmentVariables() { return new Dictionary<string, string>(environmentVariables); } public void SetEnvironmentVariable(string variable, string value) { environmentVariables[variable] = value; } } }
49
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers { public class TestFileStream : FileStream { private Action<byte[], int, int> WriteAction { get; } public TestFileStream(Action<byte[], int, int> writeAction) : base(Path.GetTempFileName(), FileMode.Append, FileAccess.Write) { WriteAction = writeAction; } public override bool CanWrite => true; public override void Write(byte[] buffer, int offset, int count) { WriteAction(TrimTrailingNullBytes(buffer).Take(count).ToArray(), offset, count); } private static IEnumerable<byte> TrimTrailingNullBytes(IEnumerable<byte> buffer) { // Trim trailing null bytes to make testing assertions easier return buffer.Reverse().SkipWhile(x => x == 0).Reverse(); } } }
32
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Serialization.Json; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class TestHandler { public const string InvokeExceptionMessage = "Invoke Exception"; protected JsonSerializer _jsonSerializer = new JsonSerializer(); public bool HandlerWasCalled { get; protected set; } public byte[] LastInputReceived { get; private set; } public byte[] LastOutputSent { get; private set; } public CancellationTokenSource CancellationSource { get; } = new CancellationTokenSource(); public TestHandler() { // In case something goes wrong make sure tests won't hang forever in the invoke loop. CancellationSource.CancelAfter(30000); } public async Task<InvocationResponse> BaseHandlerAsync(InvocationRequest invocation) { var outputStream = new MemoryStream(); await DoHandlerCommonTasksAsync(invocation.InputStream, outputStream); return new InvocationResponse(outputStream); } public async Task<InvocationResponse> BaseHandlerThrowsAsync(InvocationRequest invocation) { var outputStream = new MemoryStream(); await DoHandlerCommonTasksAsync(invocation.InputStream, null); throw new Exception(InvokeExceptionMessage); } public async Task<InvocationResponse> BaseHandlerToUpperAsync(InvocationRequest invocation) { using (var sr = new StreamReader(invocation.InputStream)) { Stream outputStream = new MemoryStream(Encoding.UTF8.GetBytes(sr.ReadToEnd().ToUpper())); outputStream.Position = 0; await DoHandlerCommonTasksAsync(invocation.InputStream, outputStream); return new InvocationResponse(outputStream); } } public async Task<InvocationResponse> BaseHandlerReturnsNullAsync(InvocationRequest invocation) { using (var sr = new StreamReader(invocation.InputStream)) { await DoHandlerCommonTasksAsync(invocation.InputStream, null); return null; } } public void HandlerVoidVoidSync() { DoHandlerTasks(null, null); } private async Task DoHandlerCommonTasksAsync(Stream input, Stream output) { await Task.Delay(0); DoHandlerTasks(input, output); } private void DoHandlerTasks(Stream input, Stream output) { CancellationSource.Cancel(); HandlerWasCalled = true; if (input == null) { LastInputReceived = null; } else { input.Position = 0; LastInputReceived = new byte[input.Length]; input.Read(LastInputReceived); } if (output == null) { LastOutputSent = null; } else { LastOutputSent = new byte[output.Length]; output.Read(LastOutputSent); output.Position = 0; } } } }
116
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Serialization.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Amazon.Lambda.RuntimeSupport.UnitTests { public class TestInitializer { public const string InitializeExceptionMessage = "Initialize Exception"; protected JsonSerializer _jsonSerializer = new JsonSerializer(); public bool InitializerWasCalled { get; protected set; } public bool InitializeTrue() { return Initialize(true); } public bool InitializeFalse() { return Initialize(false); } public bool InitializeThrow() { return Initialize(null); } public Task<bool> InitializeTrueAsync() { return Task.FromResult(Initialize(true)); } public Task<bool> InitializeFalseAsync() { return Task.FromResult(Initialize(false)); } public Task<bool> InitializeThrowAsync() { return Task.FromResult(Initialize(null)); } private bool Initialize(bool? result) { InitializerWasCalled = true; if (result.HasValue) { return result.Value; } else { throw new Exception(InitializeExceptionMessage); } } } }
71
aws-lambda-dotnet
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.RuntimeSupport.UnitTests.TestHelpers; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.Lambda.RuntimeSupport.UnitTests { internal class TestRuntimeApiClient : IRuntimeApiClient { private IEnvironmentVariables _environmentVariables; private Dictionary<string, IEnumerable<string>> _headers; public TestRuntimeApiClient(IEnvironmentVariables environmentVariables, Dictionary<string, IEnumerable<string>> headers) { _environmentVariables = environmentVariables; _headers = headers; } public bool GetNextInvocationAsyncCalled { get; private set; } public bool ReportInitializationErrorAsyncExceptionCalled { get; private set; } public bool ReportInitializationErrorAsyncTypeCalled { get; private set; } public bool ReportInvocationErrorAsyncExceptionCalled { get; private set; } public bool ReportInvocationErrorAsyncTypeCalled { get; private set; } public bool SendResponseAsyncCalled { get; private set; } public string LastTraceId { get; private set; } public byte[] FunctionInput { get; set; } public Stream LastOutputStream { get; private set; } public Exception LastRecordedException { get; private set; } public void VerifyOutput(string expectedOutput) { VerifyOutput(Encoding.UTF8.GetBytes(expectedOutput)); } public void VerifyOutput(byte[] expectedOutput) { if (expectedOutput == null && LastOutputStream == null) { return; } else if (expectedOutput != null && LastOutputStream != null) { int nextByte = 0; int count = 0; while ((nextByte = LastOutputStream.ReadByte()) != -1) { Assert.Equal(expectedOutput[count++], nextByte); } if (count == 0) { Assert.Null(expectedOutput); } } else { throw new Exception("expectedOutput and LastOutputStream must both be null or both be non-null."); } } public Task<InvocationRequest> GetNextInvocationAsync(CancellationToken cancellationToken = default) { GetNextInvocationAsyncCalled = true; LastTraceId = Guid.NewGuid().ToString(); _headers[RuntimeApiHeaders.HeaderTraceId] = new List<string>() { LastTraceId }; var inputStream = new MemoryStream(FunctionInput == null ? new byte[0] : FunctionInput); inputStream.Position = 0; return Task.FromResult(new InvocationRequest() { InputStream = inputStream, LambdaContext = new LambdaContext( new RuntimeApiHeaders(_headers), new LambdaEnvironment(_environmentVariables), new TestDateTimeHelper(), new Helpers.SimpleLoggerWriter()) }); } public Task ReportInitializationErrorAsync(Exception exception, CancellationToken cancellationToken = default) { LastRecordedException = exception; ReportInitializationErrorAsyncExceptionCalled = true; return Task.Run(() => { }); } public Task ReportInitializationErrorAsync(string errorType, CancellationToken cancellationToken = default) { ReportInitializationErrorAsyncTypeCalled = true; return Task.Run(() => { }); } public Task ReportInvocationErrorAsync(string awsRequestId, Exception exception, CancellationToken cancellationToken = default) { LastRecordedException = exception; ReportInvocationErrorAsyncExceptionCalled = true; return Task.Run(() => { }); } public Task ReportInvocationErrorAsync(string awsRequestId, string errorType, CancellationToken cancellationToken = default) { ReportInvocationErrorAsyncTypeCalled = true; return Task.Run(() => { }); } public Task SendResponseAsync(string awsRequestId, Stream outputStream, CancellationToken cancellationToken = default) { if (outputStream != null) { // copy the stream because it gets disposed by the bootstrap LastOutputStream = new MemoryStream((int)outputStream.Length); outputStream.CopyTo(LastOutputStream); LastOutputStream.Position = 0; } SendResponseAsyncCalled = true; return Task.Run(() => { }); } } }
140
aws-lambda-dotnet
aws
C#
using System.Text.Json.Serialization; using Amazon.Lambda.APIGatewayEvents; namespace CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest; [JsonSerializable(typeof(WeatherForecast))] [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))] [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyResponse))] public partial class CustomJsonSerializerContext : JsonSerializerContext { }
11
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Serialization.SystemTextJson; using CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi, options => { options.Serializer = new SourceGeneratorLambdaJsonSerializer<CustomJsonSerializerContext>(); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
34
aws-lambda-dotnet
aws
C#
namespace CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; } } }
13
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Microsoft.AspNetCore.Mvc; namespace CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest.Controllers { [ApiController] [Route("[controller]")] public class LoggerTestController : ControllerBase { [HttpGet()] public long Get() { var lambdaContext = this.HttpContext.Items["LambdaContext"] as ILambdaContext; const int maxLogs = 10000; long actualLogsWritten = 0; Action stdOutTest = () => { long index = 0; while (index < maxLogs) { Console.WriteLine($"StdOut: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; Action stdErrTest = () => { long index = 0; while (index < maxLogs) { Console.Error.WriteLine($"StdErr: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; Action contextLoggerTest = () => { long index = 0; while (index < maxLogs) { lambdaContext!.Logger.LogWarning($"ContextLogger: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; var tasks = new List<Task>(); for (int i = 0; i < 3; i++) { tasks.Add(Task.Run(stdOutTest)); tasks.Add(Task.Run(stdErrTest)); tasks.Add(Task.Run(contextLoggerTest)); } Task.WaitAll(tasks.ToArray()); return actualLogsWritten; } } }
65
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace CustomRuntimeAspNetCoreMinimalApiCustomSerializerTest.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
33
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Serialization.SystemTextJson; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
30
aws-lambda-dotnet
aws
C#
namespace CustomRuntimeAspNetCoreMinimalApiTest { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; } } }
13
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; using Amazon.Lambda.Core; namespace CustomRuntimeAspNetCoreMinimalApiTest.Controllers { [ApiController] [Route("[controller]")] public class LoggerTestController : ControllerBase { [HttpGet()] public long Get() { var lambdaContext = this.HttpContext.Items["LambdaContext"] as ILambdaContext; const int maxLogs = 10000; long actualLogsWritten = 0; Action stdOutTest = () => { long index = 0; while (index < maxLogs) { Console.WriteLine($"StdOut: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; Action stdErrTest = () => { long index = 0; while (index < maxLogs) { Console.Error.WriteLine($"StdErr: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; Action contextLoggerTest = () => { long index = 0; while (index < maxLogs) { lambdaContext!.Logger.LogWarning($"ContextLogger: {index++}"); Interlocked.Increment(ref actualLogsWritten); Thread.Yield(); } }; var tasks = new List<Task>(); for (int i = 0; i < 3; i++) { tasks.Add(Task.Run(stdOutTest)); tasks.Add(Task.Run(stdErrTest)); tasks.Add(Task.Run(contextLoggerTest)); } Task.WaitAll(tasks.ToArray()); return actualLogsWritten; } } }
65
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace CustomRuntimeAspNetCoreMinimalApiTest.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
33
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using System; using System.IO; using System.Net.Http; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CustomRuntimeFunctionTest { class CustomRuntimeFunction { private const string FailureResult = "FAILURE"; private const string SuccessResult = "SUCCESS"; private const string TestUrl = "https://www.amazon.com"; private static readonly Lazy<string> SixMBString = new Lazy<string>(() => { return new string('X', 1024 * 1024 * 6); }); private static readonly Lazy<string> SevenMBString = new Lazy<string>(() => { return new string('X', 1024 * 1024 * 7); }); private static MemoryStream ResponseStream = new MemoryStream(); private static DefaultLambdaJsonSerializer JsonSerializer = new DefaultLambdaJsonSerializer(); private static LambdaEnvironment LambdaEnvironment = new LambdaEnvironment(); private static async Task Main(string[] args) { var handler = Environment.GetEnvironmentVariable("TEST_HANDLER"); LambdaBootstrap bootstrap = null; HandlerWrapper handlerWrapper = null; try { switch (handler) { case nameof(ExceptionNonAsciiCharacterUnwrappedAsync): bootstrap = new LambdaBootstrap(ExceptionNonAsciiCharacterUnwrappedAsync); break; case nameof(UnintendedDisposeTest): bootstrap = new LambdaBootstrap(UnintendedDisposeTest); break; case nameof(LoggingStressTest): bootstrap = new LambdaBootstrap(LoggingStressTest); break; case nameof(LoggingTest): bootstrap = new LambdaBootstrap(LoggingTest); break; case nameof(ToUpperAsync): bootstrap = new LambdaBootstrap(ToUpperAsync); break; case nameof(PingAsync): bootstrap = new LambdaBootstrap(PingAsync); break; case nameof(HttpsWorksAsync): bootstrap = new LambdaBootstrap(HttpsWorksAsync); break; case nameof(CertificateCallbackWorksAsync): bootstrap = new LambdaBootstrap(CertificateCallbackWorksAsync); break; case nameof(NetworkingProtocolsAsync): bootstrap = new LambdaBootstrap(NetworkingProtocolsAsync); break; case nameof(HandlerEnvVarAsync): bootstrap = new LambdaBootstrap(HandlerEnvVarAsync); break; case nameof(AggregateExceptionUnwrappedAsync): bootstrap = new LambdaBootstrap(AggregateExceptionUnwrappedAsync); break; case nameof(AggregateExceptionUnwrapped): handlerWrapper = HandlerWrapper.GetHandlerWrapper((Action)AggregateExceptionUnwrapped); bootstrap = new LambdaBootstrap(handlerWrapper); break; case nameof(AggregateExceptionNotUnwrappedAsync): bootstrap = new LambdaBootstrap(AggregateExceptionNotUnwrappedAsync); break; case nameof(AggregateExceptionNotUnwrapped): handlerWrapper = HandlerWrapper.GetHandlerWrapper((Action)AggregateExceptionNotUnwrapped); bootstrap = new LambdaBootstrap(handlerWrapper); break; case nameof(TooLargeResponseBodyAsync): bootstrap = new LambdaBootstrap(TooLargeResponseBodyAsync); break; case nameof(LambdaEnvironmentAsync): bootstrap = new LambdaBootstrap(LambdaEnvironmentAsync); break; case nameof(LambdaContextBasicAsync): bootstrap = new LambdaBootstrap(LambdaContextBasicAsync); break; case nameof(GetPidDllImportAsync): bootstrap = new LambdaBootstrap(GetPidDllImportAsync); break; case nameof(GetTimezoneNameAsync): bootstrap = new LambdaBootstrap(GetTimezoneNameAsync); break; default: throw new Exception($"Handler {handler} is not supported."); } await bootstrap.RunAsync(); } finally { handlerWrapper?.Dispose(); bootstrap?.Dispose(); } } private static Task<InvocationResponse> LoggingStressTest(InvocationRequest invocation) { var source = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var token = source.Token; Task UseWriteAsync() { return Task.Run(() => { int i = 0; while (!token.IsCancellationRequested) { Thread.Sleep(0); Console.Write($"|Write+{i++}|"); } }); } Task UseWriteLineAsync() { return Task.Run(() => { int i = 0; while (!token.IsCancellationRequested) { Thread.Sleep(0); Console.WriteLine($"|WriteLine+{i++}|"); } }); } Task UseLoggerAsync() { return Task.Run(() => { int i = 0; while (!token.IsCancellationRequested) { Thread.Sleep(0); invocation.LambdaContext.Logger.LogInformation($"|FormattedWriteLine+{i++}|"); } }); } var task1 = UseWriteAsync(); var task2 = UseWriteLineAsync(); var task3 = UseLoggerAsync(); Task.WaitAll(task1, task2, task3); return Task.FromResult(GetInvocationResponse(nameof(LoggingStressTest), "success")); } private static Task<InvocationResponse> LoggingTest(InvocationRequest invocation) { invocation.LambdaContext.Logger.LogTrace("A trace log"); invocation.LambdaContext.Logger.LogDebug("A debug log"); invocation.LambdaContext.Logger.LogInformation("A information log"); invocation.LambdaContext.Logger.LogWarning("A warning log"); invocation.LambdaContext.Logger.LogError("A error log"); invocation.LambdaContext.Logger.LogCritical("A critical log"); Console.WriteLine("A stdout info message"); Console.Error.WriteLine("A stderror error message"); Amazon.Lambda.Core.LambdaLogger.Log("A fake message level"); return Task.FromResult(GetInvocationResponse(nameof(LoggingTest), true)); } private static Task<InvocationResponse> UnintendedDisposeTest(InvocationRequest invocation) { int errorCode = new NUnitLite.AutoRun().Execute(new string[] { "--noresult" }); Console.WriteLine("This is standard output stream."); return Task.FromResult(GetInvocationResponse(nameof(UnintendedDisposeTest), true)); } public class WrapTextWriter : TextWriter { TextWriter _textWriter; public WrapTextWriter(TextWriter textWriter) { _textWriter = textWriter; } public override Encoding Encoding => UTF8Encoding.UTF8; protected override void Dispose(bool disposing) { if(disposing) { _textWriter.Dispose(); } } public override async ValueTask DisposeAsync() { await _textWriter.DisposeAsync(); } public override void Close() { _textWriter.Close(); } } private static Task<InvocationResponse> ToUpperAsync(InvocationRequest invocation) { var input = JsonSerializer.Deserialize<string>(invocation.InputStream); return Task.FromResult(GetInvocationResponse(nameof(ToUpperAsync), input.ToUpper())); } private static Task<InvocationResponse> PingAsync(InvocationRequest invocation) { var input = JsonSerializer.Deserialize<string>(invocation.InputStream); if (input == "ping") { return Task.FromResult(GetInvocationResponse(nameof(PingAsync), "pong")); } else { throw new Exception("Expected input: ping"); } } private static async Task<InvocationResponse> HttpsWorksAsync(InvocationRequest invocation) { var isSuccess = false; using (var httpClient = new HttpClient()) { var response = await httpClient.GetAsync(TestUrl); if (response.IsSuccessStatusCode) { isSuccess = true; } Console.WriteLine($"Response from HTTP get: {response}"); } return GetInvocationResponse(nameof(HttpsWorksAsync), isSuccess); } private static async Task<InvocationResponse> CertificateCallbackWorksAsync(InvocationRequest invocation) { var isSuccess = false; using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }; using (var client = new HttpClient(httpClientHandler)) { var response = await client.GetAsync(TestUrl); if (response.IsSuccessStatusCode) { isSuccess = true; } Console.WriteLine($"Response from HTTP get: {response}"); } } return GetInvocationResponse(nameof(CertificateCallbackWorksAsync), isSuccess); } private static Task<InvocationResponse> NetworkingProtocolsAsync(InvocationRequest invocation) { var type = typeof(Socket).GetTypeInfo().Assembly.GetType("System.Net.SocketProtocolSupportPal"); var method = type.GetMethod("IsSupported", BindingFlags.NonPublic | BindingFlags.Static); var ipv4Supported = method.Invoke(null, new object[] { AddressFamily.InterNetwork }); var ipv6Supported = method.Invoke(null, new object[] { AddressFamily.InterNetworkV6 }); Exception ipv4SocketCreateException = null; try { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { } } catch (Exception e) { ipv4SocketCreateException = e; } Exception ipv6SocketCreateException = null; try { using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { } } catch (Exception e) { ipv6SocketCreateException = e; } string returnValue = ""; if (!(bool)ipv4Supported) { returnValue += "For System.Net.SocketProtocolSupportPal.IsProtocolSupported(AddressFamily.InterNetwork) Expected true, Actual false" + Environment.NewLine; } if ((bool)ipv6Supported) { returnValue += "For System.Net.SocketProtocolSupportPal.IsProtocolSupported(AddressFamily.InterNetworkV6) Expected false, Actual true" + Environment.NewLine; } if (ipv4SocketCreateException != null) { returnValue += "Error creating IPV4 Socket: " + ipv4SocketCreateException + Environment.NewLine; } if (ipv6SocketCreateException == null) { returnValue += "When creating IPV6 Socket expected exception, got none." + Environment.NewLine; } if (ipv6SocketCreateException != null && ipv6SocketCreateException.Message != "Address family not supported by protocol") { returnValue += "When creating IPV6 Socket expected exception 'Address family not supported by protocol', actual '" + ipv6SocketCreateException.Message + "'" + Environment.NewLine; } if (String.IsNullOrEmpty(returnValue)) { returnValue = "SUCCESS"; } return Task.FromResult(GetInvocationResponse(nameof(NetworkingProtocolsAsync), returnValue)); } private static Task<InvocationResponse> HandlerEnvVarAsync(InvocationRequest invocation) { return Task.FromResult(GetInvocationResponse(nameof(HandlerEnvVarAsync), LambdaEnvironment.Handler)); } private static async Task<InvocationResponse> AggregateExceptionUnwrappedAsync(InvocationRequest invocation) { // do something async so this function is compiled as async var dummy = await Task.FromResult("xyz"); throw new Exception("Exception thrown from an async handler."); } private static async Task<InvocationResponse> ExceptionNonAsciiCharacterUnwrappedAsync(InvocationRequest invocation) { // do something async so this function is compiled as async var dummy = await Task.FromResult("xyz"); throw new Exception("Unhandled exception with non ASCII character: ♂"); } private static void AggregateExceptionUnwrapped() { throw new Exception("Exception thrown from a synchronous handler."); } private static async Task<InvocationResponse> AggregateExceptionNotUnwrappedAsync(InvocationRequest invocation) { // do something async so this function is compiled as async var dummy = await Task.FromResult("xyz"); throw new AggregateException("AggregateException thrown from an async handler."); } private static void AggregateExceptionNotUnwrapped() { throw new AggregateException("AggregateException thrown from a synchronous handler."); } private static Task<InvocationResponse> TooLargeResponseBodyAsync(InvocationRequest invocation) { return Task.FromResult(GetInvocationResponse(nameof(TooLargeResponseBodyAsync), SevenMBString.Value)); } private static Task<InvocationResponse> LambdaEnvironmentAsync(InvocationRequest invocation) { AssertNotNull(LambdaEnvironment.FunctionMemorySize, nameof(LambdaEnvironment.FunctionMemorySize)); AssertNotNull(LambdaEnvironment.FunctionName, nameof(LambdaEnvironment.FunctionName)); AssertNotNull(LambdaEnvironment.FunctionVersion, nameof(LambdaEnvironment.FunctionVersion)); AssertNotNull(LambdaEnvironment.Handler, nameof(LambdaEnvironment.Handler)); AssertNotNull(LambdaEnvironment.LogGroupName, nameof(LambdaEnvironment.LogGroupName)); AssertNotNull(LambdaEnvironment.LogStreamName, nameof(LambdaEnvironment.LogStreamName)); AssertNotNull(LambdaEnvironment.RuntimeServerHostAndPort, nameof(LambdaEnvironment.RuntimeServerHostAndPort)); AssertNotNull(LambdaEnvironment.XAmznTraceId, nameof(LambdaEnvironment.XAmznTraceId)); return Task.FromResult(GetInvocationResponse(nameof(LambdaEnvironmentAsync), true)); } private static Task<InvocationResponse> LambdaContextBasicAsync(InvocationRequest invocation) { AssertNotNull(invocation.LambdaContext.AwsRequestId, nameof(invocation.LambdaContext.AwsRequestId)); AssertNotNull(invocation.LambdaContext.ClientContext, nameof(invocation.LambdaContext.ClientContext)); AssertNotNull(invocation.LambdaContext.FunctionName, nameof(invocation.LambdaContext.FunctionName)); AssertNotNull(invocation.LambdaContext.FunctionVersion, nameof(invocation.LambdaContext.FunctionVersion)); AssertNotNull(invocation.LambdaContext.Identity, nameof(invocation.LambdaContext.Identity)); AssertNotNull(invocation.LambdaContext.InvokedFunctionArn, nameof(invocation.LambdaContext.InvokedFunctionArn)); AssertNotNull(invocation.LambdaContext.Logger, nameof(invocation.LambdaContext.Logger)); AssertNotNull(invocation.LambdaContext.LogGroupName, nameof(invocation.LambdaContext.LogGroupName)); AssertNotNull(invocation.LambdaContext.LogStreamName, nameof(invocation.LambdaContext.LogStreamName)); AssertTrue(invocation.LambdaContext.MemoryLimitInMB >= 128, $"{nameof(invocation.LambdaContext.MemoryLimitInMB)}={invocation.LambdaContext.MemoryLimitInMB} is not >= 128"); AssertTrue(invocation.LambdaContext.RemainingTime > TimeSpan.Zero, $"{nameof(invocation.LambdaContext.RemainingTime)}={invocation.LambdaContext.RemainingTime} is not >= 0"); return Task.FromResult(GetInvocationResponse(nameof(LambdaContextBasicAsync), true)); } #region GetPidDllImportAsync [DllImport("libc", EntryPoint = "getpid", CallingConvention = CallingConvention.Cdecl)] private static extern int getpid(); private static Task<InvocationResponse> GetPidDllImportAsync(InvocationRequest invocation) { var isSuccess = getpid() > 0; return Task.FromResult(GetInvocationResponse(nameof(GetPidDllImportAsync), isSuccess)); } #endregion private static Task<InvocationResponse> GetTimezoneNameAsync(InvocationRequest invocation) { return Task.FromResult(GetInvocationResponse(nameof(GetTimezoneNameAsync), TimeZoneInfo.Local.Id)); } #region Helpers private static void AssertNotNull(object value, string valueName) { if (value == null) { throw new Exception($"{valueName} cannot be null."); } } private static void AssertTrue(bool value, string errorMessage) { if (!value) { throw new Exception(errorMessage); } } private static InvocationResponse GetInvocationResponse(string testName, bool isSuccess) { return GetInvocationResponse($"{testName}-{(isSuccess ? SuccessResult : FailureResult)}"); } private static InvocationResponse GetInvocationResponse(string testName, string result) { return GetInvocationResponse($"{testName}-{result}"); } private static InvocationResponse GetInvocationResponse(string result) { ResponseStream.SetLength(0); JsonSerializer.Serialize(result, ResponseStream); ResponseStream.Position = 0; return new InvocationResponse(ResponseStream, false); } #endregion } }
469
aws-lambda-dotnet
aws
C#
using System.IO; using System.Text.Json.Serialization; using Xunit; using Amazon.Lambda.Serialization.SystemTextJson; using Amazon.Lambda.APIGatewayEvents; using System; using Amazon.Lambda.Core; using System.Text; using System.Text.Json; using Amazon.Lambda.S3Events; using Amazon.Lambda.CloudWatchEvents.BatchEvents; namespace EventsTests.NET6 { [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))] [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyResponse))] internal partial class HttpApiJsonSerializationContext : JsonSerializerContext { } [JsonSerializable(typeof(S3ObjectLambdaEvent))] internal partial class S3ObjectLambdaSerializationContext : JsonSerializerContext { } [JsonSerializable(typeof(BatchJobStateChangeEvent))] internal partial class BatchJobStateChangeEventSerializationContext : JsonSerializerContext { } public class SourceGeneratorSerializerTests { [Theory] [InlineData(typeof(SourceGeneratorLambdaJsonSerializer<HttpApiJsonSerializationContext>))] public void HttpApiV2Format(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("http-api-v2-request.json")) { var request = serializer.Deserialize<APIGatewayHttpApiV2ProxyRequest>(fileStream); Assert.Equal("2.0", request.Version); Assert.Equal("$default", request.RouteKey); Assert.Equal("/my/path", request.RawPath); Assert.Equal("parameter1=value1&parameter1=value2&parameter2=value", request.RawQueryString); Assert.Equal(2, request.Cookies.Length); Assert.Equal("cookie1", request.Cookies[0]); Assert.Equal("cookie2", request.Cookies[1]); Assert.Equal(2, request.QueryStringParameters.Count); Assert.Equal("value1,value2", request.QueryStringParameters["parameter1"]); Assert.Equal("value", request.QueryStringParameters["parameter2"]); Assert.Equal("Hello from Lambda", request.Body); Assert.True(request.IsBase64Encoded); Assert.Equal(2, request.StageVariables.Count); Assert.Equal("value1", request.StageVariables["stageVariable1"]); Assert.Equal("value2", request.StageVariables["stageVariable2"]); Assert.Equal(1, request.PathParameters.Count); Assert.Equal("value1", request.PathParameters["parameter1"]); var rc = request.RequestContext; Assert.NotNull(rc); Assert.Equal("123456789012", rc.AccountId); Assert.Equal("api-id", rc.ApiId); Assert.Equal("id.execute-api.us-east-1.amazonaws.com", rc.DomainName); Assert.Equal("domain-id", rc.DomainPrefix); Assert.Equal("request-id", rc.RequestId); Assert.Equal("route-id", rc.RouteId); Assert.Equal("$default-route", rc.RouteKey); Assert.Equal("$default-stage", rc.Stage); Assert.Equal("12/Mar/2020:19:03:58 +0000", rc.Time); Assert.Equal(1583348638390, rc.TimeEpoch); var clientCert = request.RequestContext.Authentication.ClientCert; Assert.Equal("CERT_CONTENT", clientCert.ClientCertPem); Assert.Equal("www.example.com", clientCert.SubjectDN); Assert.Equal("Example issuer", clientCert.IssuerDN); Assert.Equal("a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", clientCert.SerialNumber); Assert.Equal("May 28 12:30:02 2019 GMT", clientCert.Validity.NotBefore); Assert.Equal("Aug 5 09:36:04 2021 GMT", clientCert.Validity.NotAfter); var auth = rc.Authorizer; Assert.NotNull(auth); Assert.Equal(2, auth.Jwt.Claims.Count); Assert.Equal("value1", auth.Jwt.Claims["claim1"]); Assert.Equal("value2", auth.Jwt.Claims["claim2"]); Assert.Equal(2, auth.Jwt.Scopes.Length); Assert.Equal("scope1", auth.Jwt.Scopes[0]); Assert.Equal("scope2", auth.Jwt.Scopes[1]); var http = rc.Http; Assert.NotNull(http); Assert.Equal("POST", http.Method); Assert.Equal("/my/path", http.Path); Assert.Equal("HTTP/1.1", http.Protocol); Assert.Equal("IP", http.SourceIp); Assert.Equal("agent", http.UserAgent); } } [Theory] [InlineData(typeof(SourceGeneratorLambdaJsonSerializer<S3ObjectLambdaSerializationContext>))] public void S3ObjectLambdaEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("s3-object-lambda-event.json")) { var s3Event = serializer.Deserialize<S3ObjectLambdaEvent>(fileStream); Assert.Equal("requestId", s3Event.XAmzRequestId); Assert.Equal("https://my-s3-ap-111122223333.s3-accesspoint.us-east-1.amazonaws.com/example?X-Amz-Security-Token=<snip>", s3Event.GetObjectContext.InputS3Url); Assert.Equal("io-use1-001", s3Event.GetObjectContext.OutputRoute); Assert.Equal("OutputToken", s3Event.GetObjectContext.OutputToken); Assert.Equal("arn:aws:s3-object-lambda:us-east-1:111122223333:accesspoint/example-object-lambda-ap", s3Event.Configuration.AccessPointArn); Assert.Equal("arn:aws:s3:us-east-1:111122223333:accesspoint/example-ap", s3Event.Configuration.SupportingAccessPointArn); Assert.Equal("{}", s3Event.Configuration.Payload); Assert.Equal("https://object-lambda-111122223333.s3-object-lambda.us-east-1.amazonaws.com/example", s3Event.UserRequest.Url); Assert.Equal("object-lambda-111122223333.s3-object-lambda.us-east-1.amazonaws.com", s3Event.UserRequest.Headers["Host"]); Assert.Equal("AssumedRole", s3Event.UserIdentity.Type); Assert.Equal("principalId", s3Event.UserIdentity.PrincipalId); Assert.Equal("arn:aws:sts::111122223333:assumed-role/Admin/example", s3Event.UserIdentity.Arn); Assert.Equal("111122223333", s3Event.UserIdentity.AccountId); Assert.Equal("accessKeyId", s3Event.UserIdentity.AccessKeyId); Assert.Equal("false", s3Event.UserIdentity.SessionContext.Attributes.MfaAuthenticated); Assert.Equal("Wed Mar 10 23:41:52 UTC 2021", s3Event.UserIdentity.SessionContext.Attributes.CreationDate); Assert.Equal("Role", s3Event.UserIdentity.SessionContext.SessionIssuer.Type); Assert.Equal("principalId", s3Event.UserIdentity.SessionContext.SessionIssuer.PrincipalId); Assert.Equal("arn:aws:iam::111122223333:role/Admin", s3Event.UserIdentity.SessionContext.SessionIssuer.Arn); Assert.Equal("111122223333", s3Event.UserIdentity.SessionContext.SessionIssuer.AccountId); Assert.Equal("Admin", s3Event.UserIdentity.SessionContext.SessionIssuer.UserName); Assert.Equal("1.00", s3Event.ProtocolVersion); } } [Theory] [InlineData(typeof(SourceGeneratorLambdaJsonSerializer<BatchJobStateChangeEventSerializationContext>))] public void BatchJobStateChangeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("batch-job-state-change-event.json")) { var jobStateChangeEvent = serializer.Deserialize<BatchJobStateChangeEvent>(fileStream); Assert.Equal(jobStateChangeEvent.Version, "0"); Assert.Equal(jobStateChangeEvent.Id, "c8f9c4b5-76e5-d76a-f980-7011e206042b"); Assert.Equal(jobStateChangeEvent.DetailType, "Batch Job State Change"); Assert.Equal(jobStateChangeEvent.Source, "aws.batch"); Assert.Equal(jobStateChangeEvent.Account, "aws_account_id"); Assert.Equal(jobStateChangeEvent.Time.ToUniversalTime(), DateTime.Parse("2017-10-23T17:56:03Z").ToUniversalTime()); Assert.Equal(jobStateChangeEvent.Region, "us-east-1"); Assert.Equal(jobStateChangeEvent.Resources.Count, 1); Assert.Equal(jobStateChangeEvent.Resources[0], "arn:aws:batch:us-east-1:aws_account_id:job/4c7599ae-0a82-49aa-ba5a-4727fcce14a8"); Assert.IsType(typeof(Job), jobStateChangeEvent.Detail); Assert.Equal(jobStateChangeEvent.Detail.JobName, "event-test"); Assert.Equal(jobStateChangeEvent.Detail.JobId, "4c7599ae-0a82-49aa-ba5a-4727fcce14a8"); Assert.Equal(jobStateChangeEvent.Detail.JobQueue, "arn:aws:batch:us-east-1:aws_account_id:job-queue/HighPriority"); Assert.Equal(jobStateChangeEvent.Detail.Status, "RUNNABLE"); Assert.Equal(jobStateChangeEvent.Detail.Attempts.Count, 0); Assert.Equal(jobStateChangeEvent.Detail.CreatedAt, 1508781340401); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.Attempts, 1); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].Action, "EXIT"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnExitCode, "*"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnReason, "*"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnStatusReason, "*"); Assert.Equal(jobStateChangeEvent.Detail.DependsOn.Count, 0); Assert.Equal(jobStateChangeEvent.Detail.JobDefinition, "arn:aws:batch:us-east-1:aws_account_id:job-definition/first-run-job-definition:1"); Assert.Equal(jobStateChangeEvent.Detail.Parameters.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Parameters["test"], "abc"); Assert.Equal(jobStateChangeEvent.Detail.Container.Image, "busybox"); Assert.NotNull(jobStateChangeEvent.Detail.Container.ResourceRequirements); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[0].Type, "MEMORY"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[0].Value, "2000"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[1].Type, "VCPU"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[1].Value, "2"); Assert.Equal(jobStateChangeEvent.Detail.Container.Vcpus, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Memory, 2000); Assert.Equal(jobStateChangeEvent.Detail.Container.Command.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Command[0], "echo"); Assert.Equal(jobStateChangeEvent.Detail.Container.Command[1], "'hello world'"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[0].Name, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[0].Host.SourcePath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].Name, "efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.AccessPointId, "fsap-XXXXXXXXXXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.Iam, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.FileSystemId, "fs-XXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.RootDirectory, "/"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.TransitEncryption, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.TransitEncryptionPort, 12345); Assert.NotNull(jobStateChangeEvent.Detail.Container.Environment); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment[0].Name, "MANAGED_BY_AWS"); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment[0].Value, "STARTED_BY_STEP_FUNCTIONS"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].ContainerPath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].ReadOnly, true); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].SourceVolume, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[1].ContainerPath, "/mount/efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[1].SourceVolume, "efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].HardLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].Name, "nofile"); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].SoftLimit, 2048); Assert.NotNull(jobStateChangeEvent.Detail.Container.LinuxParameters); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].ContainerPath, "/dev/sda"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].HostPath, "/dev/xvdc"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].Permissions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].Permissions[0], "MKNOD"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.InitProcessEnabled, true); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.SharedMemorySize, 64); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.MaxSwap, 1024); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Swappiness, 55); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].ContainerPath, "/run"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].Size, 65536); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions[0], "noexec"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions[1], "nosuid"); Assert.NotNull(jobStateChangeEvent.Detail.Container.LogConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.LogDriver, "json-file"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options["max-size"], "10m"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options["max-file"], "3"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions[0].Name, "apikey"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions[0].ValueFrom, "ddApiKey"); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets[0].Name, "DATABASE_PASSWORD"); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets[0].ValueFrom, "arn:aws:ssm:us-east-1:awsExampleAccountID:parameter/awsExampleParameter"); Assert.NotNull(jobStateChangeEvent.Detail.Container.NetworkConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.NetworkConfiguration.AssignPublicIp, "ENABLED"); Assert.NotNull(jobStateChangeEvent.Detail.Container.FargatePlatformConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.FargatePlatformConfiguration.PlatformVersion, "LATEST"); Assert.NotNull(jobStateChangeEvent.Detail.NodeProperties); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.MainNode, 0); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NumNodes, 0); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].TargetNodes, "0:1"); Assert.NotNull(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Image, "busybox"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[0].Type, "MEMORY"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[0].Value, "2000"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[1].Type, "VCPU"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[1].Value, "2"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Vcpus, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Memory, 2000); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command[0], "echo"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command[1], "'hello world'"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[0].Name, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[0].Host.SourcePath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].Name, "efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.AccessPointId, "fsap-XXXXXXXXXXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.Iam, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.FileSystemId, "fs-XXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.RootDirectory, "/"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.TransitEncryption, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.TransitEncryptionPort, 12345); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment[0].Name, "MANAGED_BY_AWS"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment[0].Value, "STARTED_BY_STEP_FUNCTIONS"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].ContainerPath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].ReadOnly, true); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].SourceVolume, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[1].ContainerPath, "/mount/efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[1].SourceVolume, "efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].HardLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].Name, "nofile"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].SoftLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ExecutionRoleArn, "arn:aws:iam::awsExampleAccountID:role/awsExampleRoleName"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.InstanceType, "p3.2xlarge"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.User, "testuser"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.JobRoleArn, "arn:aws:iam::awsExampleAccountID:role/awsExampleRoleName"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].HostPath, "/dev/xvdc"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].ContainerPath, "/dev/sda"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].Permissions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].Permissions[0], "MKNOD"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.InitProcessEnabled, true); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.SharedMemorySize, 64); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.MaxSwap, 1024); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Swappiness, 55); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].ContainerPath, "/run"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].Size, 65536); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions[0], "noexec"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions[1], "nosuid"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.LogDriver, "awslogs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.Options["awslogs-group"], "awslogs-wordpress"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.Options["awslogs-stream-prefix"], "awslogs-example"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions[0].Name, "apikey"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions[0].ValueFrom, "ddApiKey"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets[0].Name, "DATABASE_PASSWORD"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets[0].ValueFrom, "arn:aws:ssm:us-east-1:awsExampleAccountID:parameter/awsExampleParameter"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.NetworkConfiguration.AssignPublicIp, "DISABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.FargatePlatformConfiguration.PlatformVersion, "LATEST"); Assert.Equal(jobStateChangeEvent.Detail.PropagateTags, true); Assert.Equal(jobStateChangeEvent.Detail.Timeout.AttemptDurationSeconds, 90); Assert.Equal(jobStateChangeEvent.Detail.Tags.Count, 3); Assert.Equal(jobStateChangeEvent.Detail.Tags["Service"], "Batch"); Assert.Equal(jobStateChangeEvent.Detail.Tags["Name"], "JobDefinitionTag"); Assert.Equal(jobStateChangeEvent.Detail.Tags["Expected"], "MergeTag"); Assert.Equal(jobStateChangeEvent.Detail.PlatformCapabilities.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.PlatformCapabilities[0], "FARGATE"); } } public MemoryStream LoadJsonTestFile(string filename) { var json = File.ReadAllText(filename); return new MemoryStream(UTF8Encoding.UTF8.GetBytes(json)); } } }
343
aws-lambda-dotnet
aws
C#
using System.IO; using Xunit; using Amazon.Lambda.Serialization.SystemTextJson; using Newtonsoft.Json.Linq; namespace EventsTests31 { public class TestResponseCasing { [Fact] public void TestPascalCase() { var serializer = new DefaultLambdaJsonSerializer(); var response = new DummyResponse { BingBong = "Joy" }; MemoryStream ms = new MemoryStream(); serializer.Serialize(response, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var serialized = JObject.Parse(json); Assert.Equal("Joy", serialized["BingBong"]?.ToString()); } [Fact] public void TestCamelCase() { var serializer = new CamelCaseLambdaJsonSerializer(); var response = new DummyResponse { BingBong = "Joy" }; MemoryStream ms = new MemoryStream(); serializer.Serialize(response, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var serialized = JObject.Parse(json); Assert.Equal("Joy", serialized["bingBong"]?.ToString()); } public class DummyResponse { public string BingBong { get; set; } } } }
55
aws-lambda-dotnet
aws
C#
#pragma warning disable 618 namespace Amazon.Lambda.Tests { using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.ApplicationLoadBalancerEvents; using Amazon.Lambda.CloudWatchEvents.BatchEvents; using Amazon.Lambda.CloudWatchEvents.ECSEvents; using Amazon.Lambda.CloudWatchEvents.ScheduledEvents; using Amazon.Lambda.CloudWatchEvents.TranscribeEvents; using Amazon.Lambda.CloudWatchEvents.TranslateEvents; using Amazon.Lambda.CloudWatchLogsEvents; using Amazon.Lambda.CognitoEvents; using Amazon.Lambda.ConfigEvents; using Amazon.Lambda.ConnectEvents; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; using Amazon.Lambda.KafkaEvents; using Amazon.Lambda.KinesisAnalyticsEvents; using Amazon.Lambda.KinesisEvents; using Amazon.Lambda.KinesisFirehoseEvents; using Amazon.Lambda.LexEvents; using Amazon.Lambda.MQEvents; using Amazon.Lambda.S3Events; using Amazon.Lambda.SimpleEmailEvents; using Amazon.Lambda.SNSEvents; using Amazon.Lambda.SQSEvents; using Amazon.Lambda.LexV2Events; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xunit; using Newtonsoft.Json; using Amazon.Lambda.CloudWatchEvents; using Amazon.Lambda.CloudWatchEvents.S3Events; using JsonSerializer = Amazon.Lambda.Serialization.Json.JsonSerializer; public class EventTest { // This utility method takes care of removing the BOM that System.Text.Json doesn't like. public MemoryStream LoadJsonTestFile(string filename) { var json = File.ReadAllText(filename); return new MemoryStream(UTF8Encoding.UTF8.GetBytes(json)); } public string SerializeJson<T>(ILambdaSerializer serializer, T response) { string serializedJson; using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(response, stream); stream.Position = 0; serializedJson = Encoding.UTF8.GetString(stream.ToArray()); } return serializedJson; } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void HttpApiV2Format(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("http-api-v2-request.json")) { var request = serializer.Deserialize<APIGatewayHttpApiV2ProxyRequest>(fileStream); Assert.Equal("2.0", request.Version); Assert.Equal("$default", request.RouteKey); Assert.Equal("/my/path", request.RawPath); Assert.Equal("parameter1=value1&parameter1=value2&parameter2=value", request.RawQueryString); Assert.Equal(2, request.Cookies.Length); Assert.Equal("cookie1", request.Cookies[0]); Assert.Equal("cookie2", request.Cookies[1]); Assert.Equal(2, request.QueryStringParameters.Count); Assert.Equal("value1,value2", request.QueryStringParameters["parameter1"]); Assert.Equal("value", request.QueryStringParameters["parameter2"]); Assert.Equal("Hello from Lambda", request.Body); Assert.True(request.IsBase64Encoded); Assert.Equal(2, request.StageVariables.Count); Assert.Equal("value1", request.StageVariables["stageVariable1"]); Assert.Equal("value2", request.StageVariables["stageVariable2"]); Assert.Equal(1, request.PathParameters.Count); Assert.Equal("value1", request.PathParameters["parameter1"]); var rc = request.RequestContext; Assert.NotNull(rc); Assert.Equal("123456789012", rc.AccountId); Assert.Equal("api-id", rc.ApiId); Assert.Equal("id.execute-api.us-east-1.amazonaws.com", rc.DomainName); Assert.Equal("domain-id", rc.DomainPrefix); Assert.Equal("request-id", rc.RequestId); Assert.Equal("route-id", rc.RouteId); Assert.Equal("$default-route", rc.RouteKey); Assert.Equal("$default-stage", rc.Stage); Assert.Equal("12/Mar/2020:19:03:58 +0000", rc.Time); Assert.Equal(1583348638390, rc.TimeEpoch); var clientCert = request.RequestContext.Authentication.ClientCert; Assert.Equal("CERT_CONTENT", clientCert.ClientCertPem); Assert.Equal("www.example.com", clientCert.SubjectDN); Assert.Equal("Example issuer", clientCert.IssuerDN); Assert.Equal("a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", clientCert.SerialNumber); Assert.Equal("May 28 12:30:02 2019 GMT", clientCert.Validity.NotBefore); Assert.Equal("Aug 5 09:36:04 2021 GMT", clientCert.Validity.NotAfter); var auth = rc.Authorizer; Assert.NotNull(auth); Assert.Equal(2, auth.Jwt.Claims.Count); Assert.Equal("value1", auth.Jwt.Claims["claim1"]); Assert.Equal("value2", auth.Jwt.Claims["claim2"]); Assert.Equal(2, auth.Jwt.Scopes.Length); Assert.Equal("scope1", auth.Jwt.Scopes[0]); Assert.Equal("scope2", auth.Jwt.Scopes[1]); var http = rc.Http; Assert.NotNull(http); Assert.Equal("POST", http.Method); Assert.Equal("/my/path", http.Path); Assert.Equal("HTTP/1.1", http.Protocol); Assert.Equal("IP", http.SourceIp); Assert.Equal("agent", http.UserAgent); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void HttpApiV2FormatLambdaAuthorizer(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("http-api-v2-request-lambda-authorizer.json")) { var request = serializer.Deserialize<APIGatewayHttpApiV2ProxyRequest>(fileStream); Assert.Equal("value", request.RequestContext.Authorizer.Lambda["key"]?.ToString()); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void HttpApiV2FormatIAMAuthorizer(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("http-api-v2-request-iam-authorizer.json")) { var request = serializer.Deserialize<APIGatewayHttpApiV2ProxyRequest>(fileStream); var iam = request.RequestContext.Authorizer.IAM; Assert.NotNull(iam); Assert.Equal("ARIA2ZJZYVUEREEIHAKY", iam.AccessKey); Assert.Equal("1234567890", iam.AccountId); Assert.Equal("AROA7ZJZYVRE7C3DUXHH6:CognitoIdentityCredentials", iam.CallerId); Assert.Equal("foo", iam.CognitoIdentity.AMR[0]); Assert.Equal("us-east-1:3f291106-8703-466b-8f2b-3ecee1ca56ce", iam.CognitoIdentity.IdentityId); Assert.Equal("us-east-1:4f291106-8703-466b-8f2b-3ecee1ca56ce", iam.CognitoIdentity.IdentityPoolId); Assert.Equal("AwsOrgId", iam.PrincipalOrgId); Assert.Equal("arn:aws:iam::1234567890:user/Admin", iam.UserARN); Assert.Equal("AROA2ZJZYVRE7Y3TUXHH6", iam.UserId); } } [Fact] public void SetHeadersToHttpApiV2Response() { var response = new APIGatewayHttpApiV2ProxyResponse(); Assert.Null(response.Headers); response.SetHeaderValues("name1", "value1", false); Assert.Single(response.Headers); Assert.Equal("value1", response.Headers["name1"]); response.SetHeaderValues("name1", "value2", true); Assert.Equal("value1,value2", response.Headers["name1"]); response.SetHeaderValues("name1", "value3", false); Assert.Equal("value3", response.Headers["name1"]); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void S3ObjectLambdaEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("s3-object-lambda-event.json")) { var s3Event = serializer.Deserialize<S3ObjectLambdaEvent>(fileStream); Assert.Equal("requestId", s3Event.XAmzRequestId); Assert.Equal("https://my-s3-ap-111122223333.s3-accesspoint.us-east-1.amazonaws.com/example?X-Amz-Security-Token=<snip>", s3Event.GetObjectContext.InputS3Url); Assert.Equal("io-use1-001", s3Event.GetObjectContext.OutputRoute); Assert.Equal("OutputToken", s3Event.GetObjectContext.OutputToken); Assert.Equal("arn:aws:s3-object-lambda:us-east-1:111122223333:accesspoint/example-object-lambda-ap", s3Event.Configuration.AccessPointArn); Assert.Equal("arn:aws:s3:us-east-1:111122223333:accesspoint/example-ap", s3Event.Configuration.SupportingAccessPointArn); Assert.Equal("{}", s3Event.Configuration.Payload); Assert.Equal("https://object-lambda-111122223333.s3-object-lambda.us-east-1.amazonaws.com/example", s3Event.UserRequest.Url); Assert.Equal("object-lambda-111122223333.s3-object-lambda.us-east-1.amazonaws.com", s3Event.UserRequest.Headers["Host"]); Assert.Equal("AssumedRole", s3Event.UserIdentity.Type); Assert.Equal("principalId", s3Event.UserIdentity.PrincipalId); Assert.Equal("arn:aws:sts::111122223333:assumed-role/Admin/example", s3Event.UserIdentity.Arn); Assert.Equal("111122223333", s3Event.UserIdentity.AccountId); Assert.Equal("accessKeyId", s3Event.UserIdentity.AccessKeyId); Assert.Equal("false", s3Event.UserIdentity.SessionContext.Attributes.MfaAuthenticated); Assert.Equal("Wed Mar 10 23:41:52 UTC 2021", s3Event.UserIdentity.SessionContext.Attributes.CreationDate); Assert.Equal("Role", s3Event.UserIdentity.SessionContext.SessionIssuer.Type); Assert.Equal("principalId", s3Event.UserIdentity.SessionContext.SessionIssuer.PrincipalId); Assert.Equal("arn:aws:iam::111122223333:role/Admin", s3Event.UserIdentity.SessionContext.SessionIssuer.Arn); Assert.Equal("111122223333", s3Event.UserIdentity.SessionContext.SessionIssuer.AccountId); Assert.Equal("Admin", s3Event.UserIdentity.SessionContext.SessionIssuer.UserName); Assert.Equal("1.00", s3Event.ProtocolVersion); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void S3PutTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("s3-event.json")) { var s3Event = serializer.Deserialize<S3Event>(fileStream); Assert.Equal(s3Event.Records.Count, 1); var record = s3Event.Records[0]; Assert.Equal(record.EventVersion, "2.0"); Assert.Equal(record.EventTime.ToUniversalTime(), DateTime.Parse("1970-01-01T00:00:00.000Z").ToUniversalTime()); Assert.Equal(record.RequestParameters.SourceIPAddress, "127.0.0.1"); Assert.Equal(record.S3.ConfigurationId, "testConfigRule"); Assert.Equal(record.S3.Object.ETag, "0123456789abcdef0123456789abcdef"); Assert.Equal(record.S3.Object.Key, "HappyFace.jpg"); Assert.Equal(record.S3.Object.Size, 1024); Assert.Equal(record.S3.Bucket.Arn, "arn:aws:s3:::mybucket"); Assert.Equal(record.S3.Bucket.Name, "sourcebucket"); Assert.Equal(record.S3.Bucket.OwnerIdentity.PrincipalId, "EXAMPLE"); Assert.Equal(record.S3.S3SchemaVersion, "1.0"); Assert.Equal(record.ResponseElements.XAmzId2, "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"); Assert.Equal(record.ResponseElements.XAmzRequestId, "EXAMPLE123456789"); Assert.Equal(record.AwsRegion, "us-east-1"); Assert.Equal(record.EventName, "ObjectCreated:Put"); Assert.Equal(record.UserIdentity.PrincipalId, "EXAMPLE"); Assert.Equal(record.EventSource, "aws:s3"); Handle(s3Event); } } private void Handle(S3Event s3Event) { foreach (var record in s3Event.Records) { var s3 = record.S3; Console.WriteLine($"[{record.EventSource} - {record.EventTime}] Bucket = {s3.Bucket.Name}, Key = {s3.Object.Key}"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-event.json")) { var kinesisEvent = serializer.Deserialize<KinesisEvent>(fileStream); Assert.Equal(kinesisEvent.Records.Count, 2); var record = kinesisEvent.Records[0]; Assert.Equal(record.EventId, "shardId-000000000000:49568167373333333333333333333333333333333333333333333333"); Assert.Equal(record.EventVersion, "1.0"); Assert.Equal(record.Kinesis.PartitionKey, "s1"); var dataBytes = record.Kinesis.Data.ToArray(); Assert.Equal(Convert.ToBase64String(dataBytes), "SGVsbG8gV29ybGQ="); Assert.Equal(Encoding.UTF8.GetString(dataBytes), "Hello World"); Assert.Equal(record.Kinesis.KinesisSchemaVersion, "1.0"); Assert.Equal(record.Kinesis.SequenceNumber, "49568167373333333333333333333333333333333333333333333333"); Assert.Equal(record.InvokeIdentityArn, "arn:aws:iam::123456789012:role/LambdaRole"); Assert.Equal(record.EventName, "aws:kinesis:record"); Assert.Equal(record.EventSourceARN, "arn:aws:kinesis:us-east-1:123456789012:stream/simple-stream"); Assert.Equal(record.EventSource, "aws:kinesis"); Assert.Equal(record.AwsRegion, "us-east-1"); Assert.Equal(636162383234770000, record.Kinesis.ApproximateArrivalTimestamp.ToUniversalTime().Ticks); Handle(kinesisEvent); } } private void Handle(KinesisEvent kinesisEvent) { foreach (var record in kinesisEvent.Records) { var kinesisRecord = record.Kinesis; var dataBytes = kinesisRecord.Data.ToArray(); var dataText = Encoding.UTF8.GetString(dataBytes); Assert.Equal("Hello World", dataText); Console.WriteLine($"[{record.EventName}] Data = '{dataText}'."); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void DynamoDbUpdateTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; Stream json = LoadJsonTestFile("dynamodb-event.json"); var dynamodbEvent = serializer.Deserialize<DynamoDBEvent>(json); Assert.Equal(dynamodbEvent.Records.Count, 2); var record = dynamodbEvent.Records[0]; Assert.Equal(record.EventID, "f07f8ca4b0b26cb9c4e5e77e69f274ee"); Assert.Equal(record.EventVersion, "1.1"); Assert.Equal(record.Dynamodb.Keys.Count, 2); Assert.Equal(record.Dynamodb.Keys["key"].S, "binary"); Assert.Equal(record.Dynamodb.Keys["val"].S, "data"); Assert.Equal(record.Dynamodb.NewImage["val"].S, "data"); Assert.Equal(record.Dynamodb.NewImage["key"].S, "binary"); Assert.Equal(MemoryStreamToBase64String(record.Dynamodb.NewImage["asdf1"].B), "AAEqQQ=="); Assert.Equal(record.Dynamodb.NewImage["asdf2"].BS.Count, 2); Assert.Equal(MemoryStreamToBase64String(record.Dynamodb.NewImage["asdf2"].BS[0]), "AAEqQQ=="); Assert.Equal(MemoryStreamToBase64String(record.Dynamodb.NewImage["asdf2"].BS[1]), "QSoBAA=="); Assert.Equal(record.Dynamodb.StreamViewType, "NEW_AND_OLD_IMAGES"); Assert.Equal(record.Dynamodb.SequenceNumber, "1405400000000002063282832"); Assert.Equal(record.Dynamodb.SizeBytes, 54); Assert.Equal(record.AwsRegion, "us-east-1"); Assert.Equal(record.EventName, "INSERT"); Assert.Equal(record.EventSourceArn, "arn:aws:dynamodb:us-east-1:123456789012:table/Example-Table/stream/2016-12-01T00:00:00.000"); Assert.Equal(record.EventSource, "aws:dynamodb"); var recordDateTime = record.Dynamodb.ApproximateCreationDateTime; Assert.Equal(recordDateTime.Ticks, 636162388200000000); Handle(dynamodbEvent); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void DynamoDbBatchItemFailuresTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("dynamodb-batchitemfailures-response.json")) { var dynamoDbStreamsEventResponse = serializer.Deserialize<StreamsEventResponse>(fileStream); Assert.Equal(1, dynamoDbStreamsEventResponse.BatchItemFailures.Count); Assert.Equal("1405400000000002063282832", dynamoDbStreamsEventResponse.BatchItemFailures[0].ItemIdentifier); MemoryStream ms = new MemoryStream(); serializer.Serialize<StreamsEventResponse>(dynamoDbStreamsEventResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("dynamodb-batchitemfailures-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } private static void Handle(DynamoDBEvent ddbEvent) { foreach (var record in ddbEvent.Records) { var ddbRecord = record.Dynamodb; var keys = string.Join(", ", ddbRecord.Keys.Keys); Console.WriteLine($"{record.EventID} - Keys = [{keys}], Size = {ddbRecord.SizeBytes} bytes"); } Console.WriteLine($"Successfully processed {ddbEvent.Records.Count} records."); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP_3_1 [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-event.json")) { var cognitoEvent = serializer.Deserialize<CognitoEvent>(fileStream); Assert.Equal(cognitoEvent.Version, 2); Assert.Equal(cognitoEvent.EventType, "SyncTrigger"); Assert.Equal(cognitoEvent.Region, "us-east-1"); Assert.Equal(cognitoEvent.DatasetName, "datasetName"); Assert.Equal(cognitoEvent.IdentityPoolId, "identityPoolId"); Assert.Equal(cognitoEvent.IdentityId, "identityId"); Assert.Equal(cognitoEvent.DatasetRecords.Count, 1); Assert.True(cognitoEvent.DatasetRecords.ContainsKey("SampleKey1")); Assert.Equal(cognitoEvent.DatasetRecords["SampleKey1"].NewValue, "newValue1"); Assert.Equal(cognitoEvent.DatasetRecords["SampleKey1"].OldValue, "oldValue1"); Assert.Equal(cognitoEvent.DatasetRecords["SampleKey1"].Op, "replace"); Handle(cognitoEvent); } } private static void Handle(CognitoEvent cognitoEvent) { foreach (var datasetKVP in cognitoEvent.DatasetRecords) { var datasetName = datasetKVP.Key; var datasetRecord = datasetKVP.Value; Console.WriteLine($"[{cognitoEvent.EventType}-{datasetName}] {datasetRecord.OldValue} -> {datasetRecord.Op} -> {datasetRecord.NewValue}"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoPreSignUpEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-presignup-event.json")) { var cognitoPreSignupEvent = serializer.Deserialize<CognitoPreSignupEvent>(fileStream); AssertBaseClass(cognitoPreSignupEvent); Assert.Equal(2, cognitoPreSignupEvent.Request.ValidationData.Count); Assert.Equal("validation_1", cognitoPreSignupEvent.Request.ValidationData.ToArray()[0].Key); Assert.Equal("validation_value_1", cognitoPreSignupEvent.Request.ValidationData.ToArray()[0].Value); Assert.Equal("validation_2", cognitoPreSignupEvent.Request.ValidationData.ToArray()[1].Key); Assert.Equal("validation_value_2", cognitoPreSignupEvent.Request.ValidationData.ToArray()[1].Value); Assert.Equal(2, cognitoPreSignupEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoPreSignupEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoPreSignupEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoPreSignupEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoPreSignupEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.True(cognitoPreSignupEvent.Response.AutoConfirmUser); Assert.True(cognitoPreSignupEvent.Response.AutoVerifyPhone); Assert.True(cognitoPreSignupEvent.Response.AutoVerifyEmail); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoPreSignupEvent>(cognitoPreSignupEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-presignup-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoPostConfirmationEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-presignup-event.json")) { var cognitoPostConfirmationEvent = serializer.Deserialize<CognitoPostConfirmationEvent>(fileStream); AssertBaseClass(cognitoPostConfirmationEvent); Assert.Equal(2, cognitoPostConfirmationEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoPostConfirmationEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoPostConfirmationEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoPostConfirmationEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoPostConfirmationEvent.Request.ClientMetadata.ToArray()[1].Value); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoPostConfirmationEvent>(cognitoPostConfirmationEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-postconfirmation-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoPreAuthenticationEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-preauthentication-event.json")) { var cognitoPreAuthenticationEvent = serializer.Deserialize<CognitoPreAuthenticationEvent>(fileStream); AssertBaseClass(cognitoPreAuthenticationEvent); Assert.Equal(2, cognitoPreAuthenticationEvent.Request.ValidationData.Count); Assert.Equal("validation_1", cognitoPreAuthenticationEvent.Request.ValidationData.ToArray()[0].Key); Assert.Equal("validation_value_1", cognitoPreAuthenticationEvent.Request.ValidationData.ToArray()[0].Value); Assert.Equal("validation_2", cognitoPreAuthenticationEvent.Request.ValidationData.ToArray()[1].Key); Assert.Equal("validation_value_2", cognitoPreAuthenticationEvent.Request.ValidationData.ToArray()[1].Value); Assert.True(cognitoPreAuthenticationEvent.Request.UserNotFound); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoPreAuthenticationEvent>(cognitoPreAuthenticationEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-preauthentication-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoPostAuthenticationEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-postauthentication-event.json")) { var cognitoPostAuthenticationEvent = serializer.Deserialize<CognitoPostAuthenticationEvent>(fileStream); AssertBaseClass(cognitoPostAuthenticationEvent); Assert.Equal(2, cognitoPostAuthenticationEvent.Request.ClientMetadata.Count); Assert.Equal("client_1", cognitoPostAuthenticationEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("client_value_1", cognitoPostAuthenticationEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("client_2", cognitoPostAuthenticationEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("client_value_2", cognitoPostAuthenticationEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoPostAuthenticationEvent.Request.ValidationData.Count); Assert.Equal("validation_1", cognitoPostAuthenticationEvent.Request.ValidationData.ToArray()[0].Key); Assert.Equal("validation_value_1", cognitoPostAuthenticationEvent.Request.ValidationData.ToArray()[0].Value); Assert.Equal("validation_2", cognitoPostAuthenticationEvent.Request.ValidationData.ToArray()[1].Key); Assert.Equal("validation_value_2", cognitoPostAuthenticationEvent.Request.ValidationData.ToArray()[1].Value); Assert.True(cognitoPostAuthenticationEvent.Request.NewDevicedUsed); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoPostAuthenticationEvent>(cognitoPostAuthenticationEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-postauthentication-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoDefineAuthChallengeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-defineauthchallenge-event.json")) { var cognitoDefineAuthChallengeEvent = serializer.Deserialize<CognitoDefineAuthChallengeEvent>(fileStream); AssertBaseClass(cognitoDefineAuthChallengeEvent); Assert.Equal(2, cognitoDefineAuthChallengeEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoDefineAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoDefineAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoDefineAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoDefineAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoDefineAuthChallengeEvent.Request.Session.Count); var session0 = cognitoDefineAuthChallengeEvent.Request.Session[0]; Assert.Equal("challenge1", session0.ChallengeName); Assert.True(session0.ChallengeResult); Assert.Equal("challenge_metadata1", session0.ChallengeMetadata); var session1 = cognitoDefineAuthChallengeEvent.Request.Session[1]; Assert.Equal("challenge2", session1.ChallengeName); Assert.False(session1.ChallengeResult); Assert.Equal("challenge_metadata2", session1.ChallengeMetadata); Assert.True(cognitoDefineAuthChallengeEvent.Request.UserNotFound); Assert.Equal("challenge", cognitoDefineAuthChallengeEvent.Response.ChallengeName); Assert.True(cognitoDefineAuthChallengeEvent.Response.IssueTokens); Assert.True(cognitoDefineAuthChallengeEvent.Response.FailAuthentication); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoDefineAuthChallengeEvent>(cognitoDefineAuthChallengeEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-defineauthchallenge-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoCreateAuthChallengeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-createauthchallenge-event.json")) { var cognitoCreateAuthChallengeEvent = serializer.Deserialize<CognitoCreateAuthChallengeEvent>(fileStream); AssertBaseClass(cognitoCreateAuthChallengeEvent); Assert.Equal("challenge", cognitoCreateAuthChallengeEvent.Request.ChallengeName); Assert.Equal(2, cognitoCreateAuthChallengeEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoCreateAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoCreateAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoCreateAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoCreateAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoCreateAuthChallengeEvent.Request.Session.Count); var session0 = cognitoCreateAuthChallengeEvent.Request.Session[0]; Assert.Equal("challenge1", session0.ChallengeName); Assert.True(session0.ChallengeResult); Assert.Equal("challenge_metadata1", session0.ChallengeMetadata); var session1 = cognitoCreateAuthChallengeEvent.Request.Session[1]; Assert.Equal("challenge2", session1.ChallengeName); Assert.False(session1.ChallengeResult); Assert.Equal("challenge_metadata2", session1.ChallengeMetadata); Assert.True(cognitoCreateAuthChallengeEvent.Request.UserNotFound); Assert.Equal(2, cognitoCreateAuthChallengeEvent.Response.PublicChallengeParameters.Count); Assert.Equal("public_1", cognitoCreateAuthChallengeEvent.Response.PublicChallengeParameters.ToArray()[0].Key); Assert.Equal("public_value_1", cognitoCreateAuthChallengeEvent.Response.PublicChallengeParameters.ToArray()[0].Value); Assert.Equal("public_2", cognitoCreateAuthChallengeEvent.Response.PublicChallengeParameters.ToArray()[1].Key); Assert.Equal("public_value_2", cognitoCreateAuthChallengeEvent.Response.PublicChallengeParameters.ToArray()[1].Value); Assert.Equal(2, cognitoCreateAuthChallengeEvent.Response.PrivateChallengeParameters.Count); Assert.Equal("private_1", cognitoCreateAuthChallengeEvent.Response.PrivateChallengeParameters.ToArray()[0].Key); Assert.Equal("private_value_1", cognitoCreateAuthChallengeEvent.Response.PrivateChallengeParameters.ToArray()[0].Value); Assert.Equal("private_2", cognitoCreateAuthChallengeEvent.Response.PrivateChallengeParameters.ToArray()[1].Key); Assert.Equal("private_value_2", cognitoCreateAuthChallengeEvent.Response.PrivateChallengeParameters.ToArray()[1].Value); Assert.Equal("challenge", cognitoCreateAuthChallengeEvent.Response.ChallengeMetadata); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoCreateAuthChallengeEvent>(cognitoCreateAuthChallengeEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-createauthchallenge-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoVerifyAuthChallengeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-verifyauthchallenge-event.json")) { var cognitoVerifyAuthChallengeEvent = serializer.Deserialize<CognitoVerifyAuthChallengeEvent>(fileStream); AssertBaseClass(cognitoVerifyAuthChallengeEvent); Assert.Equal("answer_value", cognitoVerifyAuthChallengeEvent.Request.ChallengeAnswer); Assert.Equal(2, cognitoVerifyAuthChallengeEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoVerifyAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoVerifyAuthChallengeEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoVerifyAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoVerifyAuthChallengeEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoVerifyAuthChallengeEvent.Request.PrivateChallengeParameters.Count); Assert.Equal("private_1", cognitoVerifyAuthChallengeEvent.Request.PrivateChallengeParameters.ToArray()[0].Key); Assert.Equal("private_value_1", cognitoVerifyAuthChallengeEvent.Request.PrivateChallengeParameters.ToArray()[0].Value); Assert.Equal("private_2", cognitoVerifyAuthChallengeEvent.Request.PrivateChallengeParameters.ToArray()[1].Key); Assert.Equal("private_value_2", cognitoVerifyAuthChallengeEvent.Request.PrivateChallengeParameters.ToArray()[1].Value); Assert.True(cognitoVerifyAuthChallengeEvent.Request.UserNotFound); Assert.True(cognitoVerifyAuthChallengeEvent.Response.AnswerCorrect); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoVerifyAuthChallengeEvent>(cognitoVerifyAuthChallengeEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-verifyauthchallenge-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoPreTokenGenerationEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-pretokengeneration-event.json")) { var cognitoPreTokenGenerationEvent = serializer.Deserialize<CognitoPreTokenGenerationEvent>(fileStream); AssertBaseClass(cognitoPreTokenGenerationEvent); Assert.Equal(2, cognitoPreTokenGenerationEvent.Request.GroupConfiguration.GroupsToOverride.Count); Assert.Equal("group1", cognitoPreTokenGenerationEvent.Request.GroupConfiguration.GroupsToOverride[0]); Assert.Equal("group2", cognitoPreTokenGenerationEvent.Request.GroupConfiguration.GroupsToOverride[1]); Assert.Equal(2, cognitoPreTokenGenerationEvent.Request.GroupConfiguration.IamRolesToOverride.Count); Assert.Equal("role1", cognitoPreTokenGenerationEvent.Request.GroupConfiguration.IamRolesToOverride[0]); Assert.Equal("role2", cognitoPreTokenGenerationEvent.Request.GroupConfiguration.IamRolesToOverride[1]); Assert.Equal("role", cognitoPreTokenGenerationEvent.Request.GroupConfiguration.PreferredRole); Assert.Equal(2, cognitoPreTokenGenerationEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoPreTokenGenerationEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoPreTokenGenerationEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoPreTokenGenerationEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoPreTokenGenerationEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToAddOrOverride.Count); Assert.Equal("claim_1", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToAddOrOverride.ToArray()[0].Key); Assert.Equal("claim_1_value_1", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToAddOrOverride.ToArray()[0].Value); Assert.Equal("claim_2", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToAddOrOverride.ToArray()[1].Key); Assert.Equal("claim_1_value_2", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToAddOrOverride.ToArray()[1].Value); Assert.Equal(2, cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToSuppress.Count); Assert.Equal("suppress1", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToSuppress[0]); Assert.Equal("suppress2", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.ClaimsToSuppress[1]); Assert.Equal(2, cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.GroupsToOverride.Count); Assert.Equal("group1", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.GroupsToOverride[0]); Assert.Equal("group2", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.GroupsToOverride[1]); Assert.Equal(2, cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.IamRolesToOverride.Count); Assert.Equal("role1", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.IamRolesToOverride[0]); Assert.Equal("role2", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.IamRolesToOverride[1]); Assert.Equal("role", cognitoPreTokenGenerationEvent.Response.ClaimsOverrideDetails.GroupOverrideDetails.PreferredRole); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoPreTokenGenerationEvent>(cognitoPreTokenGenerationEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-pretokengeneration-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoMigrateUserEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-migrateuser-event.json")) { var cognitoMigrateUserEvent = serializer.Deserialize<CognitoMigrateUserEvent>(fileStream); AssertBaseClass(cognitoMigrateUserEvent); Assert.Equal("username", cognitoMigrateUserEvent.Request.UserName); Assert.Equal("pwd", cognitoMigrateUserEvent.Request.Password); Assert.Equal(2, cognitoMigrateUserEvent.Request.ValidationData.Count); Assert.Equal("validation_1", cognitoMigrateUserEvent.Request.ValidationData.ToArray()[0].Key); Assert.Equal("validation_value_1", cognitoMigrateUserEvent.Request.ValidationData.ToArray()[0].Value); Assert.Equal("validation_2", cognitoMigrateUserEvent.Request.ValidationData.ToArray()[1].Key); Assert.Equal("validation_value_2", cognitoMigrateUserEvent.Request.ValidationData.ToArray()[1].Value); Assert.Equal(2, cognitoMigrateUserEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoMigrateUserEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoMigrateUserEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoMigrateUserEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoMigrateUserEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal(2, cognitoMigrateUserEvent.Response.UserAttributes.Count); Assert.Equal("attribute_1", cognitoMigrateUserEvent.Response.UserAttributes.ToArray()[0].Key); Assert.Equal("attribute_value_1", cognitoMigrateUserEvent.Response.UserAttributes.ToArray()[0].Value); Assert.Equal("attribute_2", cognitoMigrateUserEvent.Response.UserAttributes.ToArray()[1].Key); Assert.Equal("attribute_value_2", cognitoMigrateUserEvent.Response.UserAttributes.ToArray()[1].Value); Assert.Equal("action", cognitoMigrateUserEvent.Response.MessageAction); Assert.Equal("status", cognitoMigrateUserEvent.Response.FinalUserStatus); Assert.True(cognitoMigrateUserEvent.Response.ForceAliasCreation); Assert.Equal(2, cognitoMigrateUserEvent.Response.DesiredDeliveryMediums.Count); Assert.Equal("medium1", cognitoMigrateUserEvent.Response.DesiredDeliveryMediums[0]); Assert.Equal("medium2", cognitoMigrateUserEvent.Response.DesiredDeliveryMediums[1]); Assert.True(cognitoMigrateUserEvent.Response.ForceAliasCreation); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoMigrateUserEvent>(cognitoMigrateUserEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-migrateuser-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoCustomMessageEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-custommessage-event.json")) { var cognitoCustomMessageEvent = serializer.Deserialize<CognitoCustomMessageEvent>(fileStream); AssertBaseClass(cognitoCustomMessageEvent); Assert.Equal("code", cognitoCustomMessageEvent.Request.CodeParameter); Assert.Equal("username", cognitoCustomMessageEvent.Request.UsernameParameter); Assert.Equal(2, cognitoCustomMessageEvent.Request.ClientMetadata.Count); Assert.Equal("metadata_1", cognitoCustomMessageEvent.Request.ClientMetadata.ToArray()[0].Key); Assert.Equal("metadata_value_1", cognitoCustomMessageEvent.Request.ClientMetadata.ToArray()[0].Value); Assert.Equal("metadata_2", cognitoCustomMessageEvent.Request.ClientMetadata.ToArray()[1].Key); Assert.Equal("metadata_value_2", cognitoCustomMessageEvent.Request.ClientMetadata.ToArray()[1].Value); Assert.Equal("sms", cognitoCustomMessageEvent.Response.SmsMessage); Assert.Equal("email", cognitoCustomMessageEvent.Response.EmailMessage); Assert.Equal("subject", cognitoCustomMessageEvent.Response.EmailSubject); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoCustomMessageEvent>(cognitoCustomMessageEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-custommessage-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoCustomEmailSenderEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-customemailsender-event.json")) { var cognitoCustomEmailSenderEvent = serializer.Deserialize<CognitoCustomEmailSenderEvent>(fileStream); AssertBaseClass(cognitoCustomEmailSenderEvent); Assert.Equal("code", cognitoCustomEmailSenderEvent.Request.Code); Assert.Equal("type", cognitoCustomEmailSenderEvent.Request.Type); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoCustomEmailSenderEvent>(cognitoCustomEmailSenderEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-customemailsender-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CognitoCustomSmsSenderEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cognito-customsmssender-event.json")) { var cognitoCustomSmsSenderEvent = serializer.Deserialize<CognitoCustomSmsSenderEvent>(fileStream); AssertBaseClass(cognitoCustomSmsSenderEvent); Assert.Equal("code", cognitoCustomSmsSenderEvent.Request.Code); Assert.Equal("type", cognitoCustomSmsSenderEvent.Request.Type); MemoryStream ms = new MemoryStream(); serializer.Serialize<CognitoCustomSmsSenderEvent>(cognitoCustomSmsSenderEvent, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("cognito-customsmssender-event.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } private static void AssertBaseClass<TRequest, TResponse>(CognitoTriggerEvent<TRequest, TResponse> cognitoTriggerEvent) where TRequest : CognitoTriggerRequest, new() where TResponse : CognitoTriggerResponse, new() { Assert.Equal("1", cognitoTriggerEvent.Version); Assert.Equal("us-east-1", cognitoTriggerEvent.Region); Assert.Equal("us-east-1_id", cognitoTriggerEvent.UserPoolId); Assert.Equal("username_uuid", cognitoTriggerEvent.UserName); Assert.NotNull(cognitoTriggerEvent.CallerContext); Assert.Equal("version", cognitoTriggerEvent.CallerContext.AwsSdkVersion); Assert.Equal("client_id", cognitoTriggerEvent.CallerContext.ClientId); Assert.Equal("trigger_source", cognitoTriggerEvent.TriggerSource); Assert.NotNull(cognitoTriggerEvent.Request); Assert.Equal(2, cognitoTriggerEvent.Request.UserAttributes.Count); Assert.Equal("attribute_1", cognitoTriggerEvent.Request.UserAttributes.ToArray()[0].Key); Assert.Equal("attribute_value_1", cognitoTriggerEvent.Request.UserAttributes.ToArray()[0].Value); Assert.Equal("attribute_2", cognitoTriggerEvent.Request.UserAttributes.ToArray()[1].Key); Assert.Equal("attribute_value_2", cognitoTriggerEvent.Request.UserAttributes.ToArray()[1].Value); Assert.NotNull(cognitoTriggerEvent.Response); } String ConfigInvokingEvent = "{\"configSnapshotId\":\"00000000-0000-0000-0000-000000000000\",\"s3ObjectKey\":\"AWSLogs/000000000000/Config/us-east-1/2016/2/24/ConfigSnapshot/000000000000_Config_us-east-1_ConfigSnapshot_20160224T182319Z_00000000-0000-0000-0000-000000000000.json.gz\",\"s3Bucket\":\"config-bucket\",\"notificationCreationTime\":\"2016-02-24T18:23:20.328Z\",\"messageType\":\"ConfigurationSnapshotDeliveryCompleted\",\"recordVersion\":\"1.1\"}"; [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ConfigTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("config-event.json")) { var configEvent = serializer.Deserialize<ConfigEvent>(fileStream); Assert.Equal(configEvent.ConfigRuleId, "config-rule-0123456"); Assert.Equal(configEvent.Version, "1.0"); Assert.Equal(configEvent.ConfigRuleName, "periodic-config-rule"); Assert.Equal(configEvent.ConfigRuleArn, "arn:aws:config:us-east-1:012345678912:config-rule/config-rule-0123456"); Assert.Equal(configEvent.InvokingEvent, ConfigInvokingEvent); Assert.Equal(configEvent.ResultToken, "myResultToken"); Assert.Equal(configEvent.EventLeftScope, false); Assert.Equal(configEvent.RuleParameters, "{\"<myParameterKey>\":\"<myParameterValue>\"}"); Assert.Equal(configEvent.ExecutionRoleArn, "arn:aws:iam::012345678912:role/config-role"); Assert.Equal(configEvent.AccountId, "012345678912"); Handle(configEvent); } } private static void Handle(ConfigEvent configEvent) { Console.WriteLine($"AWS Config rule - {configEvent.ConfigRuleName}"); Console.WriteLine($"Invoking event JSON - {configEvent.InvokingEvent}"); Console.WriteLine($"Event version - {configEvent.Version}"); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ConnectContactFlowTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("connect-contactflow-event.json")) { var contactFlowEvent = serializer.Deserialize<ContactFlowEvent>(fileStream); Assert.Equal(contactFlowEvent.Name, "ContactFlowEvent"); Assert.NotNull(contactFlowEvent.Details); Assert.NotNull(contactFlowEvent.Details.ContactData); Assert.NotNull(contactFlowEvent.Details.ContactData.Attributes); Assert.Equal(contactFlowEvent.Details.ContactData.Attributes.Count, 0); Assert.Equal(contactFlowEvent.Details.ContactData.Channel, "VOICE"); Assert.Equal(contactFlowEvent.Details.ContactData.ContactId, "4a573372-1f28-4e26-b97b-XXXXXXXXXXX"); Assert.NotNull(contactFlowEvent.Details.ContactData.CustomerEndpoint); Assert.Equal(contactFlowEvent.Details.ContactData.CustomerEndpoint.Address, "+1234567890"); Assert.Equal(contactFlowEvent.Details.ContactData.CustomerEndpoint.Type, "TELEPHONE_NUMBER"); Assert.Equal(contactFlowEvent.Details.ContactData.InitialContactId, "4a573372-1f28-4e26-b97b-XXXXXXXXXXX"); Assert.Equal(contactFlowEvent.Details.ContactData.InitiationMethod, "INBOUND | OUTBOUND | TRANSFER | CALLBACK"); Assert.Equal(contactFlowEvent.Details.ContactData.InstanceARN, "arn:aws:connect:aws-region:1234567890:instance/c8c0e68d-2200-4265-82c0-XXXXXXXXXX"); Assert.Equal(contactFlowEvent.Details.ContactData.PreviousContactId, "4a573372-1f28-4e26-b97b-XXXXXXXXXXX"); Assert.NotNull(contactFlowEvent.Details.ContactData.Queue); Assert.Equal(contactFlowEvent.Details.ContactData.Queue.Arn, "arn:aws:connect:eu-west-2:111111111111:instance/cccccccc-bbbb-dddd-eeee-ffffffffffff/queue/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); Assert.Equal(contactFlowEvent.Details.ContactData.Queue.Name, "PasswordReset"); Assert.NotNull(contactFlowEvent.Details.ContactData.SystemEndpoint); Assert.Equal(contactFlowEvent.Details.ContactData.SystemEndpoint.Address, "+1234567890"); Assert.Equal(contactFlowEvent.Details.ContactData.SystemEndpoint.Type, "TELEPHONE_NUMBER"); Assert.NotNull(contactFlowEvent.Details.Parameters); Assert.Equal(contactFlowEvent.Details.Parameters.Count, 1); Assert.Equal(contactFlowEvent.Details.Parameters["sentAttributeKey"], "sentAttributeValue"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SimpleEmailTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("simple-email-event-lambda.json")) { var sesEvent = serializer.Deserialize<SimpleEmailEvent<SimpleEmailEvents.Actions.LambdaReceiptAction>>(fileStream); Assert.Equal(sesEvent.Records.Count, 1); var record = sesEvent.Records[0]; Assert.Equal(record.EventVersion, "1.0"); Assert.Equal(record.EventSource, "aws:ses"); Assert.Equal(record.Ses.Mail.CommonHeaders.From.Count, 1); Assert.Equal(record.Ses.Mail.CommonHeaders.From[0], "Amazon Web Services <[email protected]>"); Assert.Equal(record.Ses.Mail.CommonHeaders.To.Count, 1); Assert.Equal(record.Ses.Mail.CommonHeaders.To[0], "[email protected]"); Assert.Equal(record.Ses.Mail.CommonHeaders.ReturnPath, "[email protected]"); Assert.Equal(record.Ses.Mail.CommonHeaders.MessageId, "<[email protected]>"); Assert.Equal(record.Ses.Mail.CommonHeaders.Date, "Mon, 5 Dec 2016 18:40:08 -0800"); Assert.Equal(record.Ses.Mail.CommonHeaders.Subject, "Test Subject"); Assert.Equal(record.Ses.Mail.Source, "[email protected]"); Assert.Equal(record.Ses.Mail.Timestamp.ToUniversalTime(), DateTime.Parse("2016-12-06T02:40:08.000Z").ToUniversalTime()); Assert.Equal(record.Ses.Mail.Destination.Count, 1); Assert.Equal(record.Ses.Mail.Destination[0], "[email protected]"); Assert.Equal(record.Ses.Mail.Headers.Count, 10); Assert.Equal(record.Ses.Mail.Headers[0].Name, "Return-Path"); Assert.Equal(record.Ses.Mail.Headers[0].Value, "<[email protected]>"); Assert.Equal(record.Ses.Mail.Headers[1].Name, "Received"); Assert.Equal(record.Ses.Mail.Headers[1].Value, "from mx.amazon.com (mx.amazon.com [127.0.0.1]) by inbound-smtp.us-east-1.amazonaws.com with SMTP id 6n4thuhcbhpfiuf25gshf70rss364fuejrvmqko1 for [email protected]; Tue, 06 Dec 2016 02:40:10 +0000 (UTC)"); Assert.Equal(record.Ses.Mail.Headers[2].Name, "DKIM-Signature"); Assert.Equal(record.Ses.Mail.Headers[2].Value, "v=1; a=rsa-sha256; c=relaxed/relaxed; d=iatn.net; s=amazon; h=mime-version:from:date:message-id:subject:to; bh=chlJxa/vZ11+0O9lf4tKDM/CcPjup2nhhdITm+hSf3c=; b=SsoNPK0wX7umtWnw8pln3YSib+E09XO99d704QdSc1TR1HxM0OTti/UaFxVD4e5b0+okBqo3rgVeWgNZ0sWZEUhBaZwSL3kTd/nHkcPexeV0XZqEgms1vmbg75F6vlz9igWflO3GbXyTRBNMM0gUXKU/686hpVW6aryEIfM/rLY="); Assert.Equal(record.Ses.Mail.Headers[3].Name, "MIME-Version"); Assert.Equal(record.Ses.Mail.Headers[3].Value, "1.0"); Assert.Equal(record.Ses.Mail.Headers[4].Name, "From"); Assert.Equal(record.Ses.Mail.Headers[4].Value, "Amazon Web Services <[email protected]>"); Assert.Equal(record.Ses.Mail.Headers[5].Name, "Date"); Assert.Equal(record.Ses.Mail.Headers[5].Value, "Mon, 5 Dec 2016 18:40:08 -0800"); Assert.Equal(record.Ses.Mail.Headers[6].Name, "Message-ID"); Assert.Equal(record.Ses.Mail.Headers[6].Value, "<[email protected]>"); Assert.Equal(record.Ses.Mail.Headers[7].Name, "Subject"); Assert.Equal(record.Ses.Mail.Headers[7].Value, "Test Subject"); Assert.Equal(record.Ses.Mail.Headers[8].Name, "To"); Assert.Equal(record.Ses.Mail.Headers[8].Value, "[email protected]"); Assert.Equal(record.Ses.Mail.Headers[9].Name, "Content-Type"); Assert.Equal(record.Ses.Mail.Headers[9].Value, "multipart/alternative; boundary=94eb2c0742269658b10542f452a9"); Assert.Equal(record.Ses.Mail.HeadersTruncated, false); Assert.Equal(record.Ses.Mail.MessageId, "6n4thuhcbhpfiuf25gshf70rss364fuejrvmqko1"); Assert.Equal(record.Ses.Receipt.Recipients.Count, 1); Assert.Equal(record.Ses.Receipt.Recipients[0], "[email protected]"); Assert.Equal(record.Ses.Receipt.Timestamp.ToUniversalTime(), DateTime.Parse("2016-12-06T02:40:08.000Z").ToUniversalTime()); Assert.Equal(record.Ses.Receipt.SpamVerdict.Status, "PASS"); Assert.Equal(record.Ses.Receipt.DKIMVerdict.Status, "PASS"); Assert.Equal(record.Ses.Receipt.SPFVerdict.Status, "PASS"); Assert.Equal(record.Ses.Receipt.VirusVerdict.Status, "PASS"); Assert.Equal(record.Ses.Receipt.DMARCVerdict.Status, "PASS"); Assert.Equal(record.Ses.Receipt.ProcessingTimeMillis, 574); Handle(sesEvent); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SimpleEmailLambdaActionTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("simple-email-event-lambda.json")) { var sesEvent = serializer.Deserialize<SimpleEmailEvent<SimpleEmailEvents.Actions.LambdaReceiptAction>>(fileStream); Assert.Equal(sesEvent.Records.Count, 1); var record = sesEvent.Records[0]; Assert.Equal(record.Ses.Receipt.Action.Type, "Lambda"); Assert.Equal(record.Ses.Receipt.Action.InvocationType, "Event"); Assert.Equal(record.Ses.Receipt.Action.FunctionArn, "arn:aws:lambda:us-east-1:000000000000:function:my-ses-lambda-function"); Handle(sesEvent); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SimpleEmailS3ActionTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("simple-email-event-s3.json")) { var sesEvent = serializer.Deserialize<SimpleEmailEvent<SimpleEmailEvents.Actions.S3ReceiptAction>>(fileStream); Assert.Equal(sesEvent.Records.Count, 1); var record = sesEvent.Records[0]; Assert.Equal(record.Ses.Receipt.Action.Type, "S3"); Assert.Equal(record.Ses.Receipt.Action.TopicArn, "arn:aws:sns:eu-west-1:123456789:ses-email-received"); Assert.Equal(record.Ses.Receipt.Action.BucketName, "my-ses-inbox"); Assert.Equal(record.Ses.Receipt.Action.ObjectKeyPrefix, "important"); Assert.Equal(record.Ses.Receipt.Action.ObjectKey, "important/fiddlyfaddlyhiddlyhoodly"); Handle(sesEvent); } } private static void Handle<TReceiptAction>(SimpleEmailEvent<TReceiptAction> sesEvent) where TReceiptAction : SimpleEmailEvents.Actions.IReceiptAction { foreach (var record in sesEvent.Records) { var sesRecord = record.Ses; Console.WriteLine($"[{record.EventSource} {sesRecord.Mail.Timestamp}] Subject = {sesRecord.Mail.CommonHeaders.Subject}"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SNSTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("sns-event.json")) { var snsEvent = serializer.Deserialize<SNSEvent>(fileStream); Assert.Equal(snsEvent.Records.Count, 1); var record = snsEvent.Records[0]; Assert.Equal(record.EventVersion, "1.0"); Assert.Equal(record.EventSubscriptionArn, "arn:aws:sns:EXAMPLE"); Assert.Equal(record.EventSource, "aws:sns"); Assert.Equal(record.Sns.SignatureVersion, "1"); Assert.Equal(record.Sns.Timestamp.ToUniversalTime(), DateTime.Parse("1970-01-01T00:00:00.000Z").ToUniversalTime()); Assert.Equal(record.Sns.Signature, "EXAMPLE"); Assert.Equal(record.Sns.SigningCertUrl, "EXAMPLE"); Assert.Equal(record.Sns.MessageId, "95df01b4-ee98-5cb9-9903-4c221d41eb5e"); Assert.Equal(record.Sns.Message, "Hello from SNS!"); Assert.True(record.Sns.MessageAttributes.ContainsKey("Test")); Assert.Equal(record.Sns.MessageAttributes["Test"].Type, "String"); Assert.Equal(record.Sns.MessageAttributes["Test"].Value, "TestString"); Assert.True(record.Sns.MessageAttributes.ContainsKey("TestBinary")); Assert.Equal(record.Sns.MessageAttributes["TestBinary"].Type, "Binary"); Assert.Equal(record.Sns.MessageAttributes["TestBinary"].Value, "TestBinary"); Assert.Equal(record.Sns.Type, "Notification"); Assert.Equal(record.Sns.UnsubscribeUrl, "EXAMPLE"); Assert.Equal(record.Sns.TopicArn, "arn:aws:sns:EXAMPLE"); Assert.Equal(record.Sns.Subject, "TestInvoke"); Handle(snsEvent); } } private static void Handle(SNSEvent snsEvent) { foreach (var record in snsEvent.Records) { var snsRecord = record.Sns; Console.WriteLine($"[{record.EventSource} {snsRecord.Timestamp}] Message = {snsRecord.Message}"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SQSTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("sqs-event.json")) { var sqsEvent = serializer.Deserialize<SQSEvent>(fileStream); Assert.Equal(sqsEvent.Records.Count, 1); var record = sqsEvent.Records[0]; Assert.Equal("MessageID", record.MessageId); Assert.Equal("MessageReceiptHandle", record.ReceiptHandle); Assert.Equal("Message Body", record.Body); Assert.Equal("fce0ea8dd236ccb3ed9b37dae260836f", record.Md5OfBody); Assert.Equal("582c92c5c5b6ac403040a4f3ab3115c9", record.Md5OfMessageAttributes); Assert.Equal("arn:aws:sqs:us-west-2:123456789012:SQSQueue", record.EventSourceArn); Assert.Equal("aws:sqs", record.EventSource); Assert.Equal("us-west-2", record.AwsRegion); Assert.Equal("2", record.Attributes["ApproximateReceiveCount"]); Assert.Equal("1520621625029", record.Attributes["SentTimestamp"]); Assert.Equal("AROAIWPX5BD2BHG722MW4:sender", record.Attributes["SenderId"]); Assert.Equal("1520621634884", record.Attributes["ApproximateFirstReceiveTimestamp"]); Assert.Equal(2, record.MessageAttributes.Count); { var attribute1 = record.MessageAttributes["Attribute1"]; Assert.NotNull(attribute1); Assert.Equal("123", attribute1.StringValue); Assert.Equal("Smaug", new StreamReader(attribute1.BinaryValue).ReadToEnd()); Assert.Equal(2, attribute1.StringListValues.Count); Assert.Equal("a1", attribute1.StringListValues[0]); Assert.Equal("a2", attribute1.StringListValues[1]); Assert.Equal(2, attribute1.BinaryListValues.Count); Assert.Equal("Vermithrax", new StreamReader(attribute1.BinaryListValues[0]).ReadToEnd()); Assert.Equal("Pejorative", new StreamReader(attribute1.BinaryListValues[1]).ReadToEnd()); Assert.Equal("Number", attribute1.DataType); } { var attribute2 = record.MessageAttributes["Attribute2"]; Assert.NotNull(attribute2); Assert.Equal("AttributeValue2", attribute2.StringValue); Assert.Equal(2, attribute2.StringListValues.Count); Assert.Equal("b1", attribute2.StringListValues[0]); Assert.Equal("b2", attribute2.StringListValues[1]); Assert.Equal("String", attribute2.DataType); Assert.Null(attribute2.BinaryValue); } Handle(sqsEvent); } } private static void Handle(SQSEvent sqsEvent) { foreach (var record in sqsEvent.Records) { Console.WriteLine($"[{record.EventSource}] Body = {record.Body}"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void SQSBatchResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("sqs-response.json")) { var sqsBatchResponse = serializer.Deserialize<SQSBatchResponse>(fileStream); Assert.Equal(sqsBatchResponse.BatchItemFailures.Count, 2); { var item1 = sqsBatchResponse.BatchItemFailures[0]; Assert.NotNull(item1); Assert.Equal("MessageID_1", item1.ItemIdentifier); } var item2 = sqsBatchResponse.BatchItemFailures[1]; { Assert.NotNull(item2); Assert.Equal("MessageID_2", item2.ItemIdentifier); } MemoryStream ms = new MemoryStream(); serializer.Serialize<SQSBatchResponse>(sqsBatchResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("sqs-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayProxyRequestTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("proxy-event.json")) { var proxyEvent = serializer.Deserialize<APIGatewayProxyRequest>(fileStream); Assert.Equal(proxyEvent.Resource, "/{proxy+}"); Assert.Equal(proxyEvent.Path, "/hello/world"); Assert.Equal(proxyEvent.HttpMethod, "POST"); Assert.Equal(proxyEvent.Body, "{\r\n\t\"a\": 1\r\n}"); var headers = proxyEvent.Headers; Assert.Equal(headers["Accept"], "*/*"); Assert.Equal(headers["Accept-Encoding"], "gzip, deflate"); Assert.Equal(headers["cache-control"], "no-cache"); Assert.Equal(headers["CloudFront-Forwarded-Proto"], "https"); var queryStringParameters = proxyEvent.QueryStringParameters; Assert.Equal(queryStringParameters["name"], "me"); var pathParameters = proxyEvent.PathParameters; Assert.Equal(pathParameters["proxy"], "hello/world"); var stageVariables = proxyEvent.StageVariables; Assert.Equal(stageVariables["stageVariableName"], "stageVariableValue"); var requestContext = proxyEvent.RequestContext; Assert.Equal(requestContext.AccountId, "12345678912"); Assert.Equal(requestContext.ResourceId, "roq9wj"); Assert.Equal(requestContext.Stage, "testStage"); Assert.Equal(requestContext.RequestId, "deef4878-7910-11e6-8f14-25afc3e9ae33"); Assert.Equal(requestContext.ConnectionId, "d034bc98-beed-4fdf-9e85-11bfc15bf734"); Assert.Equal(requestContext.DomainName, "somerandomdomain.net"); Assert.Equal(1519166937665, requestContext.RequestTimeEpoch); Assert.Equal("20/Feb/2018:22:48:57 +0000", requestContext.RequestTime); var identity = requestContext.Identity; Assert.Equal(identity.CognitoIdentityPoolId, "theCognitoIdentityPoolId"); Assert.Equal(identity.AccountId, "theAccountId"); Assert.Equal(identity.CognitoIdentityId, "theCognitoIdentityId"); Assert.Equal(identity.Caller, "theCaller"); Assert.Equal(identity.ApiKey, "theApiKey"); Assert.Equal(identity.SourceIp, "192.168.196.186"); Assert.Equal(identity.CognitoAuthenticationType, "theCognitoAuthenticationType"); Assert.Equal(identity.CognitoAuthenticationProvider, "theCognitoAuthenticationProvider"); Assert.Equal(identity.UserArn, "theUserArn"); Assert.Equal(identity.UserAgent, "PostmanRuntime/2.4.5"); Assert.Equal(identity.User, "theUser"); Assert.Equal("IAM_user_access_key", identity.AccessKey); var clientCert = identity.ClientCert; Assert.Equal("CERT_CONTENT", clientCert.ClientCertPem); Assert.Equal("www.example.com", clientCert.SubjectDN); Assert.Equal("Example issuer", clientCert.IssuerDN); Assert.Equal("a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", clientCert.SerialNumber); Assert.Equal("May 28 12:30:02 2019 GMT", clientCert.Validity.NotBefore); Assert.Equal("Aug 5 09:36:04 2021 GMT", clientCert.Validity.NotAfter); Handle(proxyEvent); } } private static APIGatewayProxyResponse Handle(APIGatewayProxyRequest apigProxyEvent) { Console.WriteLine($"Processing request data for request {apigProxyEvent.RequestContext.RequestId}."); Console.WriteLine($"Body size = {apigProxyEvent.Body.Length}."); var headerNames = string.Join(", ", apigProxyEvent.Headers.Keys); Console.WriteLine($"Specified headers = {headerNames}."); return new APIGatewayProxyResponse { Body = apigProxyEvent.Body, StatusCode = 200, }; } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayProxyResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var response = new APIGatewayProxyResponse { StatusCode = 200, Headers = new Dictionary<string, string> { { "Header1", "Value1" }, { "Header2", "Value2" } }, Body = "theBody" }; string serializedJson; using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(response, stream); stream.Position = 0; serializedJson = Encoding.UTF8.GetString(stream.ToArray()); } JObject root = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson) as JObject; Assert.Equal(root["statusCode"], 200); Assert.Equal(root["body"], "theBody"); Assert.NotNull(root["headers"]); var headers = root["headers"] as JObject; Assert.Equal(headers["Header1"], "Value1"); Assert.Equal(headers["Header2"], "Value2"); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayAuthorizerResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var context = new APIGatewayCustomAuthorizerContextOutput(); context["field1"] = "value1"; context["field2"] = "value2"; var response = new APIGatewayCustomAuthorizerResponse { PrincipalID = "prin1", UsageIdentifierKey = "usageKey", Context = context, PolicyDocument = new APIGatewayCustomAuthorizerPolicy { Version = "2012-10-17", Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement> { new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Action = new HashSet<string>{ "execute-api:Invoke" }, Effect = "Allow", Resource = new HashSet<string>{ "*" } } } } }; string serializedJson; using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(response, stream); stream.Position = 0; serializedJson = Encoding.UTF8.GetString(stream.ToArray()); } JObject root = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson) as JObject; Assert.Equal("prin1", root["principalId"]); Assert.Equal("usageKey", root["usageIdentifierKey"]); Assert.Equal("value1", root["context"]["field1"]); Assert.Equal("value2", root["context"]["field2"]); Assert.Equal("2012-10-17", root["policyDocument"]["Version"]); Assert.Equal("execute-api:Invoke", root["policyDocument"]["Statement"][0]["Action"][0]); Assert.Equal("Allow", root["policyDocument"]["Statement"][0]["Effect"]); Assert.Equal("*", root["policyDocument"]["Statement"][0]["Resource"][0]); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void WebSocketApiConnectTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("websocket-api-connect-request.json")) { var proxyEvent = serializer.Deserialize<APIGatewayProxyRequest>(fileStream); Assert.Null(proxyEvent.Resource); Assert.Null(proxyEvent.Path); Assert.Null(proxyEvent.HttpMethod); Assert.Null(proxyEvent.Body); var headers = proxyEvent.Headers; Assert.Equal(headers["HeaderAuth1"], "headerValue1"); Assert.Equal(headers["Host"], "lg10ltpf4f.execute-api.us-east-2.amazonaws.com"); Assert.Equal(headers["Sec-WebSocket-Extensions"], "permessage-deflate; client_max_window_bits"); Assert.Equal(headers["Sec-WebSocket-Key"], "BvlrrFKoKAPDYOlwBcGKWw=="); Assert.Equal(headers["Sec-WebSocket-Version"], "13"); Assert.Equal(headers["X-Amzn-Trace-Id"], "Root=1-625d9ad1-37a5d33a61dd9be33ae3a247"); Assert.Equal(headers["X-Forwarded-For"], "52.95.4.0"); Assert.Equal(headers["X-Forwarded-Port"], "443"); Assert.Equal(headers["X-Forwarded-Proto"], "https"); var multiValueHeaders = proxyEvent.MultiValueHeaders; Assert.Equal(multiValueHeaders["HeaderAuth1"].Count, 1); Assert.Equal(multiValueHeaders["HeaderAuth1"][0], "headerValue1"); Assert.Equal(multiValueHeaders["Host"].Count, 1); Assert.Equal(multiValueHeaders["Host"][0], "lg10ltpf4f.execute-api.us-east-2.amazonaws.com"); Assert.Equal(multiValueHeaders["Sec-WebSocket-Extensions"].Count, 1); Assert.Equal(multiValueHeaders["Sec-WebSocket-Extensions"][0], "permessage-deflate; client_max_window_bits"); Assert.Equal(multiValueHeaders["Sec-WebSocket-Key"].Count, 1); Assert.Equal(multiValueHeaders["Sec-WebSocket-Key"][0], "BvlrrFKoKAPDYOlwBcGKWw=="); Assert.Equal(multiValueHeaders["Sec-WebSocket-Version"].Count, 1); Assert.Equal(multiValueHeaders["Sec-WebSocket-Version"][0], "13"); Assert.Equal(multiValueHeaders["X-Amzn-Trace-Id"].Count, 1); Assert.Equal(multiValueHeaders["X-Amzn-Trace-Id"][0], "Root=1-625d9ad1-37a5d33a61dd9be33ae3a247"); Assert.Equal(multiValueHeaders["X-Forwarded-For"].Count, 1); Assert.Equal(multiValueHeaders["X-Forwarded-For"][0], "52.95.4.0"); Assert.Equal(multiValueHeaders["X-Forwarded-Port"].Count, 1); Assert.Equal(multiValueHeaders["X-Forwarded-Port"][0], "443"); Assert.Equal(multiValueHeaders["X-Forwarded-Proto"].Count, 1); Assert.Equal(multiValueHeaders["X-Forwarded-Proto"][0], "https"); var requestContext = proxyEvent.RequestContext; Assert.Equal(requestContext.RouteKey, "$connect"); Assert.Equal(requestContext.EventType, "CONNECT"); Assert.Equal(requestContext.ExtendedRequestId, "QyUg1HJgCYcFvbw="); Assert.Equal(requestContext.RequestTime, "18/Apr/2022:17:07:29 +0000"); Assert.Equal(requestContext.MessageDirection, "IN"); Assert.Equal(requestContext.Stage, "production"); Assert.Equal(requestContext.ConnectedAt, 1650301649973); Assert.Equal(requestContext.RequestTimeEpoch, 1650301649973); Assert.Equal(requestContext.RequestId, "QyUg1HJgCYcFvbw="); Assert.Equal(requestContext.DomainName, "lg10ltpf4f.execute-api.us-east-2.amazonaws.com"); Assert.Equal(requestContext.ConnectionId, "QyUg1czHCYcCHXw="); Assert.Equal(requestContext.ApiId, "lg10ltpf4f"); Assert.False(proxyEvent.IsBase64Encoded); var identity = requestContext.Identity; Assert.Equal(identity.SourceIp, "52.95.4.0"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ApplicationLoadBalancerRequestSingleValueTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("alb-request-single-value.json")) { var evnt = serializer.Deserialize<ApplicationLoadBalancerRequest>(fileStream); Assert.Equal(evnt.Path, "/"); Assert.Equal(evnt.HttpMethod, "GET"); Assert.Equal(evnt.Body, "not really base64"); Assert.True(evnt.IsBase64Encoded); Assert.Equal(2, evnt.QueryStringParameters.Count); Assert.Equal("value1", evnt.QueryStringParameters["query1"]); Assert.Equal("value2", evnt.QueryStringParameters["query2"]); Assert.Equal("value1", evnt.Headers["head1"]); Assert.Equal("value2", evnt.Headers["head2"]); var requestContext = evnt.RequestContext; Assert.Equal(requestContext.Elb.TargetGroupArn, "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ApplicationLoadBalancerRequestMultiValueTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("alb-request-multi-value.json")) { var evnt = serializer.Deserialize<ApplicationLoadBalancerRequest>(fileStream); Assert.Equal(evnt.Path, "/"); Assert.Equal(evnt.HttpMethod, "GET"); Assert.Equal(evnt.Body, "not really base64"); Assert.True(evnt.IsBase64Encoded); Assert.Equal(2, evnt.MultiValueQueryStringParameters.Count); Assert.Equal(2, evnt.MultiValueQueryStringParameters["query1"].Count); Assert.Equal("q1-value1", evnt.MultiValueQueryStringParameters["query1"][0]); Assert.Equal("q1-value2", evnt.MultiValueQueryStringParameters["query1"][1]); Assert.Equal(2, evnt.MultiValueQueryStringParameters["query2"].Count); Assert.Equal("q2-value1", evnt.MultiValueQueryStringParameters["query2"][0]); Assert.Equal("q2-value2", evnt.MultiValueQueryStringParameters["query2"][1]); Assert.Equal(2, evnt.MultiValueHeaders["head1"].Count); Assert.Equal(2, evnt.MultiValueHeaders["head1"].Count); Assert.Equal("h1-value1", evnt.MultiValueHeaders["head1"][0]); Assert.Equal("h1-value2", evnt.MultiValueHeaders["head1"][1]); Assert.Equal(2, evnt.MultiValueHeaders["head2"].Count); Assert.Equal("h2-value1", evnt.MultiValueHeaders["head2"][0]); Assert.Equal("h2-value2", evnt.MultiValueHeaders["head2"][1]); var requestContext = evnt.RequestContext; Assert.Equal(requestContext.Elb.TargetGroupArn, "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ApplicationLoadBalancerSingleHeaderResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var response = new ApplicationLoadBalancerResponse() { Headers = new Dictionary<string, string> { {"Head1", "h1-value1"}, {"Head2", "h2-value1"} }, IsBase64Encoded = true, Body = "not really base64", StatusCode = 200, StatusDescription = "200 OK" }; string serializedJson; using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(response, stream); stream.Position = 0; serializedJson = Encoding.UTF8.GetString(stream.ToArray()); } JObject root = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson) as JObject; Assert.Equal("h1-value1", root["headers"]["Head1"]); Assert.Equal("h2-value1", root["headers"]["Head2"]); Assert.True((bool)root["isBase64Encoded"]); Assert.Equal("not really base64", (string)root["body"]); Assert.Equal(200, (int)root["statusCode"]); Assert.Equal("200 OK", (string)root["statusDescription"]); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ApplicationLoadBalancerMultiHeaderResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var response = new ApplicationLoadBalancerResponse() { MultiValueHeaders = new Dictionary<string, IList<string>> { {"Head1", new List<string>{"h1-value1" } }, {"Head2", new List<string>{"h2-value1", "h2-value2" } } }, IsBase64Encoded = true, Body = "not really base64", StatusCode = 200, StatusDescription = "200 OK" }; string serializedJson; using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(response, stream); stream.Position = 0; serializedJson = Encoding.UTF8.GetString(stream.ToArray()); } JObject root = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson) as JObject; Assert.Equal(1, root["multiValueHeaders"]["Head1"].Count()); Assert.Equal("h1-value1", root["multiValueHeaders"]["Head1"].First()); Assert.Equal(2, root["multiValueHeaders"]["Head2"].Count()); Assert.Equal("h2-value1", root["multiValueHeaders"]["Head2"].First()); Assert.Equal("h2-value2", root["multiValueHeaders"]["Head2"].Last()); Assert.True((bool)root["isBase64Encoded"]); Assert.Equal("not really base64", (string)root["body"]); Assert.Equal(200, (int)root["statusCode"]); Assert.Equal("200 OK", (string)root["statusDescription"]); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void LexEvent(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("lex-event.json")) { var lexEvent = serializer.Deserialize<LexEvent>(fileStream); Assert.Equal("1.0", lexEvent.MessageVersion); Assert.Equal("FulfillmentCodeHook or DialogCodeHook", lexEvent.InvocationSource); Assert.Equal("User ID specified in the POST request to Amazon Lex.", lexEvent.UserId); Assert.Equal(2, lexEvent.SessionAttributes.Count); Assert.Equal("value1", lexEvent.SessionAttributes["key1"]); Assert.Equal("value2", lexEvent.SessionAttributes["key2"]); Assert.Equal("bot name", lexEvent.Bot.Name); Assert.Equal("bot alias", lexEvent.Bot.Alias); Assert.Equal("bot version", lexEvent.Bot.Version); Assert.Equal("Text or Voice, based on ContentType request header in runtime API request", lexEvent.OutputDialogMode); Assert.Equal("intent-name", lexEvent.CurrentIntent.Name); Assert.Equal(2, lexEvent.CurrentIntent.Slots.Count); Assert.Equal("value1", lexEvent.CurrentIntent.Slots["slot name1"]); Assert.Equal("value2", lexEvent.CurrentIntent.Slots["slot name2"]); Assert.Equal("None, Confirmed, or Denied (intent confirmation, if configured)", lexEvent.CurrentIntent.ConfirmationStatus); Assert.Equal("Text used to process the request", lexEvent.InputTranscript); Assert.Null(lexEvent.CurrentIntent.NluIntentConfidenceScore); Assert.Equal(2, lexEvent.RequestAttributes.Count); Assert.Equal("value1", lexEvent.RequestAttributes["key1"]); Assert.Equal("value2", lexEvent.RequestAttributes["key2"]); Assert.Equal(2, lexEvent.CurrentIntent.SlotDetails.Count); Assert.Equal("resolved value1", lexEvent.CurrentIntent.SlotDetails["slot name1"].Resolutions[0]["value1"]); Assert.Equal("resolved value2", lexEvent.CurrentIntent.SlotDetails["slot name1"].Resolutions[1]["value2"]); Assert.Equal("original text", lexEvent.CurrentIntent.SlotDetails["slot name1"].OriginalValue); Assert.Equal("resolved value1", lexEvent.CurrentIntent.SlotDetails["slot name2"].Resolutions[0]["value1"]); Assert.Equal("resolved value2", lexEvent.CurrentIntent.SlotDetails["slot name2"].Resolutions[1]["value2"]); Assert.Equal("original text", lexEvent.CurrentIntent.SlotDetails["slot name2"].OriginalValue); Assert.Equal("intent-name", lexEvent.AlternativeIntents[0].Name); Assert.Equal(5.5, lexEvent.AlternativeIntents[0].NluIntentConfidenceScore); Assert.Equal("intent-name", lexEvent.AlternativeIntents[1].Name); Assert.Null(lexEvent.AlternativeIntents[1].NluIntentConfidenceScore); Assert.Equal("Name", lexEvent.RecentIntentSummaryView[0].IntentName); Assert.Equal("Label", lexEvent.RecentIntentSummaryView[0].CheckpointLabel); Assert.Equal("value1", lexEvent.RecentIntentSummaryView[0].Slots["key1"]); Assert.Equal("Confirmed", lexEvent.RecentIntentSummaryView[0].ConfirmationStatus); Assert.Equal("ElicitIntent", lexEvent.RecentIntentSummaryView[0].DialogActionType); Assert.Equal("Fulfilled", lexEvent.RecentIntentSummaryView[0].FulfillmentState); Assert.Equal("NextSlot", lexEvent.RecentIntentSummaryView[0].SlotToElicit); Assert.Equal("name", lexEvent.ActiveContexts[0].Name); Assert.Equal(100, lexEvent.ActiveContexts[0].TimeToLive.TimeToLiveInSeconds); Assert.Equal(5, lexEvent.ActiveContexts[0].TimeToLive.TurnsToLive); Assert.Equal("value", lexEvent.ActiveContexts[0].Parameters["key"]); Assert.Equal("sentiment", lexEvent.SentimentResponse.SentimentLabel); Assert.Equal("score", lexEvent.SentimentResponse.SentimentScore); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void LexResponse(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("lex-response.json")) { var lexResponse = serializer.Deserialize<LexResponse>(fileStream); Assert.Equal(2, lexResponse.SessionAttributes.Count); Assert.Equal("value1", lexResponse.SessionAttributes["key1"]); Assert.Equal("value2", lexResponse.SessionAttributes["key2"]); Assert.Equal("ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close", lexResponse.DialogAction.Type); Assert.Equal("Fulfilled or Failed", lexResponse.DialogAction.FulfillmentState); Assert.Equal("PlainText or SSML", lexResponse.DialogAction.Message.ContentType); Assert.Equal("message to convey to the user", lexResponse.DialogAction.Message.Content); Assert.Equal("intent-name", lexResponse.DialogAction.IntentName); Assert.Equal(3, lexResponse.DialogAction.Slots.Count); Assert.Equal("value1", lexResponse.DialogAction.Slots["slot-name1"]); Assert.Equal("value2", lexResponse.DialogAction.Slots["slot-name2"]); Assert.Equal("value3", lexResponse.DialogAction.Slots["slot-name3"]); Assert.Equal("slot-name", lexResponse.DialogAction.SlotToElicit); Assert.Equal(3, lexResponse.DialogAction.ResponseCard.Version); Assert.Equal("application/vnd.amazonaws.card.generic", lexResponse.DialogAction.ResponseCard.ContentType); Assert.Equal(1, lexResponse.DialogAction.ResponseCard.GenericAttachments.Count); Assert.Equal("card-title", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].Title); Assert.Equal("card-sub-title", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].SubTitle); Assert.Equal("URL of the image to be shown", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].ImageUrl); Assert.Equal("URL of the attachment to be associated with the card", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].AttachmentLinkUrl); Assert.Equal(1, lexResponse.DialogAction.ResponseCard.GenericAttachments[0].Buttons.Count); Assert.Equal("button-text", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].Buttons[0].Text); Assert.Equal("value sent to server on button click", lexResponse.DialogAction.ResponseCard.GenericAttachments[0].Buttons[0].Value); Assert.Equal("name", lexResponse.ActiveContexts[0].Name); Assert.Equal(100, lexResponse.ActiveContexts[0].TimeToLive.TimeToLiveInSeconds); Assert.Equal(5, lexResponse.ActiveContexts[0].TimeToLive.TurnsToLive); Assert.Equal("value", lexResponse.ActiveContexts[0].Parameters["key"]); Assert.Equal("Name", lexResponse.RecentIntentSummaryView[0].IntentName); Assert.Equal("Label", lexResponse.RecentIntentSummaryView[0].CheckpointLabel); Assert.Equal("value1", lexResponse.RecentIntentSummaryView[0].Slots["key1"]); Assert.Equal("Confirmed", lexResponse.RecentIntentSummaryView[0].ConfirmationStatus); Assert.Equal("ElicitIntent", lexResponse.RecentIntentSummaryView[0].DialogActionType); Assert.Equal("Fulfilled", lexResponse.RecentIntentSummaryView[0].FulfillmentState); Assert.Equal("NextSlot", lexResponse.RecentIntentSummaryView[0].SlotToElicit); MemoryStream ms = new MemoryStream(); serializer.Serialize<LexResponse>(lexResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("lex-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] public void LexV2Event(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("lexv2-event.json")) { var lexV2Event = serializer.Deserialize<LexV2Event>(fileStream); Assert.Equal("1.0", lexV2Event.MessageVersion); Assert.Equal("DialogCodeHook", lexV2Event.InvocationSource); Assert.Equal("DTMF", lexV2Event.InputMode); Assert.Equal("ImageResponseCard", lexV2Event.ResponseContentType); Assert.Equal("test_session", lexV2Event.SessionId); Assert.Equal("test_input_transcript", lexV2Event.InputTranscript); Assert.Equal("UFIDGBA6DE", lexV2Event.Bot.Id); Assert.Equal("testbot", lexV2Event.Bot.Name); Assert.Equal("TSTALIASID", lexV2Event.Bot.AliasId); Assert.Equal("en_US", lexV2Event.Bot.LocaleId); Assert.Equal("1.0", lexV2Event.Bot.Version); Assert.Equal(2, lexV2Event.Interpretations.Count); Assert.Equal("TestAction", lexV2Event.Interpretations[0].Intent.Name); Assert.Equal(3, lexV2Event.Interpretations[0].Intent.Slots.Count); Assert.Equal("List", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Shape); Assert.Equal("Action Value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Value.InterpretedValue); Assert.Equal(1, lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Value.ResolvedValues[0]); Assert.Equal(1, lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values.Count); Assert.Equal("Scalar", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Shape); Assert.Equal("Action Value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Value.InterpretedValue); Assert.Equal(1, lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Value.ResolvedValues[0]); Assert.Null(lexV2Event.Interpretations[0].Intent.Slots["ActionType"].Values[0].Values); Assert.Null(lexV2Event.Interpretations[0].Intent.Slots["ActionDate"]); Assert.Null(lexV2Event.Interpretations[0].Intent.Slots["ActionTime"]); Assert.Equal("InProgress", lexV2Event.Interpretations[0].Intent.State); Assert.Equal("None", lexV2Event.Interpretations[0].Intent.ConfirmationState); Assert.Equal(0.79, lexV2Event.Interpretations[0].NluConfidence); Assert.Equal("testsentiment", lexV2Event.Interpretations[0].SentimentResponse.Sentiment); Assert.Equal(0.1, lexV2Event.Interpretations[0].SentimentResponse.SentimentScore.Mixed); Assert.Equal(0.1, lexV2Event.Interpretations[0].SentimentResponse.SentimentScore.Negative); Assert.Equal(0.5, lexV2Event.Interpretations[0].SentimentResponse.SentimentScore.Neutral); Assert.Equal(0.9, lexV2Event.Interpretations[0].SentimentResponse.SentimentScore.Positive); Assert.Equal("FallbackIntent", lexV2Event.Interpretations[1].Intent.Name); Assert.Equal(0, lexV2Event.Interpretations[1].Intent.Slots.Count); Assert.Equal("ActionDate", lexV2Event.ProposedNextState.DialogAction.SlotToElicit); Assert.Equal("ConfirmIntent", lexV2Event.ProposedNextState.DialogAction.Type); Assert.Equal("NextIntent", lexV2Event.ProposedNextState.Intent.Name); Assert.Equal("None", lexV2Event.ProposedNextState.Intent.ConfirmationState); Assert.Equal(0, lexV2Event.ProposedNextState.Intent.Slots.Count); Assert.Equal("Waiting", lexV2Event.ProposedNextState.Intent.State); Assert.Equal(2, lexV2Event.RequestAttributes.Count); Assert.Equal("value1", lexV2Event.RequestAttributes["key1"]); Assert.Equal("value2", lexV2Event.RequestAttributes["key2"]); Assert.Equal(1, lexV2Event.SessionState.ActiveContexts.Count); Assert.Equal(2, lexV2Event.SessionState.ActiveContexts[0].ContextAttributes.Count); Assert.Equal("contextattributevalue1", lexV2Event.SessionState.ActiveContexts[0].ContextAttributes["contextattribute1"]); Assert.Equal("contextattributevalue2", lexV2Event.SessionState.ActiveContexts[0].ContextAttributes["contextattribute2"]); Assert.Equal("testcontext", lexV2Event.SessionState.ActiveContexts[0].Name); Assert.Equal(12, lexV2Event.SessionState.ActiveContexts[0].TimeToLive.TimeToLiveInSeconds); Assert.Equal(20, lexV2Event.SessionState.ActiveContexts[0].TimeToLive.TurnsToLive); Assert.Equal("ElicitSlot", lexV2Event.SessionState.DialogAction.Type); Assert.Equal("Date", lexV2Event.SessionState.DialogAction.SlotToElicit); Assert.Equal("TestAction", lexV2Event.SessionState.Intent.Name); Assert.Equal(3, lexV2Event.SessionState.Intent.Slots.Count); Assert.Equal("List", lexV2Event.SessionState.Intent.Slots["ActionType"].Shape); Assert.Equal("Action Value", lexV2Event.SessionState.Intent.Slots["ActionType"].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.SessionState.Intent.Slots["ActionType"].Value.InterpretedValue); Assert.Equal(1, lexV2Event.SessionState.Intent.Slots["ActionType"].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.SessionState.Intent.Slots["ActionType"].Value.ResolvedValues[0]); Assert.Equal(1, lexV2Event.SessionState.Intent.Slots["ActionType"].Values.Count); Assert.Equal("Scalar", lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Shape); Assert.Equal("Action Value", lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Value.InterpretedValue); Assert.Equal(1, lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Value.ResolvedValues[0]); Assert.Null(lexV2Event.SessionState.Intent.Slots["ActionType"].Values[0].Values); Assert.Null(lexV2Event.SessionState.Intent.Slots["ActionDate"]); Assert.Null(lexV2Event.SessionState.Intent.Slots["ActionTime"]); Assert.Equal("InProgress", lexV2Event.SessionState.Intent.State); Assert.Equal("None", lexV2Event.SessionState.Intent.ConfirmationState); Assert.Equal("85f22c97-b5d3-4a74-9e3d-95446768ecaa", lexV2Event.SessionState.OriginatingRequestId); Assert.Equal(1, lexV2Event.SessionState.RuntimeHints.SlotHints.Count); Assert.Equal(1, lexV2Event.SessionState.RuntimeHints.SlotHints["hint1"].Count); Assert.Equal(2, lexV2Event.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues.Count); Assert.Equal("hintvalue1_1", lexV2Event.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues[0].Phrase); Assert.Equal("hintvalue1_2", lexV2Event.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues[1].Phrase); Assert.Equal(2, lexV2Event.SessionState.SessionAttributes.Count); Assert.Equal("sessionvalue1", lexV2Event.SessionState.SessionAttributes["sessionattribute1"]); Assert.Equal("sessionvalue2", lexV2Event.SessionState.SessionAttributes["sessionattribute2"]); Assert.Equal(1, lexV2Event.Transcriptions.Count); Assert.Equal("testtranscription", lexV2Event.Transcriptions[0].Transcription); Assert.Equal(0.8, lexV2Event.Transcriptions[0].TranscriptionConfidence); Assert.Equal("TestAction", lexV2Event.Transcriptions[0].ResolvedContext.Intent); Assert.Equal(1, lexV2Event.Transcriptions[0].ResolvedSlots.Count); Assert.Equal("List", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Shape); Assert.Equal("Action Value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Value.InterpretedValue); Assert.Equal(1, lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Value.ResolvedValues[0]); Assert.Equal(1, lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values.Count); Assert.Equal("Scalar", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Shape); Assert.Equal("Action Value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Value.OriginalValue); Assert.Equal("Action Value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Value.InterpretedValue); Assert.Equal(1, lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Value.ResolvedValues[0]); Assert.Null(lexV2Event.Transcriptions[0].ResolvedSlots["ActionType"].Values[0].Values); } } [Theory] [InlineData(typeof(JsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] public void LexV2Response(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("lexv2-response.json")) { var lexV2Response = serializer.Deserialize<LexV2Response>(fileStream); Assert.Equal(1, lexV2Response.Messages.Count); Assert.Equal("Test Content", lexV2Response.Messages[0].Content); Assert.Equal("ImageResponseCard", lexV2Response.Messages[0].ContentType); Assert.Equal(1, lexV2Response.Messages[0].ImageResponseCard.Buttons.Count); Assert.Equal("Take Action", lexV2Response.Messages[0].ImageResponseCard.Buttons[0].Text); Assert.Equal("takeaction", lexV2Response.Messages[0].ImageResponseCard.Buttons[0].Value); Assert.Equal("http://somedomain.com/testimage.png", lexV2Response.Messages[0].ImageResponseCard.ImageUrl); Assert.Equal("Click button to take action", lexV2Response.Messages[0].ImageResponseCard.Subtitle); Assert.Equal("Take Action", lexV2Response.Messages[0].ImageResponseCard.Title); Assert.Equal(1, lexV2Response.SessionState.ActiveContexts.Count); Assert.Equal(2, lexV2Response.SessionState.ActiveContexts[0].ContextAttributes.Count); Assert.Equal("contextattributevalue1", lexV2Response.SessionState.ActiveContexts[0].ContextAttributes["contextattribute1"]); Assert.Equal("contextattributevalue2", lexV2Response.SessionState.ActiveContexts[0].ContextAttributes["contextattribute2"]); Assert.Equal("testcontext", lexV2Response.SessionState.ActiveContexts[0].Name); Assert.Equal(12, lexV2Response.SessionState.ActiveContexts[0].TimeToLive.TimeToLiveInSeconds); Assert.Equal(20, lexV2Response.SessionState.ActiveContexts[0].TimeToLive.TurnsToLive); Assert.Equal("ElicitSlot", lexV2Response.SessionState.DialogAction.Type); Assert.Equal("Date", lexV2Response.SessionState.DialogAction.SlotToElicit); Assert.Equal("TestAction", lexV2Response.SessionState.Intent.Name); Assert.Equal(3, lexV2Response.SessionState.Intent.Slots.Count); Assert.Equal("List", lexV2Response.SessionState.Intent.Slots["ActionType"].Shape); Assert.Equal("Action Value", lexV2Response.SessionState.Intent.Slots["ActionType"].Value.OriginalValue); Assert.Equal("Action Value", lexV2Response.SessionState.Intent.Slots["ActionType"].Value.InterpretedValue); Assert.Equal(1, lexV2Response.SessionState.Intent.Slots["ActionType"].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Response.SessionState.Intent.Slots["ActionType"].Value.ResolvedValues[0]); Assert.Equal(1, lexV2Response.SessionState.Intent.Slots["ActionType"].Values.Count); Assert.Equal("Scalar", lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Shape); Assert.Equal("Action Value", lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Value.OriginalValue); Assert.Equal("Action Value", lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Value.InterpretedValue); Assert.Equal(1, lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Value.ResolvedValues.Count); Assert.Equal("action value", lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Value.ResolvedValues[0]); Assert.Null(lexV2Response.SessionState.Intent.Slots["ActionType"].Values[0].Values); Assert.Null(lexV2Response.SessionState.Intent.Slots["ActionDate"]); Assert.Null(lexV2Response.SessionState.Intent.Slots["ActionTime"]); Assert.Equal("InProgress", lexV2Response.SessionState.Intent.State); Assert.Equal("None", lexV2Response.SessionState.Intent.ConfirmationState); Assert.Equal("85f22c97-b5d3-4a74-9e3d-95446768ecaa", lexV2Response.SessionState.OriginatingRequestId); Assert.Equal(1, lexV2Response.SessionState.RuntimeHints.SlotHints.Count); Assert.Equal(1, lexV2Response.SessionState.RuntimeHints.SlotHints["hint1"].Count); Assert.Equal(2, lexV2Response.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues.Count); Assert.Equal("hintvalue1_1", lexV2Response.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues[0].Phrase); Assert.Equal("hintvalue1_2", lexV2Response.SessionState.RuntimeHints.SlotHints["hint1"]["detail1"].RuntimeHintValues[1].Phrase); Assert.Equal(2, lexV2Response.SessionState.SessionAttributes.Count); Assert.Equal("sessionvalue1", lexV2Response.SessionState.SessionAttributes["sessionattribute1"]); Assert.Equal("sessionvalue2", lexV2Response.SessionState.SessionAttributes["sessionattribute2"]); Assert.Equal(2, lexV2Response.RequestAttributes.Count); Assert.Equal("value1", lexV2Response.RequestAttributes["key1"]); Assert.Equal("value2", lexV2Response.RequestAttributes["key2"]); MemoryStream ms = new MemoryStream(); serializer.Serialize<LexV2Response>(lexV2Response, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("lexv2-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisFirehoseEvent(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-firehose-event.json")) { var kinesisEvent = serializer.Deserialize<KinesisFirehoseEvent>(fileStream); Assert.Equal("00540a87-5050-496a-84e4-e7d92bbaf5e2", kinesisEvent.InvocationId); Assert.Equal("arn:aws:firehose:us-east-1:AAAAAAAAAAAA:deliverystream/lambda-test", kinesisEvent.DeliveryStreamArn); Assert.Equal("us-east-1", kinesisEvent.Region); Assert.Equal(1, kinesisEvent.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisEvent.Records[0].RecordId); Assert.Equal("aGVsbG8gd29ybGQ=", kinesisEvent.Records[0].Base64EncodedData); Assert.Equal(1493276938812, kinesisEvent.Records[0].ApproximateArrivalEpoch); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisFirehoseResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-firehose-response.json")) { var kinesisResponse = serializer.Deserialize<KinesisFirehoseResponse>(fileStream); Assert.Equal(1, kinesisResponse.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisResponse.Records[0].RecordId); Assert.Equal(KinesisFirehoseResponse.TRANSFORMED_STATE_OK, kinesisResponse.Records[0].Result); Assert.Equal("SEVMTE8gV09STEQ=", kinesisResponse.Records[0].Base64EncodedData); Assert.Equal("iamValue1", kinesisResponse.Records[0].Metadata.PartitionKeys["iamKey1"]); Assert.Equal("iamValue2", kinesisResponse.Records[0].Metadata.PartitionKeys["iamKey2"]); MemoryStream ms = new MemoryStream(); serializer.Serialize<KinesisFirehoseResponse>(kinesisResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("kinesis-firehose-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsOutputDeliveryEvent(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-outputdelivery-event.json")) { var kinesisAnalyticsEvent = serializer.Deserialize<KinesisAnalyticsOutputDeliveryEvent>(fileStream); Assert.Equal("00540a87-5050-496a-84e4-e7d92bbaf5e2", kinesisAnalyticsEvent.InvocationId); Assert.Equal("arn:aws:kinesisanalytics:us-east-1:12345678911:application/lambda-test", kinesisAnalyticsEvent.ApplicationArn); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsEvent.Records[0].RecordId); Assert.Equal("aGVsbG8gd29ybGQ=", kinesisAnalyticsEvent.Records[0].Base64EncodedData); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsOutputDeliveryResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-outputdelivery-response.json")) { var kinesisAnalyticsResponse = serializer.Deserialize<KinesisAnalyticsOutputDeliveryResponse>(fileStream); Assert.Equal(1, kinesisAnalyticsResponse.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsResponse.Records[0].RecordId); Assert.Equal(KinesisAnalyticsOutputDeliveryResponse.OK, kinesisAnalyticsResponse.Records[0].Result); MemoryStream ms = new MemoryStream(); serializer.Serialize<KinesisAnalyticsOutputDeliveryResponse>(kinesisAnalyticsResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("kinesis-analytics-outputdelivery-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsInputProcessingEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-inputpreprocessing-event.json")) { var kinesisAnalyticsEvent = serializer.Deserialize<KinesisAnalyticsStreamsInputPreprocessingEvent>(fileStream); Assert.Equal("00540a87-5050-496a-84e4-e7d92bbaf5e2", kinesisAnalyticsEvent.InvocationId); Assert.Equal("arn:aws:kinesis:us-east-1:AAAAAAAAAAAA:stream/lambda-test", kinesisAnalyticsEvent.StreamArn); Assert.Equal("arn:aws:kinesisanalytics:us-east-1:12345678911:application/lambda-test", kinesisAnalyticsEvent.ApplicationArn); Assert.Equal(1, kinesisAnalyticsEvent.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsEvent.Records[0].RecordId); Assert.Equal("aGVsbG8gd29ybGQ=", kinesisAnalyticsEvent.Records[0].Base64EncodedData); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsInputProcessingResponseTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-inputpreprocessing-response.json")) { var kinesisAnalyticsResponse = serializer.Deserialize<KinesisAnalyticsInputPreprocessingResponse>(fileStream); Assert.Equal(1, kinesisAnalyticsResponse.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsResponse.Records[0].RecordId); Assert.Equal(KinesisAnalyticsInputPreprocessingResponse.OK, kinesisAnalyticsResponse.Records[0].Result); Assert.Equal("SEVMTE8gV09STEQ=", kinesisAnalyticsResponse.Records[0].Base64EncodedData); MemoryStream ms = new MemoryStream(); serializer.Serialize<KinesisAnalyticsInputPreprocessingResponse>(kinesisAnalyticsResponse, ms); ms.Position = 0; var json = new StreamReader(ms).ReadToEnd(); var original = JObject.Parse(File.ReadAllText("kinesis-analytics-inputpreprocessing-response.json")); var serialized = JObject.Parse(json); Assert.True(JToken.DeepEquals(serialized, original), "Serialized object is not the same as the original JSON"); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsStreamsInputProcessingEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-streamsinputpreprocessing-event.json")) { var kinesisAnalyticsEvent = serializer.Deserialize<KinesisAnalyticsStreamsInputPreprocessingEvent>(fileStream); Assert.Equal("00540a87-5050-496a-84e4-e7d92bbaf5e2", kinesisAnalyticsEvent.InvocationId); Assert.Equal("arn:aws:kinesis:us-east-1:AAAAAAAAAAAA:stream/lambda-test", kinesisAnalyticsEvent.StreamArn); Assert.Equal("arn:aws:kinesisanalytics:us-east-1:12345678911:application/lambda-test", kinesisAnalyticsEvent.ApplicationArn); Assert.Equal(1, kinesisAnalyticsEvent.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsEvent.Records[0].RecordId); Assert.Equal("aGVsbG8gd29ybGQ=", kinesisAnalyticsEvent.Records[0].Base64EncodedData); Assert.NotNull(kinesisAnalyticsEvent.Records[0].RecordMetadata); Assert.Equal("shardId-000000000003", kinesisAnalyticsEvent.Records[0].RecordMetadata.ShardId); Assert.Equal("7400791606", kinesisAnalyticsEvent.Records[0].RecordMetadata.PartitionKey); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsEvent.Records[0].RecordMetadata.SequenceNumber); Assert.Equal(1520280173, kinesisAnalyticsEvent.Records[0].RecordMetadata.ApproximateArrivalEpoch); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KinesisAnalyticsFirehoseInputProcessingEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kinesis-analytics-firehoseinputpreprocessing-event.json")) { var kinesisAnalyticsEvent = serializer.Deserialize<KinesisAnalyticsFirehoseInputPreprocessingEvent>(fileStream); Assert.Equal("00540a87-5050-496a-84e4-e7d92bbaf5e2", kinesisAnalyticsEvent.InvocationId); Assert.Equal("arn:aws:firehose:us-east-1:AAAAAAAAAAAA:deliverystream/lambda-test", kinesisAnalyticsEvent.StreamArn); Assert.Equal("arn:aws:kinesisanalytics:us-east-1:12345678911:application/lambda-test", kinesisAnalyticsEvent.ApplicationArn); Assert.Equal(1, kinesisAnalyticsEvent.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisAnalyticsEvent.Records[0].RecordId); Assert.Equal("aGVsbG8gd29ybGQ=", kinesisAnalyticsEvent.Records[0].Base64EncodedData); Assert.NotNull(kinesisAnalyticsEvent.Records[0].RecordMetadata); Assert.Equal(1520280173, kinesisAnalyticsEvent.Records[0].RecordMetadata.ApproximateArrivalEpoch); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchLogEvent(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("logs-event.json")) { var evnt = serializer.Deserialize<CloudWatchLogsEvent>(fileStream); Assert.NotNull(evnt.Awslogs); var data = evnt.Awslogs.DecodeData(); Assert.NotNull(data); var jobject = JsonConvert.DeserializeObject(data) as JObject; Assert.Equal("DATA_MESSAGE", jobject["messageType"].ToString()); } } private string MemoryStreamToBase64String(MemoryStream ms) { var data = ms.ToArray(); return Convert.ToBase64String(data); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void BatchJobStateChangeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("batch-job-state-change-event.json")) { var jobStateChangeEvent = serializer.Deserialize<BatchJobStateChangeEvent>(fileStream); Assert.Equal(jobStateChangeEvent.Version, "0"); Assert.Equal(jobStateChangeEvent.Id, "c8f9c4b5-76e5-d76a-f980-7011e206042b"); Assert.Equal(jobStateChangeEvent.DetailType, "Batch Job State Change"); Assert.Equal(jobStateChangeEvent.Source, "aws.batch"); Assert.Equal(jobStateChangeEvent.Account, "aws_account_id"); Assert.Equal(jobStateChangeEvent.Time.ToUniversalTime(), DateTime.Parse("2017-10-23T17:56:03Z").ToUniversalTime()); Assert.Equal(jobStateChangeEvent.Region, "us-east-1"); Assert.Equal(jobStateChangeEvent.Resources.Count, 1); Assert.Equal(jobStateChangeEvent.Resources[0], "arn:aws:batch:us-east-1:aws_account_id:job/4c7599ae-0a82-49aa-ba5a-4727fcce14a8"); Assert.IsType(typeof(Job), jobStateChangeEvent.Detail); Assert.Equal(jobStateChangeEvent.Detail.JobName, "event-test"); Assert.Equal(jobStateChangeEvent.Detail.JobId, "4c7599ae-0a82-49aa-ba5a-4727fcce14a8"); Assert.Equal(jobStateChangeEvent.Detail.JobQueue, "arn:aws:batch:us-east-1:aws_account_id:job-queue/HighPriority"); Assert.Equal(jobStateChangeEvent.Detail.Status, "RUNNABLE"); Assert.Equal(jobStateChangeEvent.Detail.Attempts.Count, 0); Assert.Equal(jobStateChangeEvent.Detail.CreatedAt, 1508781340401); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.Attempts, 1); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].Action, "EXIT"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnExitCode, "*"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnReason, "*"); Assert.Equal(jobStateChangeEvent.Detail.RetryStrategy.EvaluateOnExit[0].OnStatusReason, "*"); Assert.Equal(jobStateChangeEvent.Detail.DependsOn.Count, 0); Assert.Equal(jobStateChangeEvent.Detail.JobDefinition, "arn:aws:batch:us-east-1:aws_account_id:job-definition/first-run-job-definition:1"); Assert.Equal(jobStateChangeEvent.Detail.Parameters.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Parameters["test"], "abc"); Assert.Equal(jobStateChangeEvent.Detail.Container.Image, "busybox"); Assert.NotNull(jobStateChangeEvent.Detail.Container.ResourceRequirements); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[0].Type, "MEMORY"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[0].Value, "2000"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[1].Type, "VCPU"); Assert.Equal(jobStateChangeEvent.Detail.Container.ResourceRequirements[1].Value, "2"); Assert.Equal(jobStateChangeEvent.Detail.Container.Vcpus, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Memory, 2000); Assert.Equal(jobStateChangeEvent.Detail.Container.Command.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Command[0], "echo"); Assert.Equal(jobStateChangeEvent.Detail.Container.Command[1], "'hello world'"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[0].Name, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[0].Host.SourcePath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].Name, "efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.AccessPointId, "fsap-XXXXXXXXXXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.Iam, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.FileSystemId, "fs-XXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.RootDirectory, "/"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.TransitEncryption, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.Container.Volumes[1].EfsVolumeConfiguration.TransitEncryptionPort, 12345); Assert.NotNull(jobStateChangeEvent.Detail.Container.Environment); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment[0].Name, "MANAGED_BY_AWS"); Assert.Equal(jobStateChangeEvent.Detail.Container.Environment[0].Value, "STARTED_BY_STEP_FUNCTIONS"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].ContainerPath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].ReadOnly, true); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[0].SourceVolume, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[1].ContainerPath, "/mount/efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.MountPoints[1].SourceVolume, "efs"); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].HardLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].Name, "nofile"); Assert.Equal(jobStateChangeEvent.Detail.Container.Ulimits[0].SoftLimit, 2048); Assert.NotNull(jobStateChangeEvent.Detail.Container.LinuxParameters); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].ContainerPath, "/dev/sda"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].HostPath, "/dev/xvdc"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].Permissions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Devices[0].Permissions[0], "MKNOD"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.InitProcessEnabled, true); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.SharedMemorySize, 64); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.MaxSwap, 1024); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Swappiness, 55); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].ContainerPath, "/run"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].Size, 65536); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions[0], "noexec"); Assert.Equal(jobStateChangeEvent.Detail.Container.LinuxParameters.Tmpfs[0].MountOptions[1], "nosuid"); Assert.NotNull(jobStateChangeEvent.Detail.Container.LogConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.LogDriver, "json-file"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options["max-size"], "10m"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.Options["max-file"], "3"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions[0].Name, "apikey"); Assert.Equal(jobStateChangeEvent.Detail.Container.LogConfiguration.SecretOptions[0].ValueFrom, "ddApiKey"); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets[0].Name, "DATABASE_PASSWORD"); Assert.Equal(jobStateChangeEvent.Detail.Container.Secrets[0].ValueFrom, "arn:aws:ssm:us-east-1:awsExampleAccountID:parameter/awsExampleParameter"); Assert.NotNull(jobStateChangeEvent.Detail.Container.NetworkConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.NetworkConfiguration.AssignPublicIp, "ENABLED"); Assert.NotNull(jobStateChangeEvent.Detail.Container.FargatePlatformConfiguration); Assert.Equal(jobStateChangeEvent.Detail.Container.FargatePlatformConfiguration.PlatformVersion, "LATEST"); Assert.NotNull(jobStateChangeEvent.Detail.NodeProperties); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.MainNode, 0); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NumNodes, 0); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].TargetNodes, "0:1"); Assert.NotNull(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Image, "busybox"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[0].Type, "MEMORY"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[0].Value, "2000"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[1].Type, "VCPU"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ResourceRequirements[1].Value, "2"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Vcpus, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Memory, 2000); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command[0], "echo"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Command[1], "'hello world'"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[0].Name, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[0].Host.SourcePath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].Name, "efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.AccessPointId, "fsap-XXXXXXXXXXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.AuthorizationConfig.Iam, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.FileSystemId, "fs-XXXXXXXXX"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.RootDirectory, "/"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.TransitEncryption, "ENABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Volumes[1].EfsVolumeConfiguration.TransitEncryptionPort, 12345); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment[0].Name, "MANAGED_BY_AWS"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Environment[0].Value, "STARTED_BY_STEP_FUNCTIONS"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].ContainerPath, "/data"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].ReadOnly, true); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[0].SourceVolume, "myhostsource"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[1].ContainerPath, "/mount/efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.MountPoints[1].SourceVolume, "efs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].HardLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].Name, "nofile"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Ulimits[0].SoftLimit, 2048); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.ExecutionRoleArn, "arn:aws:iam::awsExampleAccountID:role/awsExampleRoleName"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.InstanceType, "p3.2xlarge"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.User, "testuser"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.JobRoleArn, "arn:aws:iam::awsExampleAccountID:role/awsExampleRoleName"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].HostPath, "/dev/xvdc"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].ContainerPath, "/dev/sda"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].Permissions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Devices[0].Permissions[0], "MKNOD"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.InitProcessEnabled, true); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.SharedMemorySize, 64); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.MaxSwap, 1024); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Swappiness, 55); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].ContainerPath, "/run"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].Size, 65536); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions.Count, 2); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions[0], "noexec"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LinuxParameters.Tmpfs[0].MountOptions[1], "nosuid"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.LogDriver, "awslogs"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.Options["awslogs-group"], "awslogs-wordpress"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.Options["awslogs-stream-prefix"], "awslogs-example"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions[0].Name, "apikey"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.LogConfiguration.SecretOptions[0].ValueFrom, "ddApiKey"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets[0].Name, "DATABASE_PASSWORD"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.Secrets[0].ValueFrom, "arn:aws:ssm:us-east-1:awsExampleAccountID:parameter/awsExampleParameter"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.NetworkConfiguration.AssignPublicIp, "DISABLED"); Assert.Equal(jobStateChangeEvent.Detail.NodeProperties.NodeRangeProperties[0].Container.FargatePlatformConfiguration.PlatformVersion, "LATEST"); Assert.Equal(jobStateChangeEvent.Detail.PropagateTags, true); Assert.Equal(jobStateChangeEvent.Detail.Timeout.AttemptDurationSeconds, 90); Assert.Equal(jobStateChangeEvent.Detail.Tags.Count, 3); Assert.Equal(jobStateChangeEvent.Detail.Tags["Service"], "Batch"); Assert.Equal(jobStateChangeEvent.Detail.Tags["Name"], "JobDefinitionTag"); Assert.Equal(jobStateChangeEvent.Detail.Tags["Expected"], "MergeTag"); Assert.Equal(jobStateChangeEvent.Detail.PlatformCapabilities.Count, 1); Assert.Equal(jobStateChangeEvent.Detail.PlatformCapabilities[0], "FARGATE"); Handle(jobStateChangeEvent); } } private void Handle(BatchJobStateChangeEvent jobStateChangeEvent) { Console.WriteLine($"[{jobStateChangeEvent.Source} {jobStateChangeEvent.Time}] {jobStateChangeEvent.DetailType}"); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ScheduledEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("scheduled-event.json")) { var scheduledEvent = serializer.Deserialize<ScheduledEvent>(fileStream); Assert.Equal(scheduledEvent.Version, "0"); Assert.Equal(scheduledEvent.Id, "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c"); Assert.Equal(scheduledEvent.DetailType, "Scheduled Event"); Assert.Equal(scheduledEvent.Source, "aws.events"); Assert.Equal(scheduledEvent.Account, "123456789012"); Assert.Equal(scheduledEvent.Time.ToUniversalTime(), DateTime.Parse("1970-01-01T00:00:00Z").ToUniversalTime()); Assert.Equal(scheduledEvent.Region, "us-east-1"); Assert.Equal(scheduledEvent.Resources.Count, 1); Assert.Equal(scheduledEvent.Resources[0], "arn:aws:events:us-east-1:123456789012:rule/my-schedule"); Assert.IsType(typeof(Detail), scheduledEvent.Detail); Handle(scheduledEvent); } } private void Handle(ScheduledEvent scheduledEvent) { Console.WriteLine($"[{scheduledEvent.Source} {scheduledEvent.Time}] {scheduledEvent.DetailType}"); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ECSContainerInstanceStateChangeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("ecs-container-state-change-event.json")) { var ecsEvent = serializer.Deserialize<ECSContainerInstanceStateChangeEvent>(fileStream); Assert.Equal(ecsEvent.Version, "0"); Assert.Equal(ecsEvent.Id, "8952ba83-7be2-4ab5-9c32-6687532d15a2"); Assert.Equal(ecsEvent.DetailType, "ECS Container Instance State Change"); Assert.Equal(ecsEvent.Source, "aws.ecs"); Assert.Equal(ecsEvent.Account, "111122223333"); Assert.Equal(ecsEvent.Time.ToUniversalTime(), DateTime.Parse("2016-12-06T16:41:06Z").ToUniversalTime()); Assert.Equal(ecsEvent.Region, "us-east-1"); Assert.Equal(ecsEvent.Resources.Count, 1); Assert.Equal(ecsEvent.Resources[0], "arn:aws:ecs:us-east-1:111122223333:container-instance/b54a2a04-046f-4331-9d74-3f6d7f6ca315"); Assert.IsType(typeof(ContainerInstance), ecsEvent.Detail); Assert.Equal(ecsEvent.Detail.AgentConnected, true); Assert.Equal(ecsEvent.Detail.Attributes.Count, 14); Assert.Equal(ecsEvent.Detail.Attributes[0].Name, "com.amazonaws.ecs.capability.logging-driver.syslog"); Assert.Equal(ecsEvent.Detail.ClusterArn, "arn:aws:ecs:us-east-1:111122223333:cluster/default"); Assert.Equal(ecsEvent.Detail.ContainerInstanceArn, "arn:aws:ecs:us-east-1:111122223333:container-instance/b54a2a04-046f-4331-9d74-3f6d7f6ca315"); Assert.Equal(ecsEvent.Detail.Ec2InstanceId, "i-f3a8506b"); Assert.Equal(ecsEvent.Detail.RegisteredResources.Count, 4); Assert.Equal(ecsEvent.Detail.RegisteredResources[0].Name, "CPU"); Assert.Equal(ecsEvent.Detail.RegisteredResources[0].Type, "INTEGER"); Assert.Equal(ecsEvent.Detail.RegisteredResources[0].IntegerValue, 2048); Assert.Equal(ecsEvent.Detail.RegisteredResources[2].StringSetValue[0], "22"); Assert.Equal(ecsEvent.Detail.RemainingResources.Count, 4); Assert.Equal(ecsEvent.Detail.RemainingResources[0].Name, "CPU"); Assert.Equal(ecsEvent.Detail.RemainingResources[0].Type, "INTEGER"); Assert.Equal(ecsEvent.Detail.RemainingResources[0].IntegerValue, 1988); Assert.Equal(ecsEvent.Detail.RemainingResources[2].StringSetValue[0], "22"); Assert.Equal(ecsEvent.Detail.Status, "ACTIVE"); Assert.Equal(ecsEvent.Detail.Version, 14801); Assert.Equal(ecsEvent.Detail.VersionInfo.AgentHash, "aebcbca"); Assert.Equal(ecsEvent.Detail.VersionInfo.AgentVersion, "1.13.0"); Assert.Equal(ecsEvent.Detail.VersionInfo.DockerVersion, "DockerVersion: 1.11.2"); Assert.Equal(ecsEvent.Detail.UpdatedAt.ToUniversalTime(), DateTime.Parse("2016-12-06T16:41:06.991Z").ToUniversalTime()); Handle(ecsEvent); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ECSTaskStateChangeEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("ecs-task-state-change-event.json")) { var ecsEvent = serializer.Deserialize<ECSTaskStateChangeEvent>(fileStream); Assert.Equal(ecsEvent.Version, "0"); Assert.Equal(ecsEvent.Id, "3317b2af-7005-947d-b652-f55e762e571a"); Assert.Equal(ecsEvent.DetailType, "ECS Task State Change"); Assert.Equal(ecsEvent.Source, "aws.ecs"); Assert.Equal(ecsEvent.Account, "111122223333"); Assert.Equal(ecsEvent.Time.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:58Z").ToUniversalTime()); Assert.Equal(ecsEvent.Region, "us-west-2"); Assert.NotNull(ecsEvent.Resources); Assert.Equal(ecsEvent.Resources.Count, 1); Assert.Equal(ecsEvent.Resources[0], "arn:aws:ecs:us-west-2:111122223333:task/FargateCluster/c13b4cb40f1f4fe4a2971f76ae5a47ad"); Assert.NotNull(ecsEvent.Detail); Assert.IsType(typeof(Task), ecsEvent.Detail); Assert.NotNull(ecsEvent.Detail.Attachments); Assert.Equal(ecsEvent.Detail.Attachments.Count, 1); Assert.Equal(ecsEvent.Detail.Attachments[0].Id, "1789bcae-ddfb-4d10-8ebe-8ac87ddba5b8"); Assert.Equal(ecsEvent.Detail.Attachments[0].Type, "eni"); Assert.Equal(ecsEvent.Detail.Attachments[0].Status, "ATTACHED"); Assert.NotNull(ecsEvent.Detail.Attachments[0].Details); Assert.Equal(ecsEvent.Detail.Attachments[0].Details.Count, 4); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[0].Name, "subnetId"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[0].Value, "subnet-abcd1234"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[1].Name, "networkInterfaceId"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[1].Value, "eni-abcd1234"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[2].Name, "macAddress"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[2].Value, "0a:98:eb:a7:29:ba"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[3].Name, "privateIPv4Address"); Assert.Equal(ecsEvent.Detail.Attachments[0].Details[3].Value, "10.0.0.139"); Assert.Equal(ecsEvent.Detail.AvailabilityZone, "us-west-2c"); Assert.Equal(ecsEvent.Detail.ClusterArn, "arn:aws:ecs:us-west-2:111122223333:cluster/FargateCluster"); Assert.NotNull(ecsEvent.Detail.Containers); Assert.Equal(ecsEvent.Detail.Containers.Count, 1); Assert.Equal(ecsEvent.Detail.Containers[0].ContainerArn, "arn:aws:ecs:us-west-2:111122223333:container/cf159fd6-3e3f-4a9e-84f9-66cbe726af01"); Assert.Equal(ecsEvent.Detail.Containers[0].ExitCode, 0); Assert.Equal(ecsEvent.Detail.Containers[0].LastStatus, "RUNNING"); Assert.Equal(ecsEvent.Detail.Containers[0].Name, "FargateApp"); Assert.Equal(ecsEvent.Detail.Containers[0].Image, "111122223333.dkr.ecr.us-west-2.amazonaws.com/hello-repository:latest"); Assert.Equal(ecsEvent.Detail.Containers[0].ImageDigest, "sha256:74b2c688c700ec95a93e478cdb959737c148df3fbf5ea706abe0318726e885e6"); Assert.Equal(ecsEvent.Detail.Containers[0].RuntimeId, "ad64cbc71c7fb31c55507ec24c9f77947132b03d48d9961115cf24f3b7307e1e"); Assert.Equal(ecsEvent.Detail.Containers[0].TaskArn, "arn:aws:ecs:us-west-2:111122223333:task/FargateCluster/c13b4cb40f1f4fe4a2971f76ae5a47ad"); Assert.NotNull(ecsEvent.Detail.Containers[0].NetworkInterfaces); Assert.Equal(ecsEvent.Detail.Containers[0].NetworkInterfaces.Count, 1); Assert.Equal(ecsEvent.Detail.Containers[0].NetworkInterfaces[0].AttachmentId, "1789bcae-ddfb-4d10-8ebe-8ac87ddba5b8"); Assert.Equal(ecsEvent.Detail.Containers[0].NetworkInterfaces[0].PrivateIpv4Address, "10.0.0.139"); Assert.Equal(ecsEvent.Detail.Containers[0].Cpu, "0"); Assert.Equal(ecsEvent.Detail.CreatedAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:34.402Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.LaunchType, "FARGATE"); Assert.Equal(ecsEvent.Detail.Cpu, "256"); Assert.Equal(ecsEvent.Detail.Memory, "512"); Assert.Equal(ecsEvent.Detail.DesiredStatus, "RUNNING"); Assert.Equal(ecsEvent.Detail.Group, "family:sample-fargate"); Assert.Equal(ecsEvent.Detail.LastStatus, "RUNNING"); Assert.Equal(ecsEvent.Detail.Overrides.ContainerOverrides.Count, 1); Assert.Equal(ecsEvent.Detail.Overrides.ContainerOverrides[0].Name, "FargateApp"); Assert.Equal(ecsEvent.Detail.Overrides.ContainerOverrides[0].Environment.Count, 1); Assert.Equal(ecsEvent.Detail.Overrides.ContainerOverrides[0].Environment[0].Name, "testname"); Assert.Equal(ecsEvent.Detail.Overrides.ContainerOverrides[0].Environment[0].Value, "testvalue"); Assert.Equal(ecsEvent.Detail.Connectivity, "CONNECTED"); Assert.Equal(ecsEvent.Detail.ConnectivityAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:38.453Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.PullStartedAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:52.103Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.StartedAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:58.103Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.PullStoppedAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:55.103Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.UpdatedAt.ToUniversalTime(), DateTime.Parse("2020-01-23T17:57:58.103Z").ToUniversalTime()); Assert.Equal(ecsEvent.Detail.TaskArn, "arn:aws:ecs:us-west-2:111122223333:task/FargateCluster/c13b4cb40f1f4fe4a2971f76ae5a47ad"); Assert.Equal(ecsEvent.Detail.TaskDefinitionArn, "arn:aws:ecs:us-west-2:111122223333:task-definition/sample-fargate:1"); Assert.Equal(ecsEvent.Detail.Version, 4); Assert.Equal(ecsEvent.Detail.PlatformVersion, "1.3.0"); Handle(ecsEvent); } } private void Handle(ECSContainerInstanceStateChangeEvent ecsEvent) { Console.WriteLine($"[{ecsEvent.Source} {ecsEvent.Time}] {ecsEvent.DetailType}"); } private void Handle(ECSTaskStateChangeEvent ecsEvent) { Console.WriteLine($"[{ecsEvent.Source} {ecsEvent.Time}] {ecsEvent.DetailType}"); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void KafkaEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("kafka-event.json")) { var kafkaEvent = serializer.Deserialize<KafkaEvent>(fileStream); Assert.NotNull(kafkaEvent); Assert.Equal(kafkaEvent.EventSource, "aws:kafka"); Assert.Equal(kafkaEvent.EventSourceArn, "arn:aws:kafka:us-east-1:123456789012:cluster/vpc-3432434/4834-3547-3455-9872-7929"); Assert.Equal(kafkaEvent.BootstrapServers, "b-2.demo-cluster-1.a1bcde.c1.kafka.us-east-1.amazonaws.com:9092,b-1.demo-cluster-1.a1bcde.c1.kafka.us-east-1.amazonaws.com:9092"); Assert.NotNull(kafkaEvent.Records); Assert.Equal(kafkaEvent.Records.Count, 1); var record = kafkaEvent.Records.FirstOrDefault(); Assert.NotNull(record); Assert.Equal(record.Key, "mytopic-0"); Assert.Equal(record.Value.Count, 1); var eventRecord = record.Value.FirstOrDefault(); Assert.Equal(eventRecord.Topic, "mytopic"); Assert.Equal(eventRecord.Partition, 12); Assert.Equal(eventRecord.Offset, 3043205); Assert.Equal(eventRecord.Timestamp, 1545084650987); Assert.Equal(eventRecord.TimestampType, "CREATE_TIME"); Assert.Equal(new StreamReader(eventRecord.Value).ReadToEnd(), "Hello, this is a test."); Assert.Equal(eventRecord.Headers.Count, 8); var eventRecordHeader = eventRecord.Headers.FirstOrDefault(); Assert.NotNull(eventRecordHeader); Assert.Equal(eventRecordHeader.Count, 1); var eventRecordHeaderValue = eventRecordHeader.FirstOrDefault(); Assert.NotNull(eventRecordHeaderValue); Assert.Equal(eventRecordHeaderValue.Key, "headerKey"); // Convert sbyte[] to byte[] array. var tempHeaderValueByteArray = new byte[eventRecordHeaderValue.Value.Length]; Buffer.BlockCopy(eventRecordHeaderValue.Value, 0, tempHeaderValueByteArray, 0, tempHeaderValueByteArray.Length); Assert.Equal(Encoding.UTF8.GetString(tempHeaderValueByteArray), "headerValue"); Handle(kafkaEvent); } } private void Handle(KafkaEvent kafkaEvent) { foreach (var record in kafkaEvent.Records) { foreach (var eventRecord in record.Value) { var valueBytes = eventRecord.Value.ToArray(); var valueText = Encoding.UTF8.GetString(valueBytes); Console.WriteLine($"[{record.Key}] Value = '{valueText}'."); } } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void ActiveMQEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("amazonmq-activemq.json")) { var activemqEvent = serializer.Deserialize<ActiveMQEvent>(fileStream); Assert.NotNull(activemqEvent); Assert.Equal("aws:amq", activemqEvent.EventSource); Assert.Equal("arn:aws:mq:us-west-2:112556298976:broker:test:b-9bcfa592-423a-4942-879d-eb284b418fc8", activemqEvent.EventSourceArn); Assert.Equal(2, activemqEvent.Messages.Count); Assert.Equal("ID:b-9bcfa592-423a-4942-879d-eb284b418fc8-1.mq.us-west-2.amazonaws.com-37557-1234520418293-4:1:1:1:1", activemqEvent.Messages[0].MessageId); Assert.Equal("jms/text-message", activemqEvent.Messages[0].MessageType); Assert.Equal("ABC:AAAA", Encoding.UTF8.GetString(Convert.FromBase64String(activemqEvent.Messages[0].Data))); Assert.Equal("myJMSCoID", activemqEvent.Messages[0].ConnectionId); Assert.False(activemqEvent.Messages[0].Redelivered); Assert.Null(activemqEvent.Messages[0].Persistent); Assert.Equal("testQueue", activemqEvent.Messages[0].Destination.PhysicalName); Assert.NotNull(activemqEvent.Messages[0].Timestamp); Assert.NotNull(activemqEvent.Messages[0].BrokerInTime); Assert.NotNull(activemqEvent.Messages[0].BrokerOutTime); Assert.Equal("testValue", activemqEvent.Messages[0].Properties["testKey"]); Assert.Equal("ID:b-9bcfa592-423a-4942-879d-eb284b418fc8-1.mq.us-west-2.amazonaws.com-37557-1234520418293-4:1:1:1:1", activemqEvent.Messages[1].MessageId); Assert.Equal("jms/bytes-message", activemqEvent.Messages[1].MessageType); Assert.NotNull(Convert.FromBase64String(activemqEvent.Messages[1].Data)); Assert.Equal("myJMSCoID1", activemqEvent.Messages[1].ConnectionId); Assert.Null(activemqEvent.Messages[1].Redelivered); Assert.False(activemqEvent.Messages[1].Persistent); Assert.Equal("testQueue", activemqEvent.Messages[1].Destination.PhysicalName); Assert.NotNull(activemqEvent.Messages[1].Timestamp); Assert.NotNull(activemqEvent.Messages[1].BrokerInTime); Assert.NotNull(activemqEvent.Messages[1].BrokerOutTime); Assert.Equal("testValue", activemqEvent.Messages[1].Properties["testKey"]); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void RabbitMQEventTest(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("amazonmq-rabbitmq.json")) { var rabbitmqEvent = serializer.Deserialize<RabbitMQEvent>(fileStream); Assert.NotNull(rabbitmqEvent); Assert.Equal("aws:rmq", rabbitmqEvent.EventSource); Assert.Equal("arn:aws:mq:us-west-2:112556298976:broker:pizzaBroker:b-9bcfa592-423a-4942-879d-eb284b418fc8", rabbitmqEvent.EventSourceArn); Assert.Equal(1, rabbitmqEvent.RmqMessagesByQueue.Count); Assert.Equal(1, rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"].Count); Assert.NotNull(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties); Assert.Equal("text/plain", rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.ContentType); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.ContentEncoding); Assert.Equal(3, rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.Headers.Count); Assert.Equal(1, rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.DeliveryMode); Assert.Equal(34, rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.Priority); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.CorrelationId); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.ReplyTo); Assert.Equal("60000", rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.Expiration); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.MessageId); Assert.NotNull(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.Timestamp); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.Type); Assert.Equal("AIDACKCEVSQ6C2EXAMPLE", rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.UserId); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.AppId); Assert.Null(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.ClusterId); Assert.Equal(80, rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].BasicProperties.BodySize); Assert.False(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].Redelivered); Assert.Equal("{\"timeout\":0,\"data\":\"CZrmf0Gw8Ov4bqLQxD4E\"}", Encoding.UTF8.GetString(Convert.FromBase64String(rabbitmqEvent.RmqMessagesByQueue["pizzaQueue::/"][0].Data))); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayCustomAuthorizerV2Request(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("custom-authorizer-v2-request.json")) { var request = serializer.Deserialize<APIGatewayCustomAuthorizerV2Request>(fileStream); Assert.Equal("REQUEST", request.Type); Assert.Equal("arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request", request.RouteArn); Assert.Equal(new[] { "user1", "123" }, request.IdentitySource); Assert.Equal("$default", request.RouteKey); Assert.Equal("/my/path", request.RawPath); Assert.Equal("parameter1=value1&parameter1=value2&parameter2=value", request.RawQueryString); Assert.Equal(new[] { "cookie1", "cookie2" }, request.Cookies); Assert.Equal(new Dictionary<string, string> { ["Header1"] = "value1", ["Header2"] = "value2" }, request.Headers); Assert.Equal(new Dictionary<string, string> { ["parameter1"] = "value1,value2", ["parameter2"] = "value" }, request.QueryStringParameters); var requestContext = request.RequestContext; Assert.Equal("123456789012", requestContext.AccountId); Assert.Equal("api-id", requestContext.ApiId); var clientCert = requestContext.Authentication.ClientCert; Assert.Equal("CERT_CONTENT", clientCert.ClientCertPem); Assert.Equal("www.example.com", clientCert.SubjectDN); Assert.Equal("Example issuer", clientCert.IssuerDN); Assert.Equal("a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", clientCert.SerialNumber); Assert.Equal("May 28 12:30:02 2019 GMT", clientCert.Validity.NotBefore); Assert.Equal("Aug 5 09:36:04 2021 GMT", clientCert.Validity.NotAfter); Assert.Equal("id.execute-api.us-east-1.amazonaws.com", requestContext.DomainName); Assert.Equal("id", requestContext.DomainPrefix); Assert.Equal("POST", requestContext.Http.Method); Assert.Equal("HTTP/1.1", requestContext.Http.Protocol); Assert.Equal("IP", requestContext.Http.SourceIp); Assert.Equal("agent", requestContext.Http.UserAgent); Assert.Equal("id", requestContext.RequestId); Assert.Equal("$default", requestContext.RouteKey); Assert.Equal("$default", requestContext.Stage); Assert.Equal("12/Mar/2020:19:03:58 +0000", requestContext.Time); Assert.Equal(1583348638390, requestContext.TimeEpoch); Assert.Equal(new Dictionary<string, string> { ["parameter1"] = "value1" }, request.PathParameters); Assert.Equal(new Dictionary<string, string> { ["stageVariable1"] = "value1", ["stageVariable2"] = "value2" }, request.StageVariables); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayCustomAuthorizerV2SimpleResponse(Type serializerType) { var response = new APIGatewayCustomAuthorizerV2SimpleResponse { IsAuthorized = true, Context = new Dictionary<string, object>() { ["exampleKey"] = "exampleValue" } }; var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var json = SerializeJson(serializer, response); var actualObject = JObject.Parse(json); var expectedJObject = JObject.Parse(File.ReadAllText("custom-authorizer-v2-simple-response.json")); Assert.True(JToken.DeepEquals(actualObject, expectedJObject)); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void APIGatewayCustomAuthorizerV2IamResponse(Type serializerType) { var response = new APIGatewayCustomAuthorizerV2IamResponse { PrincipalID = "abcdef", PolicyDocument = new APIGatewayCustomAuthorizerPolicy { Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement> { new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Action = new HashSet<string> { "execute-api:Invoke" }, Effect = "Allow", Resource = new HashSet<string>{ "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]" } } } }, Context = new Dictionary<string, object>() { ["exampleKey"] = "exampleValue" } }; var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; var json = SerializeJson(serializer, response); var actualObject = JObject.Parse(json); var expectedJObject = JObject.Parse(File.ReadAllText("custom-authorizer-v2-iam-response.json")); Assert.True(JToken.DeepEquals(actualObject, expectedJObject)); } [Fact] public void SerializeCanUseNamingStrategy() { var namingStrategy = new CamelCaseNamingStrategy(); var serializer = new JsonSerializer(_ => { }, namingStrategy); var classUsingPascalCase = new ClassUsingPascalCase { SomeValue = 12, SomeOtherValue = "abcd", }; var ms = new MemoryStream(); serializer.Serialize(classUsingPascalCase, ms); ms.Position = 0; var serializedString = new StreamReader(ms).ReadToEnd(); Assert.Equal(@"{""someValue"":12,""someOtherValue"":""abcd""}", serializedString); } [Fact] public void SerializeWithCamelCaseNamingStrategyCanDeserializeBothCamelAndPascalCase() { var namingStrategy = new CamelCaseNamingStrategy(); var serializer = new JsonSerializer(_ => { }, namingStrategy); var camelCaseString = @"{""someValue"":12,""someOtherValue"":""abcd""}"; var pascalCaseString = @"{""SomeValue"":12,""SomeOtherValue"":""abcd""}"; var camelCaseObject = serializer.Deserialize<ClassUsingPascalCase>(new MemoryStream(Encoding.ASCII.GetBytes(camelCaseString))); var pascalCaseObject = serializer.Deserialize<ClassUsingPascalCase>(new MemoryStream(Encoding.ASCII.GetBytes(pascalCaseString))); Assert.Equal(12, camelCaseObject.SomeValue); Assert.Equal(12, pascalCaseObject.SomeValue); Assert.Equal("abcd", camelCaseObject.SomeOtherValue); Assert.Equal("abcd", pascalCaseObject.SomeOtherValue); } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchEventsS3ObjectCreate(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-s3objectcreated.json")) { var request = serializer.Deserialize<S3ObjectCreateEvent>(fileStream); Assert.Equal("17793124-05d4-b198-2fde-7ededc63b103", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("0", detail.Version); Assert.Equal("DOC-EXAMPLE-BUCKET1", detail.Bucket.Name); Assert.Equal("example-key", detail.Object.Key); Assert.Equal(5L, detail.Object.Size); Assert.Equal("b1946ac92492d2347c6235b4d2611184", detail.Object.ETag); Assert.Equal("IYV3p45BT0ac8hjHg1houSdS1a.Mro8e", detail.Object.VersionId); Assert.Equal("617f08299329d189", detail.Object.Sequencer); Assert.Equal("N4N7GDK58NMKJ12R", detail.RequestId); Assert.Equal("123456789012", detail.Requester); Assert.Equal("1.2.3.4", detail.SourceIpAddress); Assert.Equal("PutObject", detail.Reason); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchEventsS3ObjectDelete(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-s3objectdeleted.json")) { var request = serializer.Deserialize<S3ObjectDeleteEvent>(fileStream); Assert.Equal("2ee9cc15-d022-99ea-1fb8-1b1bac4850f9", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("0", detail.Version); Assert.Equal("DOC-EXAMPLE-BUCKET1", detail.Bucket.Name); Assert.Equal("example-key", detail.Object.Key); Assert.Equal("d41d8cd98f00b204e9800998ecf8427e", detail.Object.ETag); Assert.Equal("1QW9g1Z99LUNbvaaYVpW9xDlOLU.qxgF", detail.Object.VersionId); Assert.Equal("617f0837b476e463", detail.Object.Sequencer); Assert.Equal("0BH729840619AG5K", detail.RequestId); Assert.Equal("123456789012", detail.Requester); Assert.Equal("1.2.3.4", detail.SourceIpAddress); Assert.Equal("DeleteObject", detail.Reason); Assert.Equal("Delete Marker Created", detail.DeletionType); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchEventsS3ObjectRestore(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-s3objectrestore.json")) { var request = serializer.Deserialize<S3ObjectRestoreEvent>(fileStream); Assert.Equal("6924de0d-13e2-6bbf-c0c1-b903b753565e", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("0", detail.Version); Assert.Equal("DOC-EXAMPLE-BUCKET1", detail.Bucket.Name); Assert.Equal("example-key", detail.Object.Key); Assert.Equal(5L, detail.Object.Size); Assert.Equal("b1946ac92492d2347c6235b4d2611184", detail.Object.ETag); Assert.Equal("KKsjUC1.6gIjqtvhfg5AdMI0eCePIiT3", detail.Object.VersionId); Assert.Equal("189F19CB7FB1B6A4", detail.RequestId); Assert.Equal("s3.amazonaws.com", detail.Requester); Assert.Equal("2021-11-13T00:00:00Z", detail.RestoreExpiryTime); Assert.Equal("GLACIER", detail.SourceStorageClass); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchTranscribeJobStateChangeCompleted(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-transcribejobstatechangecompleted.json")) { var request = serializer.Deserialize<TranscribeJobStateChangeEvent>(fileStream); Assert.Equal("1de9a55a-39aa-d889-84eb-22d245492319", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("51a3dfef-87fa-423a-8d3b-690ca9cae1f4", detail.TranscriptionJobName); Assert.Equal("COMPLETED", detail.TranscriptionJobStatus); Assert.Null(detail.FailureReason); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchTranscribeJobStateChangeFailed(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-transcribejobstatechangefailed.json")) { var request = serializer.Deserialize<TranscribeJobStateChangeEvent>(fileStream); Assert.Equal("5505f4fc-979b-0304-3570-8fa0e3c09525", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("d43d0b58-2129-46ba-b2e2-b53ec9d1b210", detail.TranscriptionJobName); Assert.Equal("FAILED", detail.TranscriptionJobStatus); Assert.Equal("The media format that you specified doesn't match the detected media format. Check the media format and try your request again.", detail.FailureReason); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchTranslateTextTranslationJobStateChange(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-translatetexttranslationjobstatechange.json")) { var request = serializer.Deserialize<TranslateTextTranslationJobStateChangeEvent>(fileStream); Assert.Equal("8882c5af-c9da-4a58-99e2-91fbe33b9e52", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("8ce682a1-9be8-4f2c-875c-f8ae2fe1b015", detail.JobId); Assert.Equal("COMPLETED", detail.JobStatus); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchTranslateParallelDataStateChangeCreate(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-translateparalleldatastatechange-create.json")) { var request = serializer.Deserialize<TranslateParallelDataStateChangeEvent>(fileStream); Assert.Equal("e99030f3-a7a8-42f5-923a-684fbf9bff65", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("CreateParallelData", detail.Operation); Assert.Equal("ExampleParallelData", detail.Name); Assert.Equal("ACTIVE", detail.Status); } } [Theory] [InlineData(typeof(JsonSerializer))] #if NETCOREAPP3_1_OR_GREATER [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer))] [InlineData(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] #endif public void CloudWatchTranslateParallelDataStateChangeUpdate(Type serializerType) { var serializer = Activator.CreateInstance(serializerType) as ILambdaSerializer; using (var fileStream = LoadJsonTestFile("cloudwatchevents-translateparalleldatastatechange-update.json")) { var request = serializer.Deserialize<TranslateParallelDataStateChangeEvent>(fileStream); Assert.Equal("920d9de3-fbd0-4cfb-87aa-e35b5f7cba8f", request.Id); var detail = request.Detail; Assert.NotNull(detail); Assert.Equal("UpdateParallelData", detail.Operation); Assert.Equal("ExampleParallelData2", detail.Name); Assert.Equal("ACTIVE", detail.Status); Assert.Equal("ACTIVE", detail.LatestUpdateAttemptStatus); Assert.Equal(DateTime.Parse("2023-03-02T03:31:47Z").ToUniversalTime(), detail.LatestUpdateAttemptAt); } } class ClassUsingPascalCase { public int SomeValue { get; set; } public string SomeOtherValue { get; set; } } } } #pragma warning restore 618
3,230
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace HandlerTest { public static class Common { private static readonly string AppSettingsPath = Path.Combine(GetCurrentLocation(), "appsettings.json"); private static string GetCurrentLocation() { var assemblyLocation = typeof(Common).GetTypeInfo().Assembly.Location; var currentDir = Path.GetDirectoryName(assemblyLocation); return currentDir; } public static readonly ILoggerFactory LoggerFactory = CreateLoggerFactory(); private static ILoggerFactory CreateLoggerFactory() { var configuration = new ConfigurationBuilder() .AddJsonFile(AppSettingsPath) .Build(); var loggingSection = configuration.GetSection("Lambda.Logging"); if (loggingSection == null) throw new InvalidOperationException($"Cannot find Lambda.Logging section."); var options = new LambdaLoggerOptions(configuration); if (options.IncludeCategory != false) throw new InvalidOperationException($"IncludeCategory should be false."); if (options.IncludeLogLevel != true) throw new InvalidOperationException($"IncludeLogLevel should be true."); var loggerfactory = new TestLoggerFactory() .AddLambdaLogger(options); return loggerfactory; } public static string GetString(Stream stream) { if (stream == null) return null; using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public static MemoryStream GetStream(string data) { if (data == null) return null; var bytes = Encoding.UTF8.GetBytes(data); var ms = new MemoryStream(bytes); return ms; } public static void LogCommonData(string methodName) { LogCommonData(methodName, null, null); } public static void LogCommonData(string methodName, string data) { LogCommonData(methodName, data, null); } public static void LogCommonData(string methodName, ILambdaContext context) { LogCommonData(methodName, null, context); } public static void LogCommonData(string methodName, string data, ILambdaContext context) { // log method LambdaLogger.Log($">>[{methodName}]>>"); // log data if (data != null) { LambdaLogger.Log($"<<[{data}]<<"); } // log context data if (context != null) { var contextData = new List<string>(); contextData.Add(context.GetType().FullName); contextData.Add(context.AwsRequestId); contextData.Add(context.ClientContext.GetType().FullName); contextData.Add(context.ClientContext.Client.AppPackageName); contextData.Add(context.ClientContext.Client.AppTitle); contextData.Add(context.ClientContext.Client.AppVersionCode); contextData.Add(context.ClientContext.Client.AppVersionName); contextData.Add(context.ClientContext.Client.InstallationId); contextData.Add(string.Join(", ", context.ClientContext.Custom.Keys)); contextData.Add(string.Join(", ", context.ClientContext.Custom.Values)); contextData.Add(string.Join(", ", context.ClientContext.Environment.Keys)); contextData.Add(string.Join(", ", context.ClientContext.Environment.Values)); contextData.Add(context.FunctionName); contextData.Add(context.FunctionVersion); contextData.Add(context.Identity.IdentityId); contextData.Add(context.Identity.IdentityPoolId); contextData.Add(context.InvokedFunctionArn); contextData.Add(context.Logger.GetType().FullName); contextData.Add(context.LogGroupName); contextData.Add(context.LogStreamName); contextData.Add(context.MemoryLimitInMB.ToString()); contextData.Add(context.RemainingTime.Ticks.ToString()); LambdaLogger.Log($"==[{string.Join(";", contextData)}]=="); } // log using ILogger var loggerFactory = Common.LoggerFactory; if (loggerFactory == null) throw new InvalidOperationException("LoggerFactory is null!"); var nullLogger = loggerFactory.CreateLogger(null); nullLogger.LogInformation($"__[nullLogger-{methodName}]__"); nullLogger.LogTrace($"##[nullLogger-{methodName}]##"); var testLogger = loggerFactory.CreateLogger("HandlerTest.Logging"); testLogger.LogInformation($"__[testLogger-{methodName}]__"); // log using LambdaLogger static LambdaLogger.Log($"^^[{methodName}]^^"); } } }
150
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HandlerTest { public class CustomerPoco { public string Data { get; set; } public CustomerPoco(string data) { Data = data; } } public class CustomerPocoIn : CustomerPoco { public CustomerPocoIn(string data) : base(data) { } } public class CustomerPocoOut : CustomerPoco { public CustomerPocoOut(string data) : base(data) { } } public class SpecialCustomerPoco { public string Data { get; set; } public SpecialCustomerPoco(string data) { Data = data; } } public class Task2 : Task { public Task2(Action action) : base(action) { } } public class Task2<T> : Task<T> { public Task2(Func<T> func) : base(func) { } } public class Task3 : Task<string> { public Task3(Func<string> func) : base(func) { } } public class Task4<T,V> : Task<T> { public Task4(Func<T> func) : base(func) { } } public class Task5<V> : Task<string> { public Task5(Func<string> func) : base(func) { } public Task5() : base(() => typeof(V).FullName) { } } }
90
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Core; using System; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace HandlerTest { public class CustomerType { private const string AggregateExceptionTestMarker = "AggregateExceptionTesting"; [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public async Task<CustomerPocoOut> AsyncPocosContextDefaultSerializer(CustomerPocoIn data, ILambdaContext context) { Console.WriteLine($"Context.RemainingTime: '{context.RemainingTime}'"); Console.WriteLine($"Sleeping for {delayTime}..."); await Task.Delay(delayTime); Console.WriteLine($"Context.RemainingTime: '{context.RemainingTime}'"); return new CustomerPocoOut($"Hi '{data.Data}'!"); } public Stream HelloWorld(Stream input) { var loggerFactory = Common.LoggerFactory; var logger = loggerFactory.CreateLogger("HelloWorld"); logger.LogInformation($"Current time: '{DateTime.Now}'"); logger.LogDebug($"Sleeping for {delayTime}..."); Task.Delay(delayTime).Wait(); logger.LogWarning($"Current time: '{DateTime.Now}'"); var bytes = System.Text.Encoding.UTF8.GetBytes("Hello World!"); var stream = new MemoryStream(bytes); return stream; } private static TimeSpan delayTime = TimeSpan.FromMilliseconds(100); // void-out methods public void ZeroInZeroOut() { Common.LogCommonData("ZeroInZeroOut"); } public void ZeroInZeroOutThrowsException() { throw new Exception(); } public void StringInZeroOut(string data) { Common.LogCommonData("StringInZeroOut", data); } public void StreamInZeroOut(Stream data) { Common.LogCommonData("StreamInZeroOut", Common.GetString(data)); } public void PocoInZeroOut(CustomerPoco data) { Common.LogCommonData("PocoInZeroOut", data.Data); } public void ContextInZeroOut(ILambdaContext context) { Common.LogCommonData("ContextInZeroOut", context); } public void ContextAndStringInZeroOut(string data, ILambdaContext context) { Common.LogCommonData("ContextAndStringInZeroOut", data, context); } public void ContextAndStreamInZeroOut(Stream data, ILambdaContext context) { Common.LogCommonData("ContextAndStreamInZeroOut", Common.GetString(data), context); } public void ContextAndPocoInZeroOut(CustomerPoco poco, ILambdaContext context) { Common.LogCommonData("ContextAndPocoInZeroOut", poco.Data, context); } // T-out methods public string ZeroInStringOut() { Common.LogCommonData("ZeroInStringOut"); return "(([ZeroInStringOut]))"; } public Stream ZeroInStreamOut() { Common.LogCommonData("ZeroInStreamOut"); return Common.GetStream("(([ZeroInStreamOut]))"); } public MemoryStream ZeroInMemoryStreamOut() { Common.LogCommonData("ZeroInMemoryStreamOut"); return Common.GetStream("(([ZeroInMemoryStreamOut]))"); } public CustomerPoco ZeroInPocoOut() { Common.LogCommonData("ZeroInPocoOut"); return new CustomerPoco("(([ZeroInPocoOut]))"); } public string StringInStringOut(string data) { Common.LogCommonData("StringInStringOut", data); return "(([StringInStringOut]))"; } public Stream StreamInStreamOut(Stream data) { Common.LogCommonData("StreamInStreamOut", Common.GetString(data)); return Common.GetStream("(([StreamInStreamOut]))"); } public CustomerPoco PocoInPocoOut(CustomerPoco data) { Common.LogCommonData("PocoInPocoOut", data.Data); return new CustomerPoco("(([PocoInPocoOut]))"); } public CustomerPoco ContextAndPocoInPocoOut(CustomerPoco data, ILambdaContext context) { Common.LogCommonData("ContextAndPocoInPocoOut", data.Data, context); return new CustomerPoco("(([ContextAndPocoInPocoOut]))"); } public static CustomerPocoOut PocoInPocoOutStatic(CustomerPocoIn data) { Common.LogCommonData("PocoInPocoOutStatic", data.Data); return new CustomerPocoOut("(([PocoInPocoOutStatic]))"); } // Task-out methods public async Task ZeroInTaskOut() { await Task.Delay(delayTime); Common.LogCommonData("ZeroInTaskOut"); } public async Task ZeroInTaskOutThrowsException() { await Task.Delay(delayTime); throw new Exception(AggregateExceptionTestMarker); } public async Task ZeroInTaskOutThrowsAggregateExceptionExplicitly() { await Task.Delay(delayTime); throw new AggregateException(new Exception(AggregateExceptionTestMarker)); } public Task ZeroInTaskOutSync() { return Task.Run(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTaskOutSync"); }); } // TaskT-out methods public async Task<string> ZeroInTaskStringOut() { await Task.Delay(delayTime); Common.LogCommonData("ZeroInTaskStringOut"); return "(([ZeroInTaskStringOut]))"; } public async Task<string> ZeroInTaskStringOutThrowsException() { await Task.Delay(delayTime); throw new Exception(AggregateExceptionTestMarker); } public async Task<string> ZeroInTaskStringOutThrowsAggregateExceptionExplicitly() { await Task.Delay(delayTime); throw new AggregateException(new Exception(AggregateExceptionTestMarker)); } public async Task<Stream> ZeroInTaskStreamOut() { await Task.Delay(delayTime); Common.LogCommonData("ZeroInTaskStreamOut"); return Common.GetStream("(([ZeroInTaskStreamOut]))"); } public async Task<CustomerPoco> ZeroInTaskPocoOut() { await Task.Delay(delayTime); Common.LogCommonData("ZeroInTaskPocoOut"); return new CustomerPoco("(([ZeroInTaskPocoOut]))"); } // Generic methods public T GenericMethod<T>(T input) { return input; } // Overloaded methods public string OverloadedMethod(string input) { return input; } public Stream OverloadedMethod(Stream input) { return input; } // Custom serializer methods [LambdaSerializer(typeof(ConstructorExceptionCustomerTypeSerializer))] public CustomerPocoOut ErrorSerializerMethod(CustomerPocoIn input) { return new CustomerPocoOut(input.Data); } [LambdaSerializer(typeof(SpecialCustomerTypeSerializer))] public SpecialCustomerPoco CustomSerializerMethod(SpecialCustomerPoco input) { Common.LogCommonData("CustomSerializerMethod", input.Data); return new SpecialCustomerPoco("(([CustomSerializerMethod]))"); } [LambdaSerializer(typeof(NoZeroParameterConstructorCustomerTypeSerializer))] public SpecialCustomerPoco NoZeroParameterConstructorCustomerTypeSerializerMethod(SpecialCustomerPoco input) { Common.LogCommonData("NoZeroParameterConstructorCustomerTypeSerializerMethod", input.Data); return new SpecialCustomerPoco("(([NoZeroParameterConstructorCustomerTypeSerializerMethod]))"); } [LambdaSerializer(typeof(ExceptionInConstructorCustomerTypeSerializer))] public SpecialCustomerPoco ExceptionInConstructorCustomerTypeSerializerMethod(SpecialCustomerPoco input) { Common.LogCommonData("ExceptionInConstructorCustomerTypeSerializerMethod", input.Data); return new SpecialCustomerPoco("(([ExceptionInConstructorCustomerTypeSerializerMethod]))"); } [LambdaSerializer(typeof(NoInterfaceCustomerTypeSerializer))] public SpecialCustomerPoco NoInterfaceCustomerTypeSerializerMethod(SpecialCustomerPoco input) { Common.LogCommonData("NoZeroParameterConstructorCustomerTypeSerializerMethod", input.Data); return new SpecialCustomerPoco("(([NoZeroParameterConstructorCustomerTypeSerializerMethod]))"); } // Too many inputs public void TwoInputsNoContextMethod(int a, int b) { } public void TooManyInputsMethod(int a, int b, int c) { } // params inputs public void Params(params string[] args) { } public void Varargs(__arglist) { } // LambdaLogger.Log method public Stream StreamInSameStreamOut_NonCommon(Stream value) { return value; } // async void #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async void AsyncVoid() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { } // Task subclasses public Task2 ZeroInTask2Out() { var t = new Task2(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTask2Out"); }); t.RunSynchronously(); return t; } public Task2<string> ZeroInTTask2Out() { var t = new Task2<string>(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTTask2Out"); return "(([ZeroInTTask2Out]))"; }); t.RunSynchronously(); return t; } public Task3 ZeroInTTask3Out() { var t = new Task3(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTTask3Out"); return "(([ZeroInTTask3Out]))"; }); t.RunSynchronously(); return t; } public Task4<string, int> ZeroInTTask4Out() { var t = new Task4<string, int>(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTTask4Out"); return "(([ZeroInTTask4Out]))"; }); t.RunSynchronously(); return t; } public Task5<int> ZeroInTTask5Out() { var t = new Task5<int>(() => { Task.Delay(delayTime).Wait(); Common.LogCommonData("ZeroInTTask5Out"); return "(([ZeroInTTask5Out]))"; }); t.RunSynchronously(); return t; } } public abstract class AbstractCustomerType { public abstract string AbstractMethod(string input); public static string NonAbstractMethodStringInStringOut(string input) { Common.LogCommonData("NonAbstractMethodStringInStringOut", input); return "(([NonAbstractMethodStringInStringOut]))"; } } public class ConstructorExceptionCustomerType { public ConstructorExceptionCustomerType() { throw new Exception(); } public void SimpleMethod() { } } public class GenericCustomerType<T> { public CustomerPoco PocoInPocoOut(CustomerPoco data) { Common.LogCommonData("PocoInPocoOut", data.Data); return new CustomerPoco("(([PocoInPocoOut]))"); } public T TInTOut(T input) { return Worker(input); } protected virtual T Worker(T input) { throw new NotImplementedException(); } } public class SubclassOfGenericCustomerType : GenericCustomerType<string> { protected override string Worker(string input) { Common.LogCommonData("TInTOut", input); return "(([TInTOut]))"; } } public class NoZeroParamConstructorCustomerType { public NoZeroParamConstructorCustomerType(int data) { } public void SimpleMethod() { } } public static class StaticCustomerTypeThrows { static StaticCustomerTypeThrows() { throw new Exception(nameof(StaticCustomerTypeThrows) + " static constructor has thrown an exception."); } public static void StaticCustomerMethodZeroOut() { Common.LogCommonData(nameof(StaticCustomerMethodZeroOut)); } } public static class StaticCustomerType { static StaticCustomerType() { Common.LogCommonData(nameof(StaticCustomerType) + " static constructor has run."); } public static void StaticCustomerMethodZeroOut() { Common.LogCommonData(nameof(StaticCustomerMethodZeroOut)); } } }
418
aws-lambda-dotnet
aws
C#
/* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. */ /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Lambda.Core; using System; using System.IO; using System.Text; namespace HandlerTest { public class ConstructorExceptionCustomerTypeSerializer : ILambdaSerializer { public T Deserialize<T>(Stream requestStream) { var type = typeof(T); if (type == typeof(CustomerPoco)) { object poco = new CustomerPoco(Common.GetString(requestStream)); return (T)poco; } if (type == typeof(CustomerPocoIn)) { object poco = new CustomerPocoIn(Common.GetString(requestStream)); return (T)poco; } if (type == typeof(CustomerPocoOut)) { object poco = new CustomerPocoOut(Common.GetString(requestStream)); return (T)poco; } throw new InvalidCastException(); } public void Serialize<T>(T response, Stream responseStream) { string data; object obj = response; if (response is CustomerPoco) { var poco = (CustomerPoco)obj; data = poco.Data; } else { throw new InvalidCastException(); } using (var writer = new StreamWriter(responseStream)) { writer.Write(data); } } public ConstructorExceptionCustomerTypeSerializer() { throw new Exception(); } } public class SpecialCustomerTypeSerializer : ILambdaSerializer { public T Deserialize<T>(Stream requestStream) { var type = typeof(T); if (type == typeof(SpecialCustomerPoco)) { object poco = new SpecialCustomerPoco(Common.GetString(requestStream)); return (T)poco; } throw new InvalidCastException(); } public void Serialize<T>(T response, Stream responseStream) { string data; object obj = response; if (response is SpecialCustomerPoco) { SpecialCustomerPoco poco = (SpecialCustomerPoco)obj; data = poco.Data; } else { throw new InvalidCastException(); } responseStream.Write(Encoding.ASCII.GetBytes(data), 0, data.Length); } } public class NoZeroParameterConstructorCustomerTypeSerializer : ILambdaSerializer { public T Deserialize<T>(Stream requestStream) { throw new NotImplementedException(); } public void Serialize<T>(T response, Stream responseStream) { throw new NotImplementedException(); } public NoZeroParameterConstructorCustomerTypeSerializer(int data) { } } public class ExceptionInConstructorCustomerTypeSerializer : ILambdaSerializer { public T Deserialize<T>(Stream requestStream) { throw new NotImplementedException(); } public void Serialize<T>(T response, Stream responseStream) { throw new NotImplementedException(); } public ExceptionInConstructorCustomerTypeSerializer(int data) { throw new ArithmeticException("Exception in constructor of serializer!"); } } public class NoInterfaceCustomerTypeSerializer { public T Deserialize<T>(Stream requestStream) { throw new NotImplementedException(); } public void Serialize<T>(T response, Stream responseStream) { throw new NotImplementedException(); } } }
153
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HandlerTest { public class TestLoggerFactory : ILoggerFactory { private ILoggerProvider _provider; public void AddProvider(ILoggerProvider provider) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (_provider != null) { throw new InvalidOperationException("Provider is already set, cannot add another."); } _provider = provider; } public ILogger CreateLogger(string categoryName) { return _provider.CreateLogger(categoryName); } public void Dispose() { var provider = _provider; _provider = null; if (provider != null) { provider.Dispose(); } } } }
58
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HandlerTest")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("612302be-0560-4547-b94b-400d71ca0296")] [assembly: Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
37
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HandlerTestNoSerializer { public class CustomerPoco { public string Data { get; set; } public CustomerPoco(string data) { Data = data; } } }
33
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace HandlerTestNoSerializer { public class CustomerType { public CustomerPoco PocoInPocoOut(CustomerPoco data) { return new CustomerPoco(data.Data); } } }
26
aws-lambda-dotnet
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HandlerTestNoSerializer")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b1cc8380-e576-4f4b-a09a-6a956f523c7e")]
35
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.PowerShellHost; using static Amazon.Lambda.PowerShellTests.TestUtilites; namespace Amazon.Lambda.PowerShellTests { public class ExceptionHandlingTests { [Fact] public void CheckIfErrorCode() { Assert.True(ExceptionManager.IsErrorCode("ErrorCode1")); Assert.True(ExceptionManager.IsErrorCode("Error_Code")); Assert.True(ExceptionManager.IsErrorCode("ErrorϴCode")); Assert.False(ExceptionManager.IsErrorCode("1ErrorCode")); Assert.False(ExceptionManager.IsErrorCode("Error Code")); Assert.False(ExceptionManager.IsErrorCode("Error@Code")); } [Fact] public void ValidateSystemException() { ExceptionValidator("ThrowSystemException", "FileNotFoundException", null); } [Fact] public void ValidateCustomException() { ExceptionValidator("CustomException", "AccountNotFound", "The Account is not found"); } [Fact] public void CustomExceptionNoMessage() { ExceptionValidator("CustomExceptionNoMessage", "CustomExceptionNoMessage", "CustomExceptionNoMessage"); } [Fact] public void TestMultipleInvokesWithSameCustomException() { PowerShellScriptsAsFunctions.Function function = new PowerShellScriptsAsFunctions.Function("ErrorExamples.ps1"); ExceptionValidator(function, "CustomException", "AccountNotFound", "The Account is not found"); ExceptionValidator(function, "CustomException", "AccountNotFound", "The Account is not found"); } [Fact] public void TestMultipleInvokesWithDifferentCustomException() { PowerShellScriptsAsFunctions.Function function = new PowerShellScriptsAsFunctions.Function("ErrorExamples.ps1"); ExceptionValidator(function, "CustomException", "AccountNotFound", "The Account is not found"); ExceptionValidator(function, "CustomExceptionNoMessage", "CustomExceptionNoMessage", null); } [Fact] public void ThrowWithStringMessage() { ExceptionValidator("ThrowWithStringMessage", "RuntimeException", "Here is your error"); } [Fact] public void ThrowWithStringErrorCode() { ExceptionValidator("ThrowWithStringErrorCode", "ErrorCode42", "ErrorCode42"); } [Fact] public void WriteErrorWithMessageTest() { ExceptionValidator("WriteErrorWithMessageTest", "WriteErrorException", "Testing out Write-Error"); } [Fact] public void WriteErrorWithExceptionTest() { ExceptionValidator("WriteErrorWithExceptionTest", "FileNotFoundException", null); } private void ExceptionValidator(string psFunction, string exceptionType, string message) { PowerShellScriptsAsFunctions.Function function = new PowerShellScriptsAsFunctions.Function("ErrorExamples.ps1"); ExceptionValidator(function, psFunction, exceptionType, message); } private void ExceptionValidator(PowerShellScriptsAsFunctions.Function function, string psFunction, string exceptionType, string message) { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; function.PowerShellFunctionName = psFunction; Exception foundException = null; try { function.ExecuteFunction(new MemoryStream(), context); } catch (Exception e) { foundException = e; } Assert.NotNull(foundException); Assert.True(foundException.GetType().Name.EndsWith(exceptionType)); if(message != null) { Assert.Equal(message, foundException.Message); } } } }
128
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.PowerShellHost; using static Amazon.Lambda.PowerShellTests.TestUtilites; namespace Amazon.Lambda.PowerShellTests { public class FunctionInvokeTests { [Fact] public void FunctionWithBothInputAndContext() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = "\"YOU WILL BE LOWER\""; var function = new PowerShellScriptsAsFunctions.Function("FunctionTests.ps1") { PowerShellFunctionName = "ToLowerWithBothParams" }; var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Contains("Calling ToLower with both parameters", logger.Buffer.ToString()); Assert.Contains("TestLambdaContext", logger.Buffer.ToString()); Assert.Equal(inputString.ToLower().Replace("\"", ""), resultString); } [Fact] public void FunctionWithNoContext() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = "\"YOU WILL BE LOWER\""; var function = new PowerShellScriptsAsFunctions.Function("FunctionTests.ps1") { PowerShellFunctionName = "ToLowerNoContext" }; var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Contains("Calling ToLower with no context", logger.Buffer.ToString()); Assert.DoesNotContain("TestLambdaContext", logger.Buffer.ToString()); Assert.Equal(inputString.ToLower().Replace("\"", ""), resultString); } [Fact] public void FunctionWithNoParameters() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new PowerShellScriptsAsFunctions.Function("FunctionTests.ps1") { PowerShellFunctionName = "NoParameters" }; function.ExecuteFunction(new MemoryStream(), context); Assert.Contains("Calling NoParameters", logger.Buffer.ToString()); } } }
81
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.PowerShellHost; using static Amazon.Lambda.PowerShellTests.TestUtilites; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Amazon.Lambda.PowerShellTests { public class ScriptInvokeTests { [Fact] public void ToUpperTest() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = "\"hello world from powershell\""; var function = new PowerShellScriptsAsFunctions.Function("ToUpperScript.ps1"); var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Equal(inputString.ToUpper().Replace("\"", ""), resultString); Assert.Contains("Executing Script", logger.Buffer.ToString()); Assert.Contains("Logging From Context", logger.Buffer.ToString()); } [Fact] public void TestMarshalComplexResponse() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = ""; var function = new PowerShellScriptsAsFunctions.Function("TestMarshalComplexResponse.ps1"); var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); var marshalledResponse = JsonConvert.DeserializeObject(resultString) as JObject; Assert.Equal("Hello World from PowerShell in Lambda", marshalledResponse["Body"].ToString()); Assert.Equal(200, (int)marshalledResponse["StatusCode"]); Assert.Equal("text/plain", marshalledResponse["Headers"]["ContentType"]); } [Fact] public void CallingUnknownCommandTest() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = ""; var function = new PowerShellScriptsAsFunctions.Function("CallingUnknownCommand.ps1"); Exception foundException = null; try { function.ExecuteFunction(ConvertToStream(inputString), context); } catch(Exception e) { foundException = e; } Assert.NotNull(foundException); Assert.Contains("New-MagicBeanCmdLet", logger.Buffer.ToString()); Assert.Contains("New-MagicBeanCmdLet", foundException.Message); } [Fact] public void TestExternalModuleLoaded() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = ""; var function = new PowerShellScriptsAsFunctions.Function("TestExternalModuleLoaded.ps1"); function.ExecuteFunction(ConvertToStream(inputString), context); Assert.Contains("Returns meta data about all the tasks defined in the provided psake script.", logger.Buffer.ToString()); } [Fact] public void UseAWSPowerShellCmdLetTest() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = ""; var function = new PowerShellScriptsAsFunctions.Function("UseAWSPowerShellCmdLetTest.ps1"); var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Contains(@"Importing module ./Modules/AWSPowerShell.NetCore", logger.Buffer.ToString().Replace('\\', '/')); Assert.Contains("ServiceName", resultString); Assert.Contains("AWS Lambda", resultString); } #if NETCOREAPP3_1 [Fact] public void ForObjectParallelTest() { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = ""; var function = new PowerShellScriptsAsFunctions.Function("ForObjectParallel.ps1"); function.ExecuteFunction(ConvertToStream(inputString), context); Assert.Contains("Running against: 1 for SharedVariable: Hello Shared Variable", logger.Buffer.ToString()); Assert.Contains("Running against: 50 for SharedVariable: Hello Shared Variable", logger.Buffer.ToString()); Assert.Contains("Running against: 100 for SharedVariable: Hello Shared Variable", logger.Buffer.ToString()); } #endif [Fact] public void CheckTempEnvironmentVariable() { // Non Lambda Environment { var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = "\"hello world from powershell\""; var function = new PowerShellScriptsAsFunctions.Function("TempEnvCheck.ps1"); var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Equal(Path.GetTempPath(), resultString); } var currentHome = Environment.GetEnvironmentVariable("HOME"); // Lambda environment try { Environment.SetEnvironmentVariable("HOME", null); Environment.SetEnvironmentVariable("LAMBDA_TASK_ROOT", "/var/task"); var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var inputString = "\"hello world from powershell\""; var function = new PowerShellScriptsAsFunctions.Function("TempEnvCheck.ps1"); var resultStream = function.ExecuteFunction(ConvertToStream(inputString), context); var resultString = ConvertToString(resultStream); Assert.Equal("/tmp", resultString); Assert.Contains("/tmp/home", logger.Buffer.ToString()); } finally { Environment.SetEnvironmentVariable("LAMBDA_TASK_ROOT", null); Environment.SetEnvironmentVariable("HOME", currentHome); } } } }
196
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Amazon.Lambda.PowerShellTests { public static class TestUtilites { public static string ConvertToString(Stream ms) { using (var reader = new StreamReader(ms)) { return reader.ReadToEnd(); } } public static Stream ConvertToStream(string str) { return new MemoryStream(UTF8Encoding.UTF8.GetBytes(str)); } } }
24
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestFunction { public class Function { [Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public string ToUpper(string input) { return input?.ToUpper(); } } }
18
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestFunction { public class ValidateHandlerFunctionSignatures : BaseValidateHandlerFunctionSignatures { public string NoParameters() { return null; } public string OneStringParameters(string one) { return null; } public string TooManyParameters(string one, string two, string three) { return null; } } public class BaseValidateHandlerFunctionSignatures { public string InheritedMethod(string input) { return null; } } }
34
aws-lambda-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestFunction")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("11a53c8d-a49b-4477-bfd9-e00c77d1291c")]
20
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.Serialization.Json; using Newtonsoft.Json; using AmazonSerializer = Amazon.Lambda.Serialization.Json; namespace FSharpJsonSerializer { public class FSharpJsonSerializer : AmazonSerializer.JsonSerializer { private static JsonConverter converter = new Fable.JsonConverter(); public FSharpJsonSerializer() : base(new []{converter}) { } } }
17
aws-lambda-dotnet
aws
C#
using System; using Xunit; using TestFunctionFSharp; using Amazon.Lambda.TestUtilities; using Microsoft.FSharp.Core; namespace TestFunctionCSharp { public class CSharpClassUsingFSharpTypeTest { [Fact] public void GetPaymentMethod_should_return_None_when_given_Garbage() { var context = new TestLambdaContext(); // because it's impossible to pass null in F# FunctionFSharp.PaymentMethod input = null; var actual = FunctionFSharp.getPaymentMethod(input,context); Assert.Equal(FSharpOption<FunctionFSharp.PaymentMethod>.None, actual); } } }
22
aws-lambda-dotnet
aws
C#
using System; using Xunit; using Amazon.Lambda.Serialization.Json; using System.Collections.Generic; using Newtonsoft.Json; using AmazonJsonSerializer = Amazon.Lambda.Serialization.Json.JsonSerializer; public class JsonSerializerTest { [Fact] public void JsonSerializerDoesntThrowWithNullArg () { IEnumerable<JsonConverter> converters = null; var ex = Record.Exception(() => new AmazonJsonSerializer(converters)); // No exception in general and no NullReference in particular Assert.Null(ex); } }
18
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer.Hosting.Internal; using Amazon.Lambda.AspNetCoreServer.Internal; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.Serialization.SystemTextJson; using Microsoft.AspNetCore.Hosting.Server; if (args.Length != 2) { throw new Exception("Incorrect command line arguments: <request-file-path> <response-file-path>"); } // Grab the request we want to test with var requestFilePath = args[0]; if(!File.Exists(requestFilePath)) { throw new Exception($"Unable to find request path {requestFilePath}"); } var requestJsonContent = File.ReadAllText(requestFilePath); var lambdaSerializer = new DefaultLambdaJsonSerializer(); var apiGatewayRequest = lambdaSerializer.Deserialize<APIGatewayProxyRequest>(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(requestJsonContent))); var builder = WebApplication.CreateBuilder(args); // Inject our own Lambda server replacing Kestrel. builder.Services.AddSingleton<IServer, LambdaServer>(); var app = builder.Build(); app.UseHttpsRedirection(); app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda"); app.MapPost("/test-post-complex", (Jane jane) => { return Results.Ok($"works:{jane.TestString}"); }); var source = new CancellationTokenSource(); _ = app.RunAsync(source.Token); await Task.Delay(1000); // Now that ASP.NET Core has started send the request into ASP.NET Core via Lambda function which will grab the LambdaServer register for IServer and forward the request in. var lambdaFunction = new APIGatewayRestApiLambdaRuntimeSupportServer.APIGatewayRestApiMinimalApi(app.Services); var response = await lambdaFunction.FunctionHandlerAsync(apiGatewayRequest, new TestLambdaContext()); var responseFilePath = args[1]; using (var outputStream = File.OpenWrite(responseFilePath)) { lambdaSerializer.Serialize(response, outputStream); } source.Cancel(); public record Jane(string TestString);
61
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; namespace PowerShellScriptsAsFunctions { public class Function : Amazon.Lambda.PowerShellHost.PowerShellFunctionHost { public Function(string script) : base(script) { } } }
23
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
3
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text.Json; using System.Threading; using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; namespace TestServerlessApp { public class ComplexCalculator { [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Post, "/ComplexCalculator/Add")] public Tuple<double, double> Add([FromBody]string complexNumbers, ILambdaContext context, APIGatewayHttpApiV2ProxyRequest request) { context.Logger.Log($"Request {JsonSerializer.Serialize(request)}"); var components = complexNumbers.Split(";"); if (components.Length != 2) { throw new ArgumentException(@$"Complex numbers must be in format ""1,2;3,4"", but found ""{complexNumbers}"""); } var firstComponent = components[0].Split(","); if (firstComponent.Count() != 2) { throw new ArgumentException(@$"Complex number must be in format ""1,2"", but found ""{firstComponent}"""); } var secondComponent = components[1].Split(","); if (secondComponent.Count() != 2) { throw new ArgumentException(@$"Complex number must be in format ""1,2"", but found ""{secondComponent}"""); } var c1 = new Complex(int.Parse(firstComponent[0]), int.Parse(firstComponent[1])); var c2 = new Complex(int.Parse(secondComponent[0]), int.Parse(secondComponent[1])); var result = c1 + c2; return new Tuple<double, double>(result.Real, result.Imaginary); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Post, "/ComplexCalculator/Subtract")] public Tuple<double, double> Subtract([FromBody]IList<IList<int>> complexNumbers) { if (complexNumbers.Count() != 2) { throw new ArgumentException("There must be two complex numbers"); } var firstComponent = complexNumbers[0]; if (firstComponent.Count() != 2) { throw new ArgumentException(@$"Complex number must be in format [1,2], but found ""{firstComponent}"""); } var secondComponent = complexNumbers[1]; if (secondComponent.Count() != 2) { throw new ArgumentException(@$"Complex number must be in format [1,2], but found ""{secondComponent}"""); } var c1 = new Complex(firstComponent[0], firstComponent[1]); var c2 = new Complex(secondComponent[0], secondComponent[1]); var result = c1 - c2; return new Tuple<double, double>(result.Real, result.Imaginary); } } }
74
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.Core; using System.Threading.Tasks; namespace TestServerlessApp { public class CustomizeResponseExamples { [LambdaFunction(PackageType = LambdaPackageType.Image)] [RestApi(LambdaHttpMethod.Get, "/okresponsewithheader/{x}")] public IHttpResult OkResponseWithHeader(int x, ILambdaContext context) { return HttpResults.Ok("All Good") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar"); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [RestApi(LambdaHttpMethod.Get, "/okresponsewithheaderasync/{x}")] public Task<IHttpResult> OkResponseWithHeaderAsync(int x, ILambdaContext context) { return Task.FromResult(HttpResults.Ok("All Good") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar")); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/notfoundwithheaderv2/{x}")] public IHttpResult NotFoundResponseWithHeaderV2(int x, ILambdaContext context) { return HttpResults.NotFound("Not Found") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar"); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/notfoundwithheaderv2async/{x}")] public Task<IHttpResult> NotFoundResponseWithHeaderV2Async(int x, ILambdaContext context) { return Task.FromResult(HttpResults.NotFound("Not Found") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar")); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/notfoundwithheaderv1/{x}", Version = HttpApiVersion.V1)] public IHttpResult NotFoundResponseWithHeaderV1(int x, ILambdaContext context) { return HttpResults.NotFound("Not Found") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar"); } [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/notfoundwithheaderv1async/{x}", Version = HttpApiVersion.V1)] public Task<IHttpResult> NotFoundResponseWithHeaderV1Async(int x, ILambdaContext context) { return Task.FromResult(HttpResults.NotFound("Not Found") .AddHeader("Single-Header", "Value") .AddHeader("Multi-Header", "Foo") .AddHeader("Multi-Header", "Bar")); } } }
71
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; using System.Threading.Tasks; namespace TestServerlessApp { public class DynamicExample { [LambdaFunction(PackageType = LambdaPackageType.Image)] public dynamic DynamicReturn(string text, ILambdaContext context) { context.Logger.LogLine(text); return text; } [LambdaFunction(PackageType = LambdaPackageType.Image)] public string DynamicInput(dynamic text, ILambdaContext context) { context.Logger.LogLine(text); return text; } } }
24
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; namespace TestServerlessApp { public class Greeter { [LambdaFunction(ResourceName = "GreeterSayHello", MemorySize = 1024, PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/Greeter/SayHello", Version = HttpApiVersion.V1)] public void SayHello([FromQuery(Name = "names")]IEnumerable<string> firstNames, APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine($"Request {JsonSerializer.Serialize(request)}"); if (firstNames == null) { return; } foreach (var firstName in firstNames) { Console.WriteLine($"Hello {firstName}"); } } [LambdaFunction(ResourceName = "GreeterSayHelloAsync", Timeout = 50, PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/Greeter/SayHelloAsync", Version = HttpApiVersion.V1)] public async Task SayHelloAsync([FromHeader(Name = "names")]IEnumerable<string> firstNames) { if (firstNames == null) { return; } foreach (var firstName in firstNames) { Console.WriteLine($"Hello {firstName}"); } await Task.CompletedTask; } } }
47
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; namespace TestServerlessApp { public class IntrinsicExample { [LambdaFunction(PackageType = LambdaPackageType.Image)] public void HasIntrinsic(string text, ILambdaContext context) { context.Logger.LogLine(text); } } }
15
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.Core; namespace TestServerlessApp { public class NullableReferenceTypeExample { [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/nullableheaderhttpapi")] public void NullableHeaderHttpApi([FromHeader(Name = "MyHeader")] string? text, ILambdaContext context) { context.Logger.LogLine(text); } } }
17
aws-lambda-dotnet
aws
C#
namespace TestServerlessApp { internal class PlaceholderClass { // This type exists because some of the source generator tests use fake CS files to simulate errors. // But there needs to be at least one real CS file in the test for the generator to determine the project // directory. No logic should exist in this type. } }
10
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using TestServerlessApp.Services; namespace TestServerlessApp { public class SimpleCalculator { private readonly ISimpleCalculatorService _simpleCalculatorService; /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public SimpleCalculator(ISimpleCalculatorService simpleCalculatorService) { this._simpleCalculatorService = simpleCalculatorService; } [LambdaFunction(ResourceName = "SimpleCalculatorAdd", PackageType = LambdaPackageType.Image)] [RestApi(LambdaHttpMethod.Get, "/SimpleCalculator/Add")] public int Add([FromQuery]int x, [FromQuery]int y) { return _simpleCalculatorService.Add(x, y); } [LambdaFunction(ResourceName = "SimpleCalculatorSubtract", PackageType = LambdaPackageType.Image)] [RestApi(LambdaHttpMethod.Get, "/SimpleCalculator/Subtract")] public APIGatewayProxyResponse Subtract([FromHeader]int x, [FromHeader]int y, [FromServices]ISimpleCalculatorService simpleCalculatorService) { return new APIGatewayProxyResponse { StatusCode = 200, Body = simpleCalculatorService.Subtract(x, y).ToString() }; } [LambdaFunction(ResourceName = "SimpleCalculatorMultiply", PackageType = LambdaPackageType.Image)] [RestApi(LambdaHttpMethod.Get, "/SimpleCalculator/Multiply/{x}/{y}")] public string Multiply(int x, int y) { return _simpleCalculatorService.Multiply(x, y).ToString(); } [LambdaFunction(ResourceName = "SimpleCalculatorDivideAsync", PackageType = LambdaPackageType.Image)] [RestApi(template: "/SimpleCalculator/DivideAsync/{x}/{y}", method: LambdaHttpMethod.Get)] public async Task<int> DivideAsync([FromRoute(Name = "x")]int first, [FromRoute(Name = "y")]int second) { return await Task.FromResult(_simpleCalculatorService.Divide(first, second)); } [LambdaFunction(ResourceName = "PI", PackageType = LambdaPackageType.Image)] public double Pi([FromServices]ISimpleCalculatorService simpleCalculatorService) { return simpleCalculatorService.PI(); } [LambdaFunction(ResourceName = "Random", PackageType = LambdaPackageType.Image)] public async Task<int> Random(int maxValue, ILambdaContext context) { context.Logger.Log($"Max value: {maxValue}"); var value = new Random().Next(maxValue); return await Task.FromResult(value); } [LambdaFunction(ResourceName = "Randoms", PackageType = LambdaPackageType.Image)] public IList<int> Randoms(RandomsInput input, ILambdaContext context) { context.Logger.Log($"Count: {input.Count}"); context.Logger.Log($"Max value: {input.MaxValue}"); var random = new Random(); var nums = new List<int>(); for (int i = 0; i < input.Count; i++) { nums.Add(random.Next(input.MaxValue)); } return nums; } public class RandomsInput { public int Count { get; set; } public int MaxValue { get; set; } } } }
93
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Text; using TestServerlessApp.Services; namespace TestServerlessApp { [LambdaStartup] public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<ISimpleCalculatorService, SimpleCalculatorService>(); } } }
20
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; using System.Threading.Tasks; namespace TestServerlessApp { public class TaskExample { [LambdaFunction(PackageType = LambdaPackageType.Image)] public async Task TaskReturn(string text, ILambdaContext context) { context.Logger.LogLine(text); await Task.CompletedTask; } } }
17
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; namespace TestServerlessApp { public class VoidExample { [LambdaFunction(PackageType = LambdaPackageType.Image)] public void VoidReturn(string text, ILambdaContext context) { context.Logger.LogLine(text); } } }
15
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.Core; namespace TestServerlessApp.FromScratch { public class NoApiGatewayEventsReference { [LambdaFunction(PackageType = LambdaPackageType.Image)] [HttpApi(LambdaHttpMethod.Get, "/{text}")] public string ToUpper(string text) { return text.ToUpper(); } } }
17
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; using Amazon.Lambda.Core; namespace TestServerlessApp.FromScratch { public class NoSerializerAttributeReference { [LambdaFunction(PackageType = LambdaPackageType.Image)] public string ToUpper(string text) { return text.ToUpper(); } } }
16
aws-lambda-dotnet
aws
C#
using System; using System.Text.RegularExpressions; namespace TestServerlessApp.Services { public interface ISimpleCalculatorService { int Add(int x, int y); int Subtract(int x, int y); int Multiply(int x, int y); int Divide(int x, int y); double PI(); } public class SimpleCalculatorService : ISimpleCalculatorService { public int Divide(int x, int y) { return x / y; } public double PI() { return Math.PI; } public int Multiply(int x, int y) { return x * y; } public int Add(int x, int y) { return x + y; } public int Subtract(int x, int y) { return x - y; } } }
42
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; namespace TestServerlessApp.Sub1 { public class Functions { [LambdaFunction(ResourceName = "ToUpper", PackageType = LambdaPackageType.Image)] public string ToUpper(string text) { return text.ToUpper(); } } }
15
aws-lambda-dotnet
aws
C#
using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; namespace TestServerlessApp.IntegrationTests { [Collection("Integration Tests")] public class ComplexCalculator { private readonly IntegrationTestContextFixture _fixture; public ComplexCalculator(IntegrationTestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task Add_FromBodyAsString_ReturnsJson() { var response = await _fixture.HttpClient.PostAsync($"{_fixture.HttpApiUrlPrefix}/ComplexCalculator/Add", new StringContent("1,2;3,4")); response.EnsureSuccessStatusCode(); var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(4, responseJson["Item1"]); Assert.Equal(6, responseJson["Item2"]); } [Fact] public async Task Subtract_FromBodyAsList_ReturnsJson() { var json = JsonConvert.SerializeObject(new[,] { { 1, 2 }, { 3, 4 } }); var data = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _fixture.HttpClient.PostAsync($"{_fixture.HttpApiUrlPrefix}/ComplexCalculator/Subtract", data); response.EnsureSuccessStatusCode(); var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync()); Assert.Equal(-2, responseJson["Item1"]); Assert.Equal(-2, responseJson["Item2"]); } } }
42
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace TestServerlessApp.IntegrationTests { [Collection("Integration Tests")] public class Greeter { private readonly IntegrationTestContextFixture _fixture; public Greeter(IntegrationTestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task SayHello_FromQuery_LogsToCloudWatch() { var response = await _fixture.HttpClient.GetAsync($"{_fixture.HttpApiUrlPrefix}/Greeter/SayHello?names=Alice&names=Bob"); response.EnsureSuccessStatusCode(); var lambdaFunctionName = _fixture.LambdaFunctions.FirstOrDefault(x => string.Equals(x.LogicalId, "GreeterSayHello"))?.Name; Assert.False(string.IsNullOrEmpty(lambdaFunctionName)); var logGroupName = _fixture.CloudWatchHelper.GetLogGroupName(lambdaFunctionName); Assert.True(await _fixture.CloudWatchHelper.MessageExistsInRecentLogEventsAsync("Hello Alice", logGroupName, logGroupName)); Assert.True(await _fixture.CloudWatchHelper.MessageExistsInRecentLogEventsAsync("Hello Bob", logGroupName, logGroupName)); } [Fact] public async Task SayHelloAsync_FromHeader_LogsToCloudWatch() { var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri($"{_fixture.HttpApiUrlPrefix}/Greeter/SayHelloAsync"), Headers = {{ "names", new List<string>{"Alice", "Bob"}}} }; var response = _fixture.HttpClient.SendAsync(httpRequestMessage).Result; response.EnsureSuccessStatusCode(); var lambdaFunctionName = _fixture.LambdaFunctions.FirstOrDefault(x => string.Equals(x.LogicalId, "GreeterSayHelloAsync"))?.Name; Assert.False(string.IsNullOrEmpty(lambdaFunctionName)); var logGroupName = _fixture.CloudWatchHelper.GetLogGroupName(lambdaFunctionName); Assert.True(await _fixture.CloudWatchHelper.MessageExistsInRecentLogEventsAsync("Hello Alice, Bob", logGroupName, logGroupName)); } } }
49
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudWatchLogs; using Amazon.Lambda; using Amazon.S3; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TestServerlessApp.IntegrationTests.Helpers; using Xunit; namespace TestServerlessApp.IntegrationTests { public class IntegrationTestContextFixture : IAsyncLifetime { private readonly CloudFormationHelper _cloudFormationHelper; private readonly S3Helper _s3Helper; private string _stackName; private string _bucketName; public readonly LambdaHelper LambdaHelper; public readonly CloudWatchHelper CloudWatchHelper; public readonly HttpClient HttpClient; public string RestApiUrlPrefix; public string HttpApiUrlPrefix; public List<LambdaFunction> LambdaFunctions; public IntegrationTestContextFixture() { _cloudFormationHelper = new CloudFormationHelper(new AmazonCloudFormationClient(Amazon.RegionEndpoint.USWest2)); _s3Helper = new S3Helper(new AmazonS3Client(Amazon.RegionEndpoint.USWest2)); LambdaHelper = new LambdaHelper(new AmazonLambdaClient(Amazon.RegionEndpoint.USWest2)); CloudWatchHelper = new CloudWatchHelper(new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2)); HttpClient = new HttpClient(); } public async Task InitializeAsync() { var scriptPath = Path.Combine("..", "..", "..", "DeploymentScript.ps1"); await CommandLineWrapper.RunAsync($"pwsh {scriptPath}"); _stackName = GetStackName(); _bucketName = GetBucketName(); Assert.False(string.IsNullOrEmpty(_stackName)); Assert.False(string.IsNullOrEmpty(_bucketName)); RestApiUrlPrefix = await _cloudFormationHelper.GetOutputValueAsync(_stackName, "RestApiURL"); HttpApiUrlPrefix = await _cloudFormationHelper.GetOutputValueAsync(_stackName, "HttpApiURL"); LambdaFunctions = await LambdaHelper.FilterByCloudFormationStackAsync(_stackName); Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatusAsync(_stackName)); Assert.True(await _s3Helper.BucketExistsAsync(_bucketName)); Assert.Equal(25, LambdaFunctions.Count); Assert.False(string.IsNullOrEmpty(RestApiUrlPrefix)); Assert.False(string.IsNullOrEmpty(RestApiUrlPrefix)); await LambdaHelper.WaitTillNotPending(LambdaFunctions.Select(x => x.Name).ToList()); } public async Task DisposeAsync() { await _cloudFormationHelper.DeleteStackAsync(_stackName); Assert.True(await _cloudFormationHelper.IsDeletedAsync(_stackName), $"The stack '{_stackName}' still exists and will have to be manually deleted from the AWS console."); await _s3Helper.DeleteBucketAsync(_bucketName); Assert.False(await _s3Helper.BucketExistsAsync(_bucketName), $"The bucket '{_bucketName}' still exists and will have to be manually deleted from the AWS console."); var filePath = Path.Combine("..", "..", "..", "..", "TestServerlessApp", "aws-lambda-tools-defaults.json"); var token = JObject.Parse(await File.ReadAllTextAsync(filePath)); token["s3-bucket"] = "test-serverless-app"; token["stack-name"] = "test-serverless-app"; await File.WriteAllTextAsync(filePath, token.ToString(Formatting.Indented)); } private string GetStackName() { var filePath = Path.Combine("..", "..", "..", "..", "TestServerlessApp", "aws-lambda-tools-defaults.json"); var token = JObject.Parse(File.ReadAllText(filePath))["stack-name"]; return token.ToObject<string>(); } private string GetBucketName() { var filePath = Path.Combine("..", "..", "..", "..", "TestServerlessApp", "aws-lambda-tools-defaults.json"); var token = JObject.Parse(File.ReadAllText(filePath))["s3-bucket"]; return token.ToObject<string>(); } } }
94