Esempio n. 1
0
 public virtual IDictionary <string, string> ToDictionary()
 {
     return(new Dictionary <string, string>()
     {
         { "isSuccessful", IsSuccessful.ToString() },
         { "videoFilePath", VideoFilePath.ToString() },
         { "lastVideoName", LastVideoName.ToString() }
     });
 }
Esempio n. 2
0
    public async Task Function_Can_Process_Multiple_Requests()
    {
        // Arrange
        void Configure(IServiceCollection services)
        {
            services.AddLogging((builder) => builder.AddXUnit(this));
        }

        using var server = new LambdaTestServer(Configure);
        using var cts    = new CancellationTokenSource(TimeSpan.FromSeconds(2));

        await server.StartAsync(cts.Token);

        var channels = new List <(int Expected, LambdaTestContext Context)>();

        for (int i = 0; i < 10; i++)
        {
            var request = new MyRequest()
            {
                Values = Enumerable.Range(1, i + 1).ToArray(),
            };

            channels.Add((request.Values.Sum(), await server.EnqueueAsync(request)));
        }

        _ = Task.Run(async() =>
        {
            foreach ((var _, var context) in channels)
            {
                await context.Response.WaitToReadAsync(cts.Token);
            }

            if (!cts.IsCancellationRequested)
            {
                cts.Cancel();
            }
        });

        using var httpClient = server.CreateClient();

        // Act
        await MyFunctionEntrypoint.RunAsync(httpClient, cts.Token);

        // Assert
        foreach ((int expected, var context) in channels)
        {
            context.Response.TryRead(out var response).ShouldBeTrue();

            response.ShouldNotBeNull();
            response !.IsSuccessful.ShouldBeTrue();
            response.Content.ShouldNotBeNull();

            var deserialized = response.ReadAs <MyResponse>();
            deserialized.Sum.ShouldBe(expected);
        }
    }
Esempio n. 3
0
    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.");
    }
Esempio n. 4
0
    public async Task Function_Can_Process_Request_With_Mobile_Sdk_Headers()
    {
        // Arrange
        void Configure(IServiceCollection services)
        {
            services.AddLogging((builder) => builder.AddXUnit(this));
        }

        using var server = new LambdaTestServer(Configure);
        using var cts    = new CancellationTokenSource(TimeSpan.FromSeconds(2));

        await server.StartAsync(cts.Token);

        byte[] content = Encoding.UTF8.GetBytes(@"{""Values"": [ 1, 2, 3 ]}");

        var request = new LambdaTestRequest(content)
        {
            ClientContext   = "{}",
            CognitoIdentity = "{}",
        };

        var context = await server.EnqueueAsync(request);

        _ = Task.Run(async() =>
        {
            await context.Response.WaitToReadAsync(cts.Token);

            if (!cts.IsCancellationRequested)
            {
                cts.Cancel();
            }
        });

        using var httpClient = server.CreateClient();

        // Act
        await MyFunctionEntrypoint.RunAsync(httpClient, cts.Token);

        // Assert
        context.Response.TryRead(out var response).ShouldBeTrue();

        response.ShouldNotBeNull();
        response !.IsSuccessful.ShouldBeTrue();
    }
Esempio n. 5
0
    public async Task Function_Can_Process_Request()
    {
        // Arrange
        void Configure(IServiceCollection services)
        {
            services.AddLogging((builder) => builder.AddXUnit(this));
        }

        using var server = new LambdaTestServer(Configure);
        using var cts    = new CancellationTokenSource(TimeSpan.FromSeconds(2));

        await server.StartAsync(cts.Token);

        var context = await server.EnqueueAsync(@"{""Values"": [ 1, 2, 3 ]}");

        _ = Task.Run(async() =>
        {
            await context.Response.WaitToReadAsync(cts.Token);

            if (!cts.IsCancellationRequested)
            {
                cts.Cancel();
            }
        });

        using var httpClient = server.CreateClient();

        // Act
        await MyFunctionEntrypoint.RunAsync(httpClient, cts.Token);

        // Assert
        context.Response.TryRead(out var response).ShouldBeTrue();

        response.ShouldNotBeNull();
        response !.IsSuccessful.ShouldBeTrue();
        response.Content.ShouldNotBeNull();
        response.Duration.ShouldBeGreaterThan(TimeSpan.Zero);
        Encoding.UTF8.GetString(response.Content).ShouldBe(@"{""Sum"":6}");
    }
Esempio n. 6
0
        protected sealed override void setValue(object value)
        {
            var response = value as IRestResponse;

            if (Request != null)
            {
                Request.SetValue(response.Request);
            }

            if (ErrorMessage != null)
            {
                ErrorMessage.SetValue(response.ErrorMessage);
            }

            if (ResponseStatus != null)
            {
                ResponseStatus.SetValue(response.ResponseStatus);
            }

            if (Headers != null)
            {
                foreach (var header in Headers)
                {
                    var headerValue = response.Headers.FirstOrDefault(h => h.Name == header.Key);
                    if (headerValue != null)
                    {
                        header.Value.SetValue(headerValue.Value);
                    }
                }
            }

            if (Cookies != null)
            {
                foreach (var cookie in Cookies)
                {
                    var cookieValue = response.Cookies.FirstOrDefault(c => c.Name == cookie.Key);
                    if (cookieValue != null)
                    {
                        cookie.Value.SetValue(cookieValue.Value);
                    }
                }
            }

            if (Server != null)
            {
                Server.SetValue(response.Server);
            }

            if (ResponseUri != null)
            {
                ResponseUri.SetValue(response.ResponseUri);
            }

            if (ErrorException != null)
            {
                ErrorException.SetValue(response.ErrorException);
            }

            if (RawBytes != null)
            {
                RawBytes.SetValue(response.RawBytes);
            }

            if (IsSuccessful != null)
            {
                IsSuccessful.SetValue(response.IsSuccessful);
            }

            if (StatusCode != null)
            {
                StatusCode.SetValue(response.StatusCode);
            }

            if (Content != null)
            {
                Content.SetValue(response.Content);
            }

            if (ContentEncoding != null)
            {
                ContentEncoding.SetValue(response.ContentEncoding);
            }

            if (ContentLength != null)
            {
                ContentLength.SetValue(response.ContentLength);
            }

            if (ContentType != null)
            {
                ContentType.SetValue(response.ContentType);
            }

            if (StatusDescription != null)
            {
                StatusDescription.SetValue(response.StatusDescription);
            }

            if (ProtocolVersion != null)
            {
                ProtocolVersion.SetValue(response.ProtocolVersion);
            }

            setExtraValues(response);
        }
Esempio n. 7
0
    public async Task Can_Use_Custom_Function_Variables()
    {
        // Arrange
        LambdaTestServer.ClearLambdaEnvironmentVariables();

        var options = new LambdaTestServerOptions()
        {
            FunctionArn        = "my-custom-arn",
            FunctionHandler    = "my-custom-handler",
            FunctionMemorySize = 1024,
            FunctionName       = "my-function-name",
            FunctionTimeout    = TimeSpan.FromSeconds(119),
            FunctionVersion    = 42,
            LogGroupName       = "my-log-group",
            LogStreamName      = "my-log-stream",
        };

        using var server = new LambdaTestServer(options);
        using var cts    = new CancellationTokenSource(TimeSpan.FromSeconds(2));

        await server.StartAsync(cts.Token);

        var request = new LambdaTestRequest(Array.Empty <byte>(), "my-request-id")
        {
            ClientContext   = @"{""client"":{""app_title"":""my-app""}}",
            CognitoIdentity = @"{""cognitoIdentityId"":""my-identity""}",
        };

        var context = await server.EnqueueAsync(request);

        _ = Task.Run(async() =>
        {
            await context.Response.WaitToReadAsync(cts.Token);

            if (!cts.IsCancellationRequested)
            {
                cts.Cancel();
            }
        });

        using var httpClient = server.CreateClient();

        // Act
        await CustomFunction.RunAsync(httpClient, cts.Token);

        // Assert
        context.Response.TryRead(out var response).ShouldBeTrue();

        response.ShouldNotBeNull();
        response !.IsSuccessful.ShouldBeTrue();
        response.Content.ShouldNotBeNull();

        var lambdaContext = response.ReadAs <IDictionary <string, string> >();

        lambdaContext.ShouldContainKeyAndValue("AwsRequestId", request.AwsRequestId);
        lambdaContext.ShouldContainKeyAndValue("ClientContext", "my-app");
        lambdaContext.ShouldContainKeyAndValue("FunctionName", options.FunctionName);
        lambdaContext.ShouldContainKeyAndValue("FunctionVersion", "42");
        lambdaContext.ShouldContainKeyAndValue("IdentityId", "my-identity");
        lambdaContext.ShouldContainKeyAndValue("InvokedFunctionArn", options.FunctionArn);
        lambdaContext.ShouldContainKeyAndValue("LogGroupName", options.LogGroupName);
        lambdaContext.ShouldContainKeyAndValue("LogStreamName", options.LogStreamName);
        lambdaContext.ShouldContainKeyAndValue("MemoryLimitInMB", "1024");

        lambdaContext.ShouldContainKey("RemainingTime");
        string remainingTimeString = lambdaContext["RemainingTime"];

        TimeSpan.TryParse(remainingTimeString, out var remainingTime).ShouldBeTrue();

        remainingTime.Minutes.ShouldBe(options.FunctionTimeout.Minutes);
    }
Esempio n. 8
0
 public override int GetHashCode()
 {
     return(IsRetryable.GetHashCode() + IsSuccessful.GetHashCode());
 }