Beispiel #1
0
        public async Task TestSQSEventLambdaFunction()
        {
            var sqsEvent = new SQSEvent
            {
                Records = new List <SQSEvent.SQSMessage>
                {
                    new SQSEvent.SQSMessage
                    {
                        Body = "foobar"
                    }
                }
            };

            var logger  = new TestLambdaLogger();
            var context = new TestLambdaContext
            {
                Logger = logger
            };

            var function = new Function();
            await function.Handler(sqsEvent, context);

            Assert.Contains("Processed message foobar", logger.Buffer.ToString());
        }
Beispiel #2
0
        public void Should_return_404_for_not_matching_input()
        {
            var context  = new TestLambdaContext();
            var function = new Function();
            var response = function.FunctionHandler(new APIGatewayProxyRequest {
                Body = "TeaList"
            }, context);

            var expectedResponse = new APIGatewayProxyResponse
            {
                Body       = JsonConvert.SerializeObject("Not found"),
                StatusCode = 404,
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

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

            Assert.Equal(expectedResponse.Body, response.Body);
            Assert.Equal(expectedResponse.Headers, response.Headers);
            Assert.Equal(expectedResponse.StatusCode, response.StatusCode);
        }
Beispiel #3
0
        public string TestGenerateTokenUser()
        {
            TestLambdaContext       context = new TestLambdaContext();
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            dynamic body = new
            {
                email    = "*****@*****.**",
                password = "******"
            };

            request = new APIGatewayProxyRequest()
            {
                Body = JsonConvert.SerializeObject(body)
            };
            response = this.functions.GenerateTokenUser(request, context);

            output.WriteLine(response.Body);

            Assert.Equal(200, response.StatusCode);

            return(response.Body);
        }
Beispiel #4
0
        public async Task CreateCustomResourceWithHandlerTest()
        {
            // ARRANGE
            string AccountNumber      = "123456789012";
            string Region             = "us-east-1";
            string InputBucket        = $"{Environment.UserName}-rawvideo";
            string OutputBucket       = $"{Environment.UserName}-video";
            string PresignedUrlBucket = $"{Environment.UserName}-presigned-url-test";
            string ThumbnailBucket    = $"{Environment.UserName}-thumbnails";
            string IAMRole            = $"arn:aws:iam::{AccountNumber}:role/LambdaElasticTranscoderPipeline";
            string NotificationTopic  = $"arn:aws:sns:{Region}:{AccountNumber}:ElasticTranscoderNotifications";
            string Key = "result.txt";

            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";

            Mock <IAmazonS3> s3Client = new Mock <IAmazonS3>();

            s3Client.Setup(x => x.GetPreSignedURL(It.IsAny <GetPreSignedUrlRequest>())).Returns($"https://{PresignedUrlBucket}.s3.amazonaws.com/{Key}?AWSAccessKeyId=AKIA1234567890123456&Expires=1559247929&Signature=OTgL4H7i%2FQOcTFpLM%2AV2LsFjONE%3D");

            GetPreSignedUrlRequest preSignedUrlRequest = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = Key,
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = s3Client.Object.GetPreSignedURL(preSignedUrlRequest);
            string Json         = $@"
{{
""requestType"":""create"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::TestResource"",
""logicalResourceId"":""MyTestResource"",
""resourceProperties"":{{
""Role"":""{IAMRole}"",
""Name"":""TestPipeline"",
""InputBucket"":""{InputBucket}"",
""Notifications"":{{
""Error"": ""{NotificationTopic}"",
}},
""ContentConfig"":{{
""Bucket"":""{OutputBucket}""
}},
""ThumbnailConfig"":{{
""Bucket"":""{ThumbnailBucket}""
}}
}}
}}";

            Json = Json.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "");

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Create = async(request, context) =>
            {
                try
                {
                    //AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    //IAmazonElasticTranscoder Client = new AmazonElasticTranscoderClient(Config);
                    Mock <IAmazonElasticTranscoder> mockClient = new Mock <IAmazonElasticTranscoder>();
                    mockClient.Setup(x => x.CreatePipelineAsync(It.IsAny <CreatePipelineRequest>(), default(CancellationToken)))
                    .ReturnsAsync(new CreatePipelineResponse()
                    {
                        HttpStatusCode = HttpStatusCode.OK
                    });

                    context.LogInfo("Attempting to create a pipeline.");
                    CreatePipelineRequest  PipelineRequest = JsonConvert.DeserializeObject <CreatePipelineRequest>(JsonConvert.SerializeObject(request.ResourceProperties));
                    CreatePipelineResponse CreateResponse  = await mockClient.Object.CreatePipelineAsync(PipelineRequest);

                    if ((int)CreateResponse.HttpStatusCode < 200 || (int)CreateResponse.HttpStatusCode > 299)
                    {
                        return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)CreateResponse.HttpStatusCode}.", request));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   CreateResponse.Pipeline.Id,
                                   request.StackId,
                                   request.RequestId,
                                   request.LogicalResourceId,
                                   false,
                                   new Dictionary <string, object>()
                        {
                            { "Name", CreateResponse.Pipeline.Name },
                            { "Arn", CreateResponse.Pipeline.Arn },
                            { "Id", CreateResponse.Pipeline.Id }
                        }
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               Guid.NewGuid().ToString(),
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
                catch (Exception e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               Guid.NewGuid().ToString(),
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Update = async(request, context) =>
            {
                try
                {
                    context.LogInfo("Initiating update for pipeline.");

                    UpdatePipelineRequest PipelineRequest = JsonConvert.DeserializeObject <UpdatePipelineRequest>(JsonConvert.SerializeObject(request.ResourceProperties));

                    ListPipelinesRequest Listing = new ListPipelinesRequest();

                    List <Pipeline>       Pipelines = new List <Pipeline>();
                    ListPipelinesResponse Pipes;

                    AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    IAmazonElasticTranscoder      Client = new AmazonElasticTranscoderClient(Config);

                    do
                    {
                        Pipes = await Client.ListPipelinesAsync(Listing);

                        Pipelines.AddRange(Pipes.Pipelines.Where(x => x.Name.Equals(request.ResourceProperties["Name"] as string) &&
                                                                 x.InputBucket.Equals(request.ResourceProperties["InputBucket"]) &&
                                                                 x.Role.Equals(request.ResourceProperties["Role"])
                                                                 ));
                    } while (Pipes.NextPageToken != null);

                    if (Pipelines.Count > 1)
                    {
                        context.LogWarning($"{Pipelines.Count} pipelines were found matching the Name, InputBucket, and Role specified.");
                    }

                    if (Pipelines.Count > 0)
                    {
                        PipelineRequest.Id = Pipelines.First().Id;

                        UpdatePipelineResponse UpdateResponse = await Client.UpdatePipelineAsync(PipelineRequest);

                        if ((int)UpdateResponse.HttpStatusCode < 200 || (int)UpdateResponse.HttpStatusCode > 299)
                        {
                            return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)UpdateResponse.HttpStatusCode}.", request));
                        }
                        else
                        {
                            return(new CustomResourceResponse(
                                       CustomResourceResponse.RequestStatus.SUCCESS,
                                       $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                       request,
                                       false,
                                       new Dictionary <string, object>()
                            {
                                { "Name", UpdateResponse.Pipeline.Name },
                                { "Arn", UpdateResponse.Pipeline.Arn },
                                { "Id", UpdateResponse.Pipeline.Id }
                            }
                                       ));
                        }
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.FAILED,
                                   "No pipelines could be found with the matching characteristics.",
                                   request
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
                catch (Exception e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Delete = async(request, context) =>
            {
                try
                {
                    context.LogInfo("Attempting to delete a pipeline.");

                    ListPipelinesRequest Listing = new ListPipelinesRequest();

                    List <Pipeline>       Pipelines = new List <Pipeline>();
                    ListPipelinesResponse Pipes;

                    AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    IAmazonElasticTranscoder      Client = new AmazonElasticTranscoderClient(Config);

                    do
                    {
                        Pipes = await Client.ListPipelinesAsync(Listing);

                        Pipelines.AddRange(Pipes.Pipelines.Where(x => x.Name.Equals(request.ResourceProperties["Name"] as string) &&
                                                                 x.InputBucket.Equals(request.ResourceProperties["InputBucket"]) &&
                                                                 x.Role.Equals(request.ResourceProperties["Role"])
                                                                 ));
                    } while (Pipes.NextPageToken != null);

                    if (Pipelines.Count > 1)
                    {
                        context.LogWarning($"{Pipelines.Count} pipelines were found matching the Name, InputBucket, and Role specified.");
                    }

                    if (Pipelines.Count > 0)
                    {
                        DeletePipelineRequest PipelineRequest = new DeletePipelineRequest()
                        {
                            Id = Pipelines.First().Id
                        };

                        DeletePipelineResponse DeleteResponse = await Client.DeletePipelineAsync(PipelineRequest);

                        if ((int)DeleteResponse.HttpStatusCode < 200 || (int)DeleteResponse.HttpStatusCode > 299)
                        {
                            return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)DeleteResponse.HttpStatusCode}.", request));
                        }
                        else
                        {
                            return(new CustomResourceResponse(
                                       CustomResourceResponse.RequestStatus.SUCCESS,
                                       $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                       request,
                                       false
                                       ));
                        }
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   "No pipelines could be found with the matching characteristics.",
                                   request
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    // If the pipeline doesn't exist, consider it deleted
                    if (e.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   request
                                   ));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.FAILED,
                                   e.Message,
                                   request
                                   ));
                    }
                }
                catch (Exception e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
            };

            CustomResourceRequest        customResourceRequest = JsonConvert.DeserializeObject <CustomResourceRequest>(Json);
            Mock <ICustomResourceHelper> mockHelper            = new Mock <ICustomResourceHelper>();

            mockHelper.Setup(x => x.PutCustomResourceResponseAsync(It.IsAny <CustomResourceRequest>(), It.IsAny <CustomResourceResponse>()))
            .ReturnsAsync(new CustomResourceResult(customResourceRequest, new CustomResourceResponse(RequestStatus.SUCCESS, "", customResourceRequest), new HttpResponseMessage(HttpStatusCode.OK)));

            ICustomResourceHandler Handler = new CustomResourceFactory(Create, Update, Delete, mockHelper.Object);

            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName    = "ElasticTranscoderPipelineCreation",
                FunctionVersion = "1",
                Logger          = TestLogger,
                ClientContext   = ClientContext,
                LogGroupName    = "aws/lambda/ElasticTranscoderPipeline",
                LogStreamName   = Guid.NewGuid().ToString()
            };

            // ACT

            CustomResourceResult Response = await Handler.ExecuteAsync(customResourceRequest, Context);

            // ASSERT
            Assert.NotNull(Response);
            Assert.NotNull(Response.Response);
            Assert.NotNull(Response.S3Response);
            Assert.True(Response.IsSuccess);
        }
        public void TestGetId()
        {
            var lambdaFunction = new LambdaEntryPoint();

            var request = GetTestRequest("./SampleRequests/ValuesController-GetId.json");
            var context = new TestLambdaContext
            {
                FunctionName       = "ServerlessFunction",
                InvokedFunctionArn = "arn:aws:lambda:us-east-2:123456789012:function:my-function:1",
            };

            APIGatewayProxyResponse    response = null;
            IImmutableList <IMockSpan> spans    = null;
            const string propagatedTraceId      = "0123456789abceff";
            const string parentSpanId           = "0123456789abceff";

            try
            {
                TelemetryConfiguration.ContextPropagationEnabled = true;
                request.MultiValueHeaders = new Dictionary <string, IList <string> >
                {
                    { HttpHeaderNames.B3TraceId, new List <string> {
                          propagatedTraceId
                      } },
                    { HttpHeaderNames.B3SpanId, new List <string> {
                          parentSpanId
                      } },
                    { HttpHeaderNames.B3Sampled, new List <string> {
                          "1"
                      } },
                };

                spans = BackendMock.CollectSpans(
                    async() => response = await lambdaFunction.FunctionHandlerAsync(request, context));
            }
            finally
            {
                TelemetryConfiguration.ContextPropagationEnabled = false;
            }

            // Check response.
            Assert.Equal(200, response.StatusCode);
            Assert.Equal("value_56", response.Body);
            Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type"));
            Assert.Equal("text/plain; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]);

            // Check trace.
            Assert.Single(spans);
            var span = spans.First();

            Assert.Equal("api/Values/{id}", span.Name);
            Assert.True(span.Tags.TryGetValue("span.kind", out var spanKind));
            Assert.Equal("server", spanKind);
            Assert.True(span.Tags.TryGetValue("http.method", out var httpMethod));
            Assert.Equal("GET", httpMethod);

            // Check context propagation.
            Assert.Equal(propagatedTraceId, span.TraceId.ToString("x16"));
            Assert.True(span.ParentId.HasValue);
            Assert.Equal(parentSpanId, span.ParentId.Value.ToString("x16"));
        }
 private async Task <APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequest(TestLambdaContext context, string fileName)
 {
     return(await InvokeAPIGatewayRequestWithContent(context, GetRequestContent(fileName)));
 }
Beispiel #7
0
        public async Task TestCreate()
        {
            // ARRANGE
            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";

            string StreamName         = "test-stream";
            string PresignedUrlBucket = "pre-sign-url-bucket";
            string AccountNumber      = "123456789012";
            string Region             = "us-east-1";

            IAmazonS3 S3Client = new AmazonS3Client();

            GetPreSignedUrlRequest Req = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = "result.txt",
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = S3Client.GetPreSignedURL(Req);

            string Json = $@"
{{
""requestType"":""create"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::KinesisStreamAwaiter"",
""logicalResourceId"":""KinesisStreamAwaiter"",
""resourceProperties"":{{
""StreamName"":""{StreamName}""
}}
}}";


            CustomResourceRequest Request = JsonConvert.DeserializeObject <CustomResourceRequest>(Json);

            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName    = "KinesisStreamAwaiter",
                FunctionVersion = "1",
                Logger          = TestLogger,
                ClientContext   = ClientContext,
                LogGroupName    = "aws/lambda/KinesisStreamAwaiter",
                LogStreamName   = Guid.NewGuid().ToString(),
                RemainingTime   = TimeSpan.FromSeconds(300)
            };


            Entrypoint Entrypoint = new Entrypoint();

            // ACT
            IAmazonKinesis      KinesisClient = new AmazonKinesisClient();
            CreateStreamRequest CreateReq     = new CreateStreamRequest()
            {
                ShardCount = 1,
                StreamName = StreamName
            };


            CreateStreamResponse CreateResponse = await KinesisClient.CreateStreamAsync(CreateReq);

            try
            {
                CustomResourceResult Response = await Entrypoint.ExecuteAsync(Request, Context);

                // ASSERT

                Assert.True(Response.IsSuccess);
            }
            finally
            {
                DeleteStreamRequest DeleteReq = new DeleteStreamRequest()
                {
                    StreamName = StreamName
                };

                await KinesisClient.DeleteStreamAsync(DeleteReq);
            }
        }
        public async Task ExpenseTestAsync()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions(this.DDBClient, this.TableName);

            // Add a new expense
            Expense myExpense = new Expense();

            myExpense.Name         = "The awesome post";
            myExpense.Cost         = 3;
            myExpense.PurchaseDate = DateTime.Parse("06/08/2019");

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(myExpense)
            };
            context  = new TestLambdaContext();
            response = await functions.AddExpenseAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            var expenseId = response.Body;

            // Confirm we can get the expense back out
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, expenseId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetExpenseAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Expense readExpense = JsonConvert.DeserializeObject <Expense>(response.Body);

            Assert.Equal(myExpense.Name, readExpense.Name);
            Assert.Equal(myExpense.Cost, readExpense.Cost);
            Assert.Equal(myExpense.PurchaseDate, readExpense.PurchaseDate);

            // List the expenses
            request = new APIGatewayProxyRequest
            {
            };
            context  = new TestLambdaContext();
            response = await functions.GetExpensesAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Expense[] expense = JsonConvert.DeserializeObject <Expense[]>(response.Body);
            Assert.Single(expense);
            Assert.Equal(myExpense.Name, expense[0].Name);
            Assert.Equal(myExpense.Cost, expense[0].Cost);
            Assert.Equal(myExpense.PurchaseDate, expense[0].PurchaseDate);

            // Delete the expense
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, expenseId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.RemoveExpenseAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            // Make sure the post was deleted.
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, expenseId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetExpenseAsync(request, context);

            Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
        }
        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));
        }
Beispiel #10
0
        private async Task <APIGatewayProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent)
        {
            var lambdaFunction = new ApiGatewayLambdaFunction();
            var request        = JsonConvert.DeserializeObject <APIGatewayProxyRequest>(requestContent);

            return(await lambdaFunction.FunctionHandlerAsync(request, context));
        }
        private async Task <APIGatewayProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent)
        {
            var lambdaFunction = new ApiGatewayLambdaFunction();
            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));
        }
Beispiel #12
0
 public TestApp()
 {
     _handler = new LambdaHandler();
     _context = new TestLambdaContext();
 }
 public ValuesControllerTests()
 {
     _lambdaFunction    = new LambdaEntryPoint();
     _testLambdaContext = new TestLambdaContext();
 }
Beispiel #14
0
        public async Task TestToUpperFunction()
        {
            try
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient(RegionEndpoint.USEast1);
                string mdtexttest           = "{\r\n \"RatingDataAsOf\": \"20190828\",\r\n  \"KeyCurrency\": \"USD\",\r\n  \"KeyRatingCreditType\": \"CORP\",\r\n  \"CreditRatingDerivedCDS\": \"AAA\",\r\n  \"CDSBenchmarkSpread\": \"17.506131099768\",\r\n  \"CDSBenchmarkSpread1Day\": \"17.499652220154\",\r\n  \"CDSBenchmarkSpread7Day\": \"17.689977433049\",\r\n  \"CDSBenchmarkSpread30Day\": \"17.612596564917\",\r\n  \"CDSBenchmarkSpread90Day\": \"17.531741482981\",\r\n  \"CDSBenchmarkSpread1Year\": \"16.721663421274\",\r\n  \"CDSBenchmarkSpread2Year\": \"22.812501511208\",\r\n  \"CDSBenchmarkSpread3Year\": \"28.591981044712\",\r\n  \"RatingPublishDate\": \"08/29/2019\"\r\n}";

                var requestDel = new DeleteTableRequest
                {
                    TableName = "MDSSourceDynamoDBTest1"
                };

                //
                var responseDel = await client.DeleteTableAsync(requestDel);

                var requestDelDest = new DeleteTableRequest
                {
                    TableName = "MDSSourceDynamoDBDest1"
                };
                var responseDelDest = await client.DeleteTableAsync(requestDelDest);

                System.Threading.Thread.Sleep(3000);
                List <KeySchemaElement> schemadest = new List <KeySchemaElement>
                {
                    new KeySchemaElement
                    {
                        AttributeName = "GUID", KeyType = "HASH"
                    },
                    new KeySchemaElement
                    {
                        AttributeName = "Data", KeyType = "RANGE"
                    }
                };

                // Define key attributes:
                //  The key attributes "Author" and "Title" are string types
                List <AttributeDefinition> definitionsdest = new List <AttributeDefinition>
                {
                    new AttributeDefinition
                    {
                        AttributeName = "GUID", AttributeType = "S"
                    },
                    new AttributeDefinition
                    {
                        AttributeName = "Data", AttributeType = "S"
                    }
                };

                // Define table throughput:
                //  Table has capacity of 20 reads and 50 writes
                ProvisionedThroughput throughputdest = new ProvisionedThroughput
                {
                    ReadCapacityUnits  = 20,
                    WriteCapacityUnits = 50
                };

                // Configure the CreateTable request
                CreateTableRequest requestdest = new CreateTableRequest
                {
                    TableName             = "MDSSourceDynamoDBDest1",
                    KeySchema             = schemadest,
                    ProvisionedThroughput = throughputdest,
                    AttributeDefinitions  = definitionsdest
                };


                // View new table properties
                var tableDescriptiondest = await client.CreateTableAsync(requestdest);

                Table  Catologdest = Table.LoadTable(client, tableDescriptiondest.TableDescription.TableName);
                string status      = null;
                // Let us wait until table is created. Call DescribeTable.
                do
                {
                    System.Threading.Thread.Sleep(3000); // Wait 5 seconds.
                    try
                    {
                        var res = await client.DescribeTableAsync(new DescribeTableRequest
                        {
                            TableName = "MDSSourceDynamoDBDest1"
                        });

                        Console.WriteLine("Table name: {0}, status: {1}",
                                          res.Table.TableName,
                                          res.Table.TableStatus);
                        status = res.Table.TableStatus;
                    }
                    catch (ResourceNotFoundException)
                    {
                        // DescribeTable is eventually consistent. So you might
                        // get resource not found. So we handle the potential exception.
                    }
                } while (status != "ACTIVE");
                //var context = new TestLambdaContext();
                //var function = new Function();

                //function.FunctionHandler(null, context);

                // Define table schema:
                //  Table has a hash-key "Author" and a range-key "Title"
                List <KeySchemaElement> schema = new List <KeySchemaElement>
                {
                    new KeySchemaElement
                    {
                        AttributeName = "guid", KeyType = "HASH"
                    },
                    new KeySchemaElement
                    {
                        AttributeName = "Data", KeyType = "RANGE"
                    }
                };

                // Define key attributes:
                //  The key attributes "Author" and "Title" are string types
                List <AttributeDefinition> definitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition
                    {
                        AttributeName = "guid", AttributeType = "S"
                    },
                    new AttributeDefinition
                    {
                        AttributeName = "Data", AttributeType = "S"
                    }
                };

                // Define table throughput:
                //  Table has capacity of 20 reads and 50 writes
                ProvisionedThroughput throughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits  = 20,
                    WriteCapacityUnits = 50
                };

                // Configure the CreateTable request
                CreateTableRequest request = new CreateTableRequest
                {
                    TableName             = "MDSSourceDynamoDBTest1",
                    KeySchema             = schema,
                    ProvisionedThroughput = throughput,
                    AttributeDefinitions  = definitions
                };


                // View new table properties
                var tableDescription = await client.CreateTableAsync(request);

                Console.WriteLine("Table name: {0}", tableDescription.TableDescription.TableName);
                Console.WriteLine("Creation time: {0}", tableDescription.TableDescription.CreationDateTime);
                Console.WriteLine("Item count: {0}", tableDescription.TableDescription.ItemCount);
                Console.WriteLine("Table size (bytes): {0}", tableDescription.TableDescription.TableSizeBytes);
                Console.WriteLine("Table status: {0}", tableDescription.TableDescription.TableStatus);
                //dbList.Add()

                Table  Catolog    = Table.LoadTable(client, tableDescription.TableDescription.TableName);
                string statusdest = null;
                // Let us wait until table is created. Call DescribeTable.
                do
                {
                    System.Threading.Thread.Sleep(3000); // Wait 5 seconds.
                    try
                    {
                        var res = await client.DescribeTableAsync(new DescribeTableRequest
                        {
                            TableName = "MDSSourceDynamoDBTest1"
                        });

                        Console.WriteLine("Table name: {0}, status: {1}",
                                          res.Table.TableName,
                                          res.Table.TableStatus);
                        statusdest = res.Table.TableStatus;
                    }
                    catch (ResourceNotFoundException)
                    {
                        // DescribeTable is eventually consistent. So you might
                        // get resource not found. So we handle the potential exception.
                    }
                } while (statusdest != "ACTIVE");
                Console.WriteLine("\n*** listing tables ***");

                var data = new Document();
                data["guid"]           = Guid.NewGuid().ToString();
                data["Data"]           = mdtexttest;
                data["RSMappedValues"] = "CORP";
                data["timestamp"]      = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                data["UniqueRow"]      = Convert.ToInt64(String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000));
                data["Error"]          = "RS Mapping Missing";
                Document response = await Catolog.PutItemAsync(data);

                var context       = new TestLambdaContext();
                var function      = new Function();
                var responseFinal = await function.FunctionHandler(null, context);

                Assert.Equal(responseFinal, null);
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #15
0
        public async Task CustomersTestAsync()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            CustomerFunctions functions = new CustomerFunctions(this.DDBClient, this.TableName);


            // Add a new blog post
            Customers cust = new Customers();

            cust.Name  = "The awesome post";
            cust.Email = "Content for the awesome blog";

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(cust)
            };
            context  = new TestLambdaContext();
            response = await functions.AddCustomerAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            var blogId = response.Body;

            // Confirm we can get the blog post back out
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { CustomerFunctions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetCustomerAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Customers read = JsonConvert.DeserializeObject <Customers>(response.Body);


            // List the blog posts
            request = new APIGatewayProxyRequest
            {
            };
            context  = new TestLambdaContext();
            response = await functions.GetCustomersAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Customers[] blogPosts = JsonConvert.DeserializeObject <Customers[]>(response.Body);
            Assert.Single(blogPosts);



            // Delete the blog post
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { CustomerFunctions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.RemoveCustomerAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            // Make sure the post was deleted.
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { CustomerFunctions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetCustomerAsync(request, context);

            Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #16
0
 public async Task TetGetMethod()
 {
     var functions = new Functions();
     var context   = new TestLambdaContext();
     await functions.Retweet(context);
 }
Beispiel #17
0
        public void handleRequest()
        {
            DynamoDBEvent evnt = new DynamoDBEvent
            {
                Records = new List <DynamoDBEvent.DynamodbStreamRecord>
                {
                    // Test Record for the user to enter the store
                    new DynamoDBEvent.DynamodbStreamRecord
                    {
                        AwsRegion = "us-east-1",
                        EventName = "MODIFY",
                        Dynamodb  = new StreamRecord
                        {
                            ApproximateCreationDateTime = DateTime.Now,
                            Keys = new Dictionary <string, AttributeValue> {
                                { "Id", new AttributeValue {
                                      N = "1"
                                  } }
                            },
                            NewImage = new Dictionary <string, AttributeValue> {
                                { "StoreLocation", new AttributeValue {
                                      S = "entrance"
                                  } }
                            },
                            OldImage = new Dictionary <string, AttributeValue> {
                                { "StoreLocation", new AttributeValue {
                                      S = ""
                                  } }
                            },
                            StreamViewType = StreamViewType.NEW_AND_OLD_IMAGES
                        }
                    },
                    // Test Record for the user to move from entrance to aisle
                    new DynamoDBEvent.DynamodbStreamRecord
                    {
                        AwsRegion = "us-east-1",
                        EventName = "MODIFY",
                        Dynamodb  = new StreamRecord
                        {
                            ApproximateCreationDateTime = DateTime.Now,
                            Keys = new Dictionary <string, AttributeValue> {
                                { "Id", new AttributeValue {
                                      N = "2"
                                  } }
                            },
                            NewImage = new Dictionary <string, AttributeValue> {
                                { "StoreLocation", new AttributeValue {
                                      S = "aisle1"
                                  } }
                            },
                            OldImage = new Dictionary <string, AttributeValue> {
                                { "StoreLocation", new AttributeValue {
                                      S = "entrance"
                                  } }
                            },
                            StreamViewType = StreamViewType.NEW_AND_OLD_IMAGES
                        }
                    }
                }
            };

            var context  = new TestLambdaContext();
            var function = new Function();

            function.FunctionHandler(evnt, context);

            var testLogger = context.Logger as TestLambdaLogger;

            Assert.Contains("Stream processing complete", testLogger.Buffer.ToString());
        }
        public CreateSessionWithSmsWorkflowTests()
        {
            Environment.SetEnvironmentVariable("TWILIO_ACCOUNTSID", "ACxxxxxxxxxxxxxx");
            Environment.SetEnvironmentVariable("TWILIO_AUTHTOKEN", "TestAuthTokenValue");
            context      = new TestLambdaContext();
            connectEvent = JObject.Parse(
                @"{
    ""Details"": {
      ""ContactData"": {
        ""Attributes"": {},
        ""Channel"": ""VOICE"",
        ""ContactId"": ""ASDAcxcasDFSSDFs"",
        ""CustomerEndpoint"": {
          ""Address"": ""+17202950840"",
          ""Type"": ""TELEPHONE_NUMBER""
        },
        ""InitialContactId"": ""ASDAcxcasDFSSDFs"",
        ""InitiationMethod"": ""INBOUND"",
        ""InstanceARN"": """",
        ""PreviousContactId"": """",
        ""Queue"": null,
        ""SystemEndpoint"": {
          ""Address"": ""+18582016694"",
          ""Type"": ""TELEPHONE_NUMBER""
        }
      },
      ""Parameters"": {
        ""RequestName"": ""CreateSessionWithSms"",
        ""SmsMessage"": ""Tap this link to start ChoiceView: http://choiceview.com/start.html?account=radish1&phone=""
      }
    },
    ""Name"": ""ContactFlowEvent""
  }");
            connectEventWithoutSmsMessage = JObject.Parse(
                @"{
    ""Details"": {
      ""ContactData"": {
        ""Attributes"": {},
        ""Channel"": ""VOICE"",
        ""ContactId"": ""ASDAcxcasDFSSDFs"",
        ""CustomerEndpoint"": {
          ""Address"": ""+17202950840"",
          ""Type"": ""TELEPHONE_NUMBER""
        },
        ""InitialContactId"": ""ASDAcxcasDFSSDFs"",
        ""InitiationMethod"": ""INBOUND"",
        ""InstanceARN"": """",
        ""PreviousContactId"": """",
        ""Queue"": null,
        ""SystemEndpoint"": {
          ""Address"": ""+18582016694"",
          ""Type"": ""TELEPHONE_NUMBER""
        }
      },
      ""Parameters"": {
        ""RequestName"": ""CreateSessionWithSms"",
      }
    },
    ""Name"": ""ContactFlowEvent""
  }");

            connectEventWithoutClientUrl = JObject.Parse(
                @"{
    ""Details"": {
      ""ContactData"": {
        ""Attributes"": {},
        ""Channel"": ""VOICE"",
        ""ContactId"": ""ASDAcxcasDFSSDFs"",
        ""CustomerEndpoint"": {
          ""Address"": ""+17202950840"",
          ""Type"": ""TELEPHONE_NUMBER""
        },
        ""InitialContactId"": ""ASDAcxcasDFSSDFs"",
        ""InitiationMethod"": ""INBOUND"",
        ""InstanceARN"": """",
        ""PreviousContactId"": """",
        ""Queue"": null,
        ""SystemEndpoint"": {
          ""Address"": ""+18582016694"",
          ""Type"": ""TELEPHONE_NUMBER""
        }
      },
      ""Parameters"": {
        ""RequestName"": ""CreateSessionWithSms"",
        ""SmsMessage"": ""Welcome to the unit test!""
      }
    },
    ""Name"": ""ContactFlowEvent""
  }");
        }
Beispiel #19
0
        public async Task BlogTestAsync()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions(this.DDBClient, this.TableName);


            // Add a new blog post
            Blog myBlog = new Blog();

            myBlog.Name    = "The awesome post";
            myBlog.Content = "Content for the awesome blog";

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(myBlog)
            };
            context  = new TestLambdaContext();
            response = await functions.AddBlogAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            var blogId = response.Body;

            // Confirm we can get the blog post back out
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetBlogAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Blog readBlog = JsonConvert.DeserializeObject <Blog>(response.Body);

            Assert.Equal(myBlog.Name, readBlog.Name);
            Assert.Equal(myBlog.Content, readBlog.Content);

            // List the blog posts
            request = new APIGatewayProxyRequest
            {
            };
            context  = new TestLambdaContext();
            response = await functions.GetBlogsAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Blog[] blogPosts = JsonConvert.DeserializeObject <Blog[]>(response.Body);
            Assert.Single(blogPosts);
            Assert.Equal(myBlog.Name, blogPosts[0].Name);
            Assert.Equal(myBlog.Content, blogPosts[0].Content);


            // Delete the blog post
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.RemoveBlogAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            // Make sure the post was deleted.
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.ID_QUERY_STRING_NAME, blogId }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetBlogAsync(request, context);

            Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
        }
 private void GivenLambdaContext()
 {
     this.context = new TestLambdaContext();
 }
        public async Task ExpensesFilterTestAsync()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions(this.DDBClient, this.TableName);

            // Add a new expense
            Expense myExpense = new Expense();

            myExpense.Name         = "Coffee";
            myExpense.Cost         = 3;
            myExpense.PurchaseDate = DateTime.Parse("06/08/2019");

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(myExpense)
            };
            context  = new TestLambdaContext();
            response = await functions.AddExpenseAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            // Add second expense
            Expense myExpense2 = new Expense();

            myExpense2.Name         = "Lunch";
            myExpense2.Cost         = 3;
            myExpense2.PurchaseDate = DateTime.Parse("06/14/2019");

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(myExpense2)
            };
            await functions.AddExpenseAsync(request, context);

            // Add third expense
            Expense myExpense3 = new Expense();

            myExpense3.Name         = "Lunch";
            myExpense3.Cost         = 3;
            myExpense3.PurchaseDate = DateTime.Parse("06/20/2019");

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(myExpense3)
            };
            await functions.AddExpenseAsync(request, context);

            // List the expenses
            request = new APIGatewayProxyRequest
            {
            };
            context  = new TestLambdaContext();
            response = await functions.GetExpensesAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            Expense[] expense = JsonConvert.DeserializeObject <Expense[]>(response.Body);
            Assert.Equal(3, expense.Count());

            // List expenses with specified date range
            request = new APIGatewayProxyRequest
            {
                PathParameters = new Dictionary <string, string> {
                    { Functions.DATE_FROM_QUERY_STRING_NAME, "06/13/2019" },
                    { Functions.DATE_TO_QUERY_STRING_NAME, "06/19/2019" }
                }
            };
            context  = new TestLambdaContext();
            response = await functions.GetExpensesAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            expense = JsonConvert.DeserializeObject <Expense[]>(response.Body);
            Assert.Single(expense);
            Assert.Equal(myExpense2.Name, expense[0].Name);
            Assert.Equal(myExpense2.Cost, expense[0].Cost);
            Assert.Equal(myExpense2.PurchaseDate, expense[0].PurchaseDate);
        }
Beispiel #22
0
        private static SkillResponse ExecuteFunction(SkillRequest request, TestLambdaContext context)
        {
            var function = new PerfectGymFunction();

            return(function.FunctionHandler(request, context));
        }
Beispiel #23
0
        public async Task TestSourceFunctionAsyncRSMapIssue()
        {
            // Invoke the lambda function and confirm the string was upper cased.
            AmazonDynamoDBClient    client = new AmazonDynamoDBClient(RegionEndpoint.USEast1);
            List <KeySchemaElement> schema = new List <KeySchemaElement>
            {
                new KeySchemaElement
                {
                    AttributeName = "guid", KeyType = "HASH"
                },
                new KeySchemaElement
                {
                    AttributeName = "Data", KeyType = "RANGE"
                }
            };

            // Define key attributes:
            //  The key attributes "Author" and "Title" are string types
            List <AttributeDefinition> definitions = new List <AttributeDefinition>
            {
                new AttributeDefinition
                {
                    AttributeName = "guid", AttributeType = "S"
                },
                new AttributeDefinition
                {
                    AttributeName = "Data", AttributeType = "S"
                }
            };

            // Define table throughput:
            //  Table has capacity of 20 reads and 50 writes
            ProvisionedThroughput throughput = new ProvisionedThroughput
            {
                ReadCapacityUnits  = 20,
                WriteCapacityUnits = 50
            };

            // Configure the CreateTable request
            CreateTableRequest request = new CreateTableRequest
            {
                TableName             = "MDSSourceDynamoDBTestDat1",
                KeySchema             = schema,
                ProvisionedThroughput = throughput,
                AttributeDefinitions  = definitions
            };


            // View new table properties
            var tableDescription = await client.CreateTableAsync(request);

            Console.WriteLine("Table name: {0}", tableDescription.TableDescription.TableName);
            Console.WriteLine("Creation time: {0}", tableDescription.TableDescription.CreationDateTime);
            Console.WriteLine("Item count: {0}", tableDescription.TableDescription.ItemCount);
            Console.WriteLine("Table size (bytes): {0}", tableDescription.TableDescription.TableSizeBytes);
            Console.WriteLine("Table status: {0}", tableDescription.TableDescription.TableStatus);
            //dbList.Add()

            Table  Catolog = Table.LoadTable(client, tableDescription.TableDescription.TableName);
            string status  = null;

            // Let us wait until table is created. Call DescribeTable.
            do
            {
                System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
                try
                {
                    var res = await client.DescribeTableAsync(new DescribeTableRequest
                    {
                        TableName = "MDSSourceDynamoDBTestDat1"
                    });

                    Console.WriteLine("Table name: {0}, status: {1}",
                                      res.Table.TableName,
                                      res.Table.TableStatus);
                    status = res.Table.TableStatus;
                }
                catch (ResourceNotFoundException)
                {
                    // DescribeTable is eventually consistent. So you might
                    // get resource not found. So we handle the potential exception.
                }
            } while (status != "ACTIVE");
            Console.WriteLine("\n*** listing tables ***");

            IAmazonS3 s3Client              = new AmazonS3Client(RegionEndpoint.USEast1);
            string    inputData             = "#BUSINESS_DATE|CURRENCY|CREDIT_TYPE|RATINGS|TODAY|DAY_1|DAYS_7|DAYS_30|DAYS_90|DAYS_365|YEARS_2|YEARS_3|LOAD_DATE\n20190828|USD|CORPS|AAA|17.506131099768|17.499652220154|17.689977433049|17.612596564917|17.531741482981|16.721663421274|22.812501511208|28.591981044712|08/29/2019";
            var       destinationBucketName = "spgmi-dest-buck-test";
            var       bucketName            = "spgi-mds-data-dev-test2".ToLower();
            var       key = "MDR_EQUITY_PDR_ZSCORE_INCR_20191217032542.txt";

            // Create a bucket an object to setup a test data.
            await s3Client.PutBucketAsync(destinationBucketName);

            try
            {
                await s3Client.PutObjectAsync(new PutObjectRequest
                {
                    BucketName  = bucketName,
                    Key         = key,
                    ContentBody = inputData
                });

                // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function.
                var s3Event = new S3Event
                {
                    Records = new List <S3EventNotification.S3EventNotificationRecord>
                    {
                        new S3EventNotification.S3EventNotificationRecord
                        {
                            S3 = new S3EventNotification.S3Entity
                            {
                                Bucket = new S3EventNotification.S3BucketEntity {
                                    Name = bucketName
                                },
                                Object = new S3EventNotification.S3ObjectEntity {
                                    Key = key
                                }
                            }
                        }
                    }
                };
                var context = new TestLambdaContext();
                // Invoke the lambda function and confirm the content type was returned.
                var function    = new Function(s3Client);
                var contentType = await function.FunctionHandler(s3Event, context);

                Assert.Equal("text/plain", contentType);
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #24
0
        public async void TestUpdatingAgentStateChange()
        {
            Environment.SetEnvironmentVariable(WRITE_EVENTS_TO_QUEUE_ENVIRONMENT_VARIABLE_LOOKUP, true.ToString());

            string recordData = @" {
    'AWSAccountId': '236630710668',
            'AgentARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/agent/dfe8970a-ee78-4fa2-b79b-b6b3e92d35c0',
            'CurrentAgentSnapshot': {
                'AgentStatus': {
                    'ARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/agent-state/24728943-1643-4181-9844-6aec6e981563',
                    'Name': 'Available',
                    'StartTimestamp': '2018-05-16T16:23:19.019Z'
                },
                'Configuration': {
                    'AgentHierarchyGroups': null,
                    'FirstName': 'Christy',
                    'LastName': 'Burkholder',
                    'RoutingProfile': {
                        'ARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/routing-profile/12d022b9-6480-4fd4-b5b9-ca72bc66e8a1',
                        'DefaultOutboundQueue': {
                            'ARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/queue/c5407123-79de-4df1-8afd-fb74a5df5162',
                            'Name': 'BasicQueue'
                        },
                        'InboundQueues': [
                        {
                            'ARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/queue/c5407123-79de-4df1-8afd-fb74a5df5162',
                            'Name': 'BasicQueue'
                        }
                        ],
                        'Name': 'Basic Routing Profile'
                    },
                    'Username': '******'
                },
                'Contacts': []
            },
            'EventId': '7315b213-f9c3-4362-b2d6-e26c79dbd3ea',
            'EventTimestamp': '2018-05-16T16:23:19.019Z',
            'EventType': 'STATE_CHANGE',
            'InstanceARN': 'arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef',
            'PreviousAgentSnapshot': null,
            'Version': '2017-10-01'
        }";

            ConnectKinesisEventRecord loginRecord = new ConnectKinesisEventRecord()
            {
                AgentARN =
                    "arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/agent/dfe8970a-ee78-4fa2-b79b-b6b3e92d35c0",
                AgentUsername            = null,
                CurrentState             = null,
                LastEventTimeStamp       = Convert.ToDateTime("2018-05-16T16:12:59.059"),
                LastStateChangeTimeStamp = null,
                RawAgentEventJSon        = recordData
            };

            ConnectKinesisEventRecord stateChangeAvailableRecord = new ConnectKinesisEventRecord()
            {
                AgentARN =
                    "arn:aws:connect:us-east-1:236630710668:instance/6e3230e5-2dd2-4464-ade8-b032cdd0abef/agent/dfe8970a-ee78-4fa2-b79b-b6b3e92d35c0",
                AgentUsername            = "******",
                CurrentState             = "Available",
                LastEventTimeStamp       = Convert.ToDateTime("2018-05-16T16:23:19.019"),
                LastStateChangeTimeStamp = Convert.ToDateTime("2018-05-16T16:23:19.019"),
                RawAgentEventJSon        = recordData
            };

            var evnt = GenerateKinesisEvent(recordData);

            var context = new TestLambdaContext()
            {
                Logger = new FakeLambdaLogger()
            };
            FakeDynamoDBContext fakeDbContext = new FakeDynamoDBContext();
            FakeSQSFacade       fakeSqsFacade = new FakeSQSFacade();

            await fakeDbContext.SaveAsync(loginRecord);

            var function = new ProcessKinesisEvents(fakeDbContext, fakeSqsFacade);
            await function.AspectKinesisHandler(evnt, context);

            ConnectKinesisEventRecord dynamoRecord = fakeDbContext.DynamoTable[stateChangeAvailableRecord.AgentARN];

            AssertExpectedRecordAgainstDynamoRecord(stateChangeAvailableRecord, dynamoRecord);
        }
        public async Task LPTestAsync()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request = new APIGatewayProxyRequest();
            APIGatewayProxyResponse response;


            // Add a new LP post
            LP myLP = new LP
            {
                Id             = new Guid(),
                MeterPointCode = 555555
            };

            LP myLP1 = new LP
            {
                Id             = new Guid(),
                MeterPointCode = 77777
            };


            List <LP> myLpsList = new List <LP>
            {
                myLP,
                myLP1
            };

            IEnumerable <LP> myLps = myLpsList.AsEnumerable();

            var mock = new Mock <Interfaces.ILPService>();

            mock.Setup(x => x.AddLPs(myLps));
            mock.Setup(x => x.GetLPs())
            .Returns(Task.FromResult(myLps));

            var repository = mock.Object;

            Functions functions = new Functions(repository, null);

            LPS body = new LPS
            {
                Lp = new List <LP> {
                    myLP1
                }
            };

            request = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(body)
            };
            context  = new TestLambdaContext();
            response = await functions.AddLPsAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            var LPId = response.Body;

            context  = new TestLambdaContext();
            response = await functions.GetLPsAsync(request, context);

            Assert.Equal(200, response.StatusCode);

            var readLP = JsonConvert.DeserializeObject <List <LP> >(response.Body);

            Assert.Equal(myLP.MeterPointCode, readLP[0].MeterPointCode);
            Assert.Equal(myLP1.MeterPointCode, readLP[1].MeterPointCode);
        }
Beispiel #26
0
        private async Task TestManifestFile()
        {
            // ARRANGE
            string            Json          = $@"
{{
    ""Records"": [
      {{
        ""eventVersion"": ""2.0"",
        ""eventSource"": ""aws:s3"",
        ""awsRegion"": ""{Region}"",
        ""eventTime"": ""2018-10-01T01:00:00.000Z"",
        ""eventName"": ""ObjectCreated:Put"",
        ""userIdentity"": {{
          ""principalId"": ""EXAMPLE""
        }},
        ""requestParameters"": {{
          ""sourceIPAddress"": ""127.0.0.1""
        }},
        ""responseElements"": {{
          ""x-amz-request-id"": ""EXAMPLE123456789"",
          ""x-amz-id-2"": ""EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH""
        }},
        ""s3"": {{
          ""s3SchemaVersion"": ""1.0"",
          ""configurationId"": ""testConfigRule"",
          ""bucket"": {{
            ""name"": ""{SourceBucket}"",
            ""ownerIdentity"": {{
              ""principalId"": ""EXAMPLE""
            }},
            ""arn"": ""arn:{AWSPartition}:s3:::{SourceBucket}""
          }},
          ""object"": {{
            ""key"": ""{SourceManifestKey}"",
            ""size"": 7658,
            ""eTag"": ""0409fb62239b5d5daa27a2a1982c4dc2"",
            ""sequencer"": ""0A1B2C3D4E5F678901""
          }}
      }}
    }}
  ]
}}
";
            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName       = "CURManager",
                FunctionVersion    = "1",
                Logger             = TestLogger,
                ClientContext      = ClientContext,
                LogGroupName       = "aws/lambda/CURManager",
                LogStreamName      = Guid.NewGuid().ToString(),
                RemainingTime      = TimeSpan.FromSeconds(300),
                InvokedFunctionArn = $"arn:{AWSPartition}:lambda:{Region}:{AccountNumber}:function:CURManager"
            };

            S3Event Event = JsonConvert.DeserializeObject <S3Event>(Json);

            Environment.SetEnvironmentVariable("DESTINATION_S3_BUCKET", DestinationBucket);

            Entrypoint Entry = new Entrypoint();

            // ACT

            await Entry.Exec(Event, Context);

            // ASSERT

            // No exception
        }
        private async Task <APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent)
        {
            var lambdaFunction = new TestWebApp.HttpV2LambdaFunction();
            var requestStream  = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent));

#if NETCOREAPP_2_1
            var request = new Amazon.Lambda.Serialization.Json.JsonSerializer().Deserialize <APIGatewayHttpApiV2ProxyRequest>(requestStream);
#else
            var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize <APIGatewayHttpApiV2ProxyRequest>(requestStream);
#endif
            return(await lambdaFunction.FunctionHandlerAsync(request, context));
        }
Beispiel #28
0
        public async Task Start()
        {
            if (RequestHandler == null)
            {
                throw new Exception("Cannot start server, SillyProxyHandler cannot be null");
            }

            Console.WriteLine("Starting build server on " + IP.ToString() + ":" + Port + ":" + Directory.GetCurrentDirectory());

            Listener = new TcpListener(IP, Port);

            Listener.Start();

            while (true)
            {
                string            consoleStr = string.Empty;
                Socket            socket     = null;
                SillyHttpResponse response   = new SillyHttpResponse(SillyHttpStatusCode.Success, Encoding.ASCII.GetBytes(TestPayload), SillyMimeType.TextHtml);

                try
                {
                    socket = await Listener.AcceptSocketAsync();

                    if (socket == null)
                    {
                        throw new Exception("Incoming connection is null");
                    }

                    consoleStr += socket.RemoteEndPoint + " -- [" + DateTime.Now.ToString() + "] ";

                    if (socket.Connected)
                    {
                        Byte[] receiveData = new Byte[1024];

                        socket.Receive(receiveData, receiveData.Length, 0);

                        string buffer = Encoding.ASCII.GetString(receiveData);

                        SillyHttpRequestParser request = new SillyHttpRequestParser(buffer);

                        if (request.Ignore)
                        {
                            consoleStr += "-> Empty request received, ignoring";

                            continue;
                        }

                        if (request.IsInvalid)
                        {
                            consoleStr += "-> " + request.InvalidReason + " ";

                            continue;
                        }

                        consoleStr += request.Method + " " + request.URL + " " + request.Version;// + " : PROXY " + request.httpMethod + " " + request.path + " " + request.QueryToString();

                        string normalizedRequest = Directory.GetCurrentDirectory() + request.URL.Trim().ToLower();

                        // figure out if request should be proxied or not. Probably be configurable by the user sometime in the future.

                        if (!File.Exists(normalizedRequest))
                        {
                            consoleStr += " : PROXY " + request.httpMethod + " " + request.path + " " + request.QueryToString();

                            TestLambdaContext lambdaContext = new TestLambdaContext();

                            response.ProxyResponse = RequestHandler.Handle(request, lambdaContext);
                        }
                        else
                        {
                            FileInfo      requestedFile = new FileInfo(normalizedRequest);
                            SillyResource resource      = new SillyResource(requestedFile);

                            response.Payload = resource.Contents();

                            switch (resource.Type)
                            {
                            case SillyResource.Types.CSS:
                                response.ProxyResponse.headers.ContentType = SillyMimeType.TextCss;
                                break;

                            case SillyResource.Types.JS:
                                response.ProxyResponse.headers.ContentType = SillyMimeType.ApplicationJavascript;
                                break;

                            default:
                                break;
                            }
                        }

                        consoleStr += " RESOLVED ";
                    }
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    consoleStr += "-> Exception: " + ex.Message + " ";
                }
                finally
                {
                    response.SendResponse(socket);

                    consoleStr += response.ProxyResponse.statusCode;

                    Console.WriteLine(consoleStr);
                    Console.ResetColor();

                    if (socket != null && socket.Connected)
                    {
                        socket.Dispose();
                    }
                }
            }
        }
 public FunctionTest()
 {
     _function = new Function();
     _context  = new TestLambdaContext();
 }
 public IncomeTaxCalculatorTest()
 {
     function = new IncomeTaxCalculator();
     context  = new TestLambdaContext();
 }