public static async Task Function_Reverses_Numbers_With_Mobile_Sdk() { // Arrange using var server = new LambdaTestServer(); using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await server.StartAsync(cancellationTokenSource.Token); int[] value = new[] { 1, 2, 3 }; byte[] content = JsonSerializer.SerializeToUtf8Bytes(value); var request = new LambdaTestRequest(content) { ClientContext = JsonSerializer.Serialize(new { client = new { app_title = "my-app" } }), CognitoIdentity = JsonSerializer.Serialize(new { identityId = "my-identity" }), }; LambdaTestContext context = await server.EnqueueAsync(content); using var httpClient = server.CreateClient(); // Act await ReverseFunction.RunAsync(httpClient, cancellationTokenSource.Token); // Assert Assert.True(context.Response.TryRead(out LambdaTestResponse? response)); Assert.NotNull(response); Assert.True(response !.IsSuccessful); var actual = JsonSerializer.Deserialize <int[]>(response.Content); Assert.NotNull(actual); Assert.Equal(new[] { 3, 2, 1 }, actual); }
public static async Task Function_Reverses_Numbers() { // Arrange using var server = new LambdaTestServer(); using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await server.StartAsync(cancellationTokenSource.Token); int[] value = new[] { 1, 2, 3 }; byte[] json = JsonSerializer.SerializeToUtf8Bytes(value); LambdaTestContext context = await server.EnqueueAsync(json); using var httpClient = server.CreateClient(); // Act await ReverseFunction.RunAsync(httpClient, cancellationTokenSource.Token); // Assert Assert.True(context.Response.TryRead(out LambdaTestResponse? response)); Assert.True(response !.IsSuccessful); Assert.NotNull(response.Content); var actual = JsonSerializer.Deserialize <int[]>(response.Content); Assert.NotNull(actual); Assert.Equal(new[] { 3, 2, 1 }, actual); }
private static CancellationTokenSource GetCancellationTokenSourceForResponseAvailable( LambdaTestContext context, TimeSpan?timeout = null) { if (timeout == null) { timeout = System.Diagnostics.Debugger.IsAttached ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(3); } var cts = new CancellationTokenSource(timeout.Value); // Queue a task to stop the test server from listening as soon as the response is available _ = Task.Factory.StartNew( async() => { await context.Response.WaitToReadAsync(cts.Token); if (!cts.IsCancellationRequested) { cts.Cancel(); } }, cts.Token, TaskCreationOptions.None, TaskScheduler.Default); return(cts); }
public static async Task Function_Can_Process_Request() { // Arrange - Create a test server for the Lambda runtime to use using var server = new LambdaTestServer(); // Create a cancellation token that stops the server listening for new requests. // Auto-cancel the server after 2 seconds in case something goes wrong and the request is not handled. using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2)); // Start the test server so it is ready to listen for requests from the Lambda runtime await server.StartAsync(cancellationTokenSource.Token); // Create a test request for the Lambda function being tested var value = new MyRequest() { Values = new[] { 1, 2, 3 }, // The function returns the sum of the specified numbers }; string requestJson = JsonSerializer.Serialize(value); // Queue the request with the server to invoke the Lambda function and // store the ChannelReader into a variable to use to read the response. LambdaTestContext context = await server.EnqueueAsync(requestJson); // Queue a task to stop the test server from listening as soon as the response is available _ = Task.Run(async() => { await context.Response.WaitToReadAsync(cancellationTokenSource.Token); if (!cancellationTokenSource.IsCancellationRequested) { cancellationTokenSource.Cancel(); } }); // Create an HttpClient for the Lambda to use with LambdaBootstrap using var httpClient = server.CreateClient(); // Act - Start the Lambda runtime and run until the cancellation token is signalled await MyFunctionEntrypoint.RunAsync(httpClient, cancellationTokenSource.Token); // Assert - The channel reader should have the response available context.Response.TryRead(out LambdaTestResponse? response).ShouldBeTrue("No Lambda response is available."); response !.IsSuccessful.ShouldBeTrue("The Lambda function failed to handle the request."); response.Content.ShouldNotBeEmpty("The Lambda function did not return any content."); string responseJson = await response.ReadAsStringAsync(); var actual = JsonSerializer.Deserialize <MyResponse>(responseJson); actual.ShouldNotBeNull(); actual.Sum.ShouldBe(6, "The Lambda function returned an incorrect response."); }
private async Task <APIGatewayProxyResponse> AssertApiGatewayRequestIsHandledAsync( APIGatewayProxyRequest request) { // Arrange var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); string json = JsonSerializer.Serialize(request, options); LambdaTestContext context = await _server.EnqueueAsync(json); using var cts = GetCancellationTokenSourceForResponseAvailable(context); // Act _ = Task.Factory.StartNew( () => { try { typeof(Site.Program).Assembly.EntryPoint !.Invoke(null, new[] { Array.Empty <string>() }); } catch (Exception ex) when(LambdaServerWasShutDown(ex)) { // The Lambda runtime server was shut down } }, cts.Token, TaskCreationOptions.None, TaskScheduler.Default); // Assert await context.Response.WaitToReadAsync(cts.IsCancellationRequested?default: cts.Token); context.Response.TryRead(out LambdaTestResponse? response).ShouldBeTrue(); response.IsSuccessful.ShouldBeTrue($"Failed to process request: {await response.ReadAsStringAsync()}"); response.Duration.ShouldBeInRange(TimeSpan.Zero, TimeSpan.FromSeconds(2)); response.Content.ShouldNotBeEmpty(); // Assert var actual = JsonSerializer.Deserialize <APIGatewayProxyResponse>(response.Content, options); actual.ShouldNotBeNull(); return(actual); }
public async Task Alexa_Function_Can_Process_Request() { // Arrange SkillRequest request = CreateRequest <LaunchRequest>(); request.Request.Type = "LaunchRequest"; string json = JsonConvert.SerializeObject(request); void Configure(IServiceCollection services) { services.AddLogging((builder) => builder.AddXUnit(this)); } using var server = new LambdaTestServer(Configure); using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2)); await server.StartAsync(cancellationTokenSource.Token); LambdaTestContext context = await server.EnqueueAsync(json); // Queue a task to stop the Lambda function as soon as the response is processed _ = Task.Run(async() => { await context.Response.WaitToReadAsync(cancellationTokenSource.Token); if (!cancellationTokenSource.IsCancellationRequested) { cancellationTokenSource.Cancel(); } }); using var httpClient = server.CreateClient(); // Act await FunctionEntrypoint.RunAsync(httpClient, cancellationTokenSource.Token); // Assert context.Response.TryRead(out LambdaTestResponse result).ShouldBeTrue(); result.ShouldNotBeNull(); result.IsSuccessful.ShouldBeTrue(); result.Duration.ShouldBeInRange(TimeSpan.FromTicks(1), TimeSpan.FromSeconds(1)); result.Content.ShouldNotBeEmpty(); json = await result.ReadAsStringAsync(); var actual = JsonConvert.DeserializeObject <SkillResponse>(json); actual.ShouldNotBeNull(); ResponseBody response = AssertResponse(actual, shouldEndSession: false); response.Card.ShouldBeNull(); response.Reprompt.ShouldBeNull(); response.OutputSpeech.ShouldNotBeNull(); response.OutputSpeech.Type.ShouldBe("SSML"); var ssml = response.OutputSpeech.ShouldBeOfType <SsmlOutputSpeech>(); ssml.Ssml.ShouldBe("<speak>Welcome to London Travel. You can ask me about disruption or for the status of any tube line, London Overground, the D.L.R. or T.F.L. Rail.</speak>"); }