public async Task TestServerlessPackage()
        {
            var logger   = new TestToolLogger();
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp");
            var command  = new PackageCICommand(logger, fullPath, new string[0]);

            command.Region                       = "us-west-2";
            command.Configuration                = "Release";
            command.TargetFramework              = "netcoreapp2.1";
            command.CloudFormationTemplate       = "serverless.template";
            command.CloudFormationOutputTemplate = Path.Combine(Path.GetTempPath(), "output-serverless.template");
            command.S3Bucket                     = "serverless-package-test-" + DateTime.Now.Ticks;
            command.DisableInteractive           = true;

            if (File.Exists(command.CloudFormationOutputTemplate))
            {
                File.Delete(command.CloudFormationOutputTemplate);
            }


            await command.S3Client.PutBucketAsync(command.S3Bucket);

            try
            {
                Assert.True(await command.ExecuteAsync());
                Assert.True(File.Exists(command.CloudFormationOutputTemplate));
            }
            finally
            {
                await AmazonS3Util.DeleteS3BucketWithObjectsAsync(command.S3Client, command.S3Bucket);
            }
        }
        public void NETCore_2_1_AllWithTooNewVersionNumber()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest-v2.1.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NETCore_2_1_AllWithTooNewVersionNumber.xml");


            try
            {
                LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
                Assert.True(true, "Missing LambdaToolsException thrown");
            }
            catch (LambdaToolsException e)
            {
                Assert.Contains("which is newer than", e.Message);
            }


            projectFile = projectFile.Replace("Microsoft.AspNetCore.All", "Microsoft.AspNetCore.App");
            try
            {
                LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
                Assert.True(true, "Missing LambdaToolsException thrown");
            }
            catch (LambdaToolsException e)
            {
                Assert.Contains("which is newer than", e.Message);
            }
        }
        public async Task FunctionImmediateAvailable()
        {
            var functionName = "fakeFunction";

            var mockLambda = new Mock <IAmazonLambda>();

            mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny <GetFunctionConfigurationRequest>(), It.IsAny <CancellationToken>()))
            .Callback <GetFunctionConfigurationRequest, CancellationToken>((request, token) =>
            {
                Assert.Equal(functionName, request.FunctionName);
            })
            .Returns((GetFunctionConfigurationRequest r, CancellationToken token) =>
            {
                return(Task.FromResult(new GetFunctionConfigurationResponse
                {
                    State = State.Active,
                    LastUpdateStatus = LastUpdateStatus.Successful
                }));
            });

            var logger = new TestToolLogger();
            await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName);

            Assert.Equal(0, logger.Buffer.Length);
        }
Exemplo n.º 4
0
        public void NewerAspNetCoreReference()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NewerAspNetCoreReference.xml");

            Assert.Throws <LambdaToolsException>(() => Utilities.ValidateMicrosoftAspNetCoreAllReferenceWithManifest(logger, manifest, projectFile));
        }
        public void FindProjFiles(string projectDirectory)
        {
            var    logger   = new TestToolLogger();
            string manifest = LambdaUtilities.LoadPackageStoreManifest(logger, "netcoreapp2.0");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectPath(logger, "netcoreapp2.0", manifest, projectDirectory);

            Assert.DoesNotContain("error", logger.Buffer.ToLower());
        }
Exemplo n.º 6
0
        public void NotUsingAspNetCore()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/CurrentAspNetCoreReference.xml");

            Utilities.ValidateMicrosoftAspNetCoreAllReferenceWithManifest(logger, manifest, projectFile);

            Assert.DoesNotContain("error", logger.Buffer.ToLower());
        }
        public void NETCore_2_0_NotUsingAspNetCore()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/CurrentAspNetCoreReference.xml");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.0", manifest, projectFile);

            Assert.DoesNotContain("error", logger.Buffer.ToLower());
        }
        public void NETCore_2_1_AllWithSupportedVersionNumber()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest-v2.1.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NETCore_2_1_AllWithSupportedVersionNumber.xml");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);

            projectFile = projectFile.Replace("Microsoft.AspNetCore.All", "Microsoft.AspNetCore.App");
            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
        }
Exemplo n.º 9
0
        public async Task TestServerlessPackage()
        {
            var logger   = new TestToolLogger();
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp");
            var command  = new PackageCICommand(logger, fullPath, new string[0]);

            command.Region                       = "us-west-2";
            command.Configuration                = "Release";
            command.CloudFormationTemplate       = "serverless-arm.template";
            command.CloudFormationOutputTemplate = Path.Combine(Path.GetTempPath(), "output-serverless-arm.template");
            command.S3Bucket                     = "serverless-package-test-" + DateTime.Now.Ticks;
            command.DisableInteractive           = true;

            if (File.Exists(command.CloudFormationOutputTemplate))
            {
                File.Delete(command.CloudFormationOutputTemplate);
            }


            await command.S3Client.PutBucketAsync(command.S3Bucket);

            try
            {
                Assert.True(await command.ExecuteAsync());
                Assert.True(File.Exists(command.CloudFormationOutputTemplate));

                var templateJson = File.ReadAllText(command.CloudFormationOutputTemplate);
                var templateRoot = JsonConvert.DeserializeObject(templateJson) as JObject;
                var codeUri      = templateRoot["Resources"]["DefaultFunction"]["Properties"]["CodeUri"].ToString();
                Assert.False(string.IsNullOrEmpty(codeUri));

                var s3Key = codeUri.Split('/').Last();

                var transfer        = new TransferUtility(command.S3Client);
                var functionZipPath = Path.GetTempFileName();
                await transfer.DownloadAsync(functionZipPath, command.S3Bucket, s3Key);

                Assert.Equal("linux-arm64", GetRuntimeFromBundle(functionZipPath));

                File.Delete(functionZipPath);
            }
            finally
            {
                await AmazonS3Util.DeleteS3BucketWithObjectsAsync(command.S3Client, command.S3Bucket);
            }
        }
        public void NETCore_2_0_NewerAspNetCoreReference()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NewerAspNetCoreReference.xml");

            try
            {
                LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.0", manifest, projectFile);
                Assert.True(true, "Missing LambdaToolsException thrown");
            }
            catch (LambdaToolsException e)
            {
                Assert.Contains("which is newer", e.Message);
            }
        }
Exemplo n.º 11
0
        public async Task CreateLayer()
        {
            var logger = new TestToolLogger(_testOutputHelper);

            var command = new PublishLayerCommand(logger, _singleLayerFunctionPath, new string[0]);

            command.Region             = "us-east-1";
            command.TargetFramework    = "netcoreapp2.1";
            command.S3Bucket           = this._testFixture.Bucket;
            command.DisableInteractive = true;
            command.LayerName          = "DotnetTest-CreateLayer";
            command.LayerType          = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE;
            command.PackageManifest    = _singleLayerFunctionPath;

            try
            {
                Assert.True(await command.ExecuteAsync());
                Assert.NotNull(command.NewLayerVersionArn);

                var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });

                Assert.NotNull(getResponse.Description);


                var data = JsonMapper.ToObject <LayerDescriptionManifest>(getResponse.Description);
                Assert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt);
                Assert.NotNull(data.Dir);
                Assert.Equal(this._testFixture.Bucket, data.Buc);
                Assert.NotNull(data.Key);


                using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key))
                    using (var reader = new StreamReader(getManifestResponse.ResponseStream))
                    {
                        var xml = await reader.ReadToEndAsync();

                        Assert.Contains("AWSSDK.S3", xml);
                        Assert.Contains("Amazon.Lambda.Core", xml);
                    }
            }
            finally
            {
                await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
            }
        }
Exemplo n.º 12
0
        public void SingleAppendEnv()
        {
            var logger   = new TestToolLogger();
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp");
            var command  = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]);

            command.EnvironmentVariables       = null;
            command.AppendEnvironmentVariables = new Dictionary <string, string> {
                { "foo", "bar" }
            };

            var combinedEnv = command.GetEnvironmentVariables(null);

            Assert.Single(combinedEnv);
            Assert.Equal("bar", combinedEnv["foo"]);
        }
Exemplo n.º 13
0
        public async Task UseNewtonsoft10()
        {
            var fullPath = GetTestProjectPath("UseNewtonsoft10");
            var logger   = new TestToolLogger();
            var command  = new PackageCommand(logger, fullPath, new string[0]);

            command.DisableInteractive = true;
            command.Configuration      = "Release";
            command.TargetFramework    = "netcoreapp1.0";

            command.OutputPackageFileName = Path.GetTempFileName() + ".zip";

            var created = await command.ExecuteAsync();

            Assert.False(created);

            Assert.True(logger.Buffer.ToLower().Contains("error: netstandard.library 1.6.1 is used for target framework netcoreapp1.1"));
            Assert.True(logger.Buffer.ToLower().Contains("error: 	newtonsoft.json : 10.0.2"));
        }
Exemplo n.º 14
0
        public async Task Use11ASPNetCoreDependencies()
        {
            var fullPath = GetTestProjectPath("Use11ASPNetCoreDependencies");
            var logger   = new TestToolLogger();
            var command  = new PackageCommand(logger, fullPath, new string[0]);

            command.DisableInteractive = true;
            command.Configuration      = "Release";
            command.TargetFramework    = "netcoreapp1.0";

            command.OutputPackageFileName = Path.GetTempFileName() + ".zip";

            var created = await command.ExecuteAsync();

            Assert.False(created);

            Assert.True(logger.Buffer.ToLower().Contains("error: netstandard.library 1.6.1 is used for target framework netcoreapp1.1"));
            Assert.True(logger.Buffer.ToLower().Contains("error: 	microsoft.aspnetcore.diagnostics : 1.1.1"));
            Assert.True(logger.Buffer.ToLower().Contains("error: 	microsoft.extensions.fileproviders.embedded : 1.1.0"));
        }
        public async Task UpdateFunctionGoesToFailure()
        {
            var functionName = "fakeFunction";

            var mockLambda = new Mock <IAmazonLambda>();

            var getConfigCallCount = 0;

            mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny <GetFunctionConfigurationRequest>(), It.IsAny <CancellationToken>()))
            .Callback <GetFunctionConfigurationRequest, CancellationToken>((request, token) =>
            {
                Assert.Equal(functionName, request.FunctionName);
            })
            .Returns((GetFunctionConfigurationRequest r, CancellationToken token) =>
            {
                getConfigCallCount++;
                if (getConfigCallCount < 3)
                {
                    return(Task.FromResult(new GetFunctionConfigurationResponse
                    {
                        State = State.Active,
                        LastUpdateStatus = LastUpdateStatus.InProgress
                    }));
                }

                return(Task.FromResult(new GetFunctionConfigurationResponse
                {
                    State = State.Active,
                    LastUpdateStatus = LastUpdateStatus.Failed,
                    LastUpdateStatusReason = "Its Bad"
                }));
            });

            var logger = new TestToolLogger();
            await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName);

            Assert.Contains("An update is currently", logger.Buffer);
            Assert.Contains("... Waiting", logger.Buffer);
            Assert.Contains("Warning: function", logger.Buffer);
            Assert.Contains("Its Bad", logger.Buffer);
        }
        public async Task TestDeployLargeServerless()
        {
            var logger   = new TestToolLogger();
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp");
            var command  = new DeployServerlessCommand(logger, fullPath, new string[0]);

            command.Region                 = "us-east-1";
            command.Configuration          = "Release";
            command.TargetFramework        = "netcoreapp2.1";
            command.CloudFormationTemplate = "large-serverless.template";
            command.StackName              = "TestDeployLargeServerless-" + DateTime.Now.Ticks;
            command.S3Bucket               = this._testFixture.Bucket;

            command.WaitForStackToComplete = true;
            command.ProjectLocation        = fullPath;
            command.DisableInteractive     = true;



            var created = await command.ExecuteAsync();

            try
            {
                Assert.True(created);
            }
            finally
            {
                if (created)
                {
                    var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]);
                    deleteCommand.StackName          = command.StackName;
                    deleteCommand.Region             = command.Region;
                    deleteCommand.DisableInteractive = true;
                    await deleteCommand.ExecuteAsync();
                }
            }
        }
Exemplo n.º 17
0
        private async Task <PublishLayerCommand> PublishLayerAsync(string projectDirectory, string optDirectory)
        {
            var logger = new TestToolLogger(_testOutputHelper);

            var publishLayerCommand = new PublishLayerCommand(logger, projectDirectory, new string[0]);

            publishLayerCommand.Region             = "us-east-1";
            publishLayerCommand.TargetFramework    = "netcoreapp2.1";
            publishLayerCommand.S3Bucket           = this._testFixture.Bucket;
            publishLayerCommand.DisableInteractive = true;
            publishLayerCommand.LayerName          = "Dotnet-IntegTest-";
            publishLayerCommand.LayerType          = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE;
            publishLayerCommand.OptDirectory       = optDirectory;
//            publishLayerCommand.PackageManifest = _singleLayerFunctionPath;

            if (!(await publishLayerCommand.ExecuteAsync()))
            {
                throw publishLayerCommand.LastToolsException;
            }

            return(publishLayerCommand);
        }
Exemplo n.º 18
0
        public void CombinedEnvAndAppendEnvIgnoreExisting()
        {
            var logger   = new TestToolLogger();
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp");
            var command  = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]);

            command.EnvironmentVariables = new Dictionary <string, string> {
                { "service", "s3" }
            };
            command.AppendEnvironmentVariables = new Dictionary <string, string> {
                { "foo", "bar" }
            };

            var combinedEnv = command.GetEnvironmentVariables(new Dictionary <string, string> {
                { "service", "lambda" }
            });

            Assert.Equal(2, combinedEnv.Count);
            Assert.Equal("bar", combinedEnv["foo"]);
            Assert.Equal("s3", combinedEnv["service"]);
        }
Exemplo n.º 19
0
        public async Task DeployServerlessWithlayer()
        {
            var logger = new TestToolLogger(_testOutputHelper);

            var templateTilePath = Path.Combine(_serverlessLayerFunctionPath, "serverless.template");

            if (File.Exists(templateTilePath))
            {
                File.Delete(templateTilePath);
            }

            var publishLayerCommand = await PublishLayerAsync(_serverlessLayerFunctionPath, "");

            try
            {
                var templateContent = File.ReadAllText(Path.Combine(_serverlessLayerFunctionPath, "fake.template"));
                templateContent =
                    templateContent.Replace("LAYER_ARN_PLACEHOLDER", publishLayerCommand.NewLayerVersionArn);

                File.WriteAllText(templateTilePath, templateContent);

                var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), _serverlessLayerFunctionPath, new string[] { });
                command.DisableInteractive     = true;
                command.StackName              = "DeployServerlessWithlayer-" + DateTime.Now.Ticks;
                command.Region                 = publishLayerCommand.Region;
                command.S3Bucket               = this._testFixture.Bucket;
                command.WaitForStackToComplete = true;
                command.DisableInteractive     = true;
                command.ProjectLocation        = _serverlessLayerFunctionPath;

                var created = await command.ExecuteAsync();

                try
                {
                    Assert.True(created);

                    Func <string, Task> testFunctionAsync = async(functionName) =>
                    {
                        var lambdaFunctionName =
                            await TestHelper.GetPhysicalCloudFormationResourceId(_testFixture.CFClient, command.StackName, functionName);

                        await ValidateInvokeAsync(lambdaFunctionName, "\"hello\"", "\"HELLO\"");

                        var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = lambdaFunctionName });

                        Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn)));

                        var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(lambdaFunctionName);

                        using (var client = new HttpClient())
                        {
                            var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location);

                            var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read);

                            Assert.NotNull(zipArchive.GetEntry("TestLayerServerless.dll"));
                            Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll"));
                        }
                    };

                    await testFunctionAsync("TheFunction");
                    await testFunctionAsync("TheSecondFunctionSameSource");
                }
                finally
                {
                    if (created)
                    {
                        var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), _serverlessLayerFunctionPath, new string[0]);
                        deleteCommand.DisableInteractive = true;
                        deleteCommand.Region             = publishLayerCommand.Region;
                        deleteCommand.StackName          = command.StackName;
                        await deleteCommand.ExecuteAsync();
                    }
                }
            }
            finally
            {
                await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });

                if (File.Exists(templateTilePath))
                {
                    File.Delete(templateTilePath);
                }
            }
        }
        public async Task DeployStepFunctionWithTemplateSubstitution()
        {
            var cfClient = new AmazonCloudFormationClient(RegionEndpoint.USEast2);
            var s3Client = new AmazonS3Client(RegionEndpoint.USEast2);

            var bucketName = "deploy-step-functions-" + DateTime.Now.Ticks;
            await s3Client.PutBucketAsync(bucketName);

            try
            {
                var logger   = new TestToolLogger();
                var assembly = this.GetType().GetTypeInfo().Assembly;

                var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TemplateSubstitutionTestProjects/StateMachineDefinitionStringTest");
                var command  = new DeployServerlessCommand(logger, fullPath, new string[0]);
                command.DisableInteractive     = true;
                command.Configuration          = "Release";
                command.TargetFramework        = "netcoreapp1.0";
                command.StackName              = "DeployStepFunctionWithTemplateSubstitution-" + DateTime.Now.Ticks;
                command.S3Bucket               = bucketName;
                command.WaitForStackToComplete = true;

                command.TemplateParameters = new Dictionary <string, string> {
                    { "NonExisting", "Parameter" }, { "StubParameter", "SecretFoo" }
                };

                var created = await command.ExecuteAsync();

                try
                {
                    Assert.True(created);

                    var describeResponse = await cfClient.DescribeStacksAsync(new DescribeStacksRequest
                    {
                        StackName = command.StackName
                    });

                    Assert.Equal(StackStatus.CREATE_COMPLETE, describeResponse.Stacks[0].StackStatus);

                    Assert.DoesNotContain("SecretFoo", logger.Buffer.ToString());
                    Assert.Contains("****", logger.Buffer.ToString());
                }
                finally
                {
                    if (created)
                    {
                        try
                        {
                            var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]);
                            deleteCommand.StackName = command.StackName;
                            await deleteCommand.ExecuteAsync();
                        }
                        catch
                        {
                            // Bury exception because we don't want to lose any exceptions during the deploy stage.
                        }
                    }
                }
            }
            finally
            {
                await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName);
            }
        }
Exemplo n.º 21
0
        public async Task DeployAspNetCoreWithlayer()
        {
            var logger = new TestToolLogger(_testOutputHelper);

            var templateTilePath = Path.Combine(_aspnercoreLayerFunctionPath, "serverless.template");

            if (File.Exists(templateTilePath))
            {
                File.Delete(templateTilePath);
            }

            var publishLayerCommand = await PublishLayerAsync(_aspnercoreLayerFunctionPath, "");

            try
            {
                var getLayerResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });

                Assert.NotNull(getLayerResponse.Description);

                // Make sure layer does not contain any core ASP.NET Core dependencies.
                var layerManifest = JsonMapper.ToObject <LayerDescriptionManifest>(getLayerResponse.Description);
                using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(layerManifest.Buc, layerManifest.Key))
                    using (var reader = new StreamReader(getManifestResponse.ResponseStream))
                    {
                        var xml = await reader.ReadToEndAsync();

                        Assert.False(xml.Contains("Microsoft.AspNetCore"));
                        Assert.False(xml.Contains("runtime"));
                    }

                var templateContent = File.ReadAllText(Path.Combine(_aspnercoreLayerFunctionPath, "fake.template"));
                templateContent =
                    templateContent.Replace("LAYER_ARN_PLACEHOLDER", publishLayerCommand.NewLayerVersionArn);

                File.WriteAllText(templateTilePath, templateContent);

                var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[] { });
                command.DisableInteractive     = true;
                command.StackName              = "DeployAspNetCoreWithlayer-" + DateTime.Now.Ticks;
                command.Region                 = publishLayerCommand.Region;
                command.S3Bucket               = this._testFixture.Bucket;
                command.WaitForStackToComplete = true;
                command.DisableInteractive     = true;
                command.ProjectLocation        = _aspnercoreLayerFunctionPath;
                var created = await command.ExecuteAsync();

                try
                {
                    Assert.True(created);

                    var lambdaFunctionName =
                        await TestHelper.GetPhysicalCloudFormationResourceId(_testFixture.CFClient, command.StackName, "AspNetCoreFunction");

                    var apiUrl = await TestHelper.GetOutputParameter(_testFixture.CFClient, command.StackName, "ApiURL");

                    using (var client = new HttpClient())
                    {
                        await client.GetStringAsync(new Uri(new Uri(apiUrl), "api/values"));
                    }

                    var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = lambdaFunctionName });

                    Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn)));

                    var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(lambdaFunctionName);

                    using (var client = new HttpClient())
                    {
                        var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location);

                        var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read);

                        Assert.NotNull(zipArchive.GetEntry("TestLayerAspNetCore.dll"));
                        Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll"));
                        Assert.Null(zipArchive.GetEntry("AWSSDK.S3.dll"));
                        Assert.Null(zipArchive.GetEntry("AWSSDK.Extensions.NETCore.Setup.dll"));
                        Assert.Null(zipArchive.GetEntry("Amazon.Lambda.AspNetCoreServer.dll"));
                    }
                }
                finally
                {
                    if (created)
                    {
                        var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[0]);
                        deleteCommand.DisableInteractive = true;
                        deleteCommand.Region             = publishLayerCommand.Region;
                        deleteCommand.StackName          = command.StackName;
                        await deleteCommand.ExecuteAsync();
                    }
                }
            }
            finally
            {
                await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });

                if (File.Exists(templateTilePath))
                {
                    File.Delete(templateTilePath);
                }
            }
        }
Exemplo n.º 22
0
        public async Task DeployFunctionWithLayer(string optDirectory)
        {
            var logger = new TestToolLogger(_testOutputHelper);

            var publishLayerCommand = await PublishLayerAsync(_singleLayerFunctionPath, optDirectory);

            try
            {
                Assert.NotNull(publishLayerCommand.NewLayerVersionArn);


                var deployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), _singleLayerFunctionPath, new string[0]);
                deployCommand.FunctionName = "test-layer-function-" + DateTime.Now.Ticks;
                deployCommand.Region       = publishLayerCommand.Region;
                deployCommand.Handler      = "TestLayerExample::TestLayerExample.Function::FunctionHandler";
                deployCommand.Timeout      = 10;
                deployCommand.MemorySize   = 512;
                deployCommand.Role         = await TestHelper.GetTestRoleArnAsync();

                deployCommand.Configuration      = "Release";
                deployCommand.TargetFramework    = "netcoreapp2.1";
                deployCommand.Runtime            = "dotnetcore2.1";
                deployCommand.LayerVersionArns   = new string[] { publishLayerCommand.NewLayerVersionArn };
                deployCommand.DisableInteractive = true;

                var created = await deployCommand.ExecuteAsync();

                try
                {
                    // See if we got back the return which proves we were able to load an assembly from the S3 NuGet package
                    // return new Amazon.S3.Model.ListBucketsRequest().ToString();
                    await ValidateInvokeAsync(deployCommand.FunctionName, "\"TEST\"", "\"Amazon.S3.Model.ListBucketsRequest\"");


                    var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = deployCommand.FunctionName });

                    Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn)));

                    var dotnetSharedSource = getConfigResponse.Environment.Variables[LambdaConstants.ENV_DOTNET_SHARED_STORE];
                    if (!string.IsNullOrEmpty(optDirectory))
                    {
                        Assert.Equal($"/opt/{optDirectory}/", dotnetSharedSource);
                    }
                    else
                    {
                        Assert.Equal($"/opt/{LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY}/", dotnetSharedSource);
                    }

                    var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(deployCommand.FunctionName);

                    using (var client = new HttpClient())
                    {
                        var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location);

                        var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read);

                        Assert.NotNull(zipArchive.GetEntry("TestLayerExample.dll"));
                        Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll"));
                        Assert.Null(zipArchive.GetEntry("AWSSDK.S3.dll"));
                    }

                    var redeployLayerCommand = await PublishLayerAsync(_singleLayerFunctionPath, optDirectory);

                    var redeployFunctionCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), _singleLayerFunctionPath, new string[0]);
                    redeployFunctionCommand.FunctionName       = deployCommand.FunctionName;
                    redeployFunctionCommand.Region             = deployCommand.Region;
                    redeployFunctionCommand.Handler            = deployCommand.Handler;
                    redeployFunctionCommand.Timeout            = deployCommand.Timeout;
                    redeployFunctionCommand.MemorySize         = deployCommand.MemorySize;
                    redeployFunctionCommand.Role               = deployCommand.Role;
                    redeployFunctionCommand.Configuration      = deployCommand.Configuration;
                    redeployFunctionCommand.TargetFramework    = deployCommand.TargetFramework;
                    redeployFunctionCommand.Runtime            = deployCommand.Runtime;
                    redeployFunctionCommand.LayerVersionArns   = new string[] { redeployLayerCommand.NewLayerVersionArn };
                    redeployFunctionCommand.DisableInteractive = true;

                    if (!await redeployFunctionCommand.ExecuteAsync())
                    {
                        throw redeployFunctionCommand.LastToolsException;
                    }

                    await ValidateInvokeAsync(redeployFunctionCommand.FunctionName, "\"TEST\"", "\"Amazon.S3.Model.ListBucketsRequest\"");
                }
                finally
                {
                    await this._testFixture.LambdaClient.DeleteFunctionAsync(new DeleteFunctionRequest { FunctionName = deployCommand.FunctionName });
                }
            }
            finally
            {
                await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });
            }
        }
Exemplo n.º 23
0
        // This test behaves different depending on the OS the test is running on which means
        // all code paths are not always being tested. Future work is needed to figure out how to
        // mock the underlying calls to the dotnet CLI.
        public async Task AttemptToCreateAnOptmizedLayer()
        {
            var logger   = new TestToolLogger(_testOutputHelper);
            var assembly = this.GetType().GetTypeInfo().Assembly;

            var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestLayerExample");
            var command  = new PublishLayerCommand(logger, fullPath, new string[] { "--enable-package-optimization", "true" });

            command.Region             = "us-east-1";
            command.TargetFramework    = "netcoreapp2.1";
            command.S3Bucket           = this._testFixture.Bucket;
            command.DisableInteractive = true;
            command.LayerName          = "DotnetTest-AttemptToCreateAnOptmizedLayer";
            command.LayerType          = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE;
            command.PackageManifest    = fullPath;

            bool success = false;

            try
            {
                success = await command.ExecuteAsync();

                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.False(success);
                    Assert.Equal(LambdaToolsException.LambdaErrorCode.UnsupportedOptimizationPlatform.ToString(), command.LastToolsException.Code);
                }
                else
                {
                    Assert.True(success);
                    Assert.NotNull(command.NewLayerVersionArn);

                    var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });

                    Assert.NotNull(getResponse.Description);


                    var data = JsonMapper.ToObject <LayerDescriptionManifest>(getResponse.Description);
                    Assert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt);
                    Assert.NotNull(data.Dir);
                    Assert.Equal(this._testFixture.Bucket, data.Buc);
                    Assert.NotNull(data.Key);


                    using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key))
                        using (var reader = new StreamReader(getManifestResponse.ResponseStream))
                        {
                            var xml = await reader.ReadToEndAsync();

                            Assert.Contains("AWSSDK.S3", xml);
                            Assert.Contains("Amazon.Lambda.Core", xml);
                        }
                }
            }
            finally
            {
                if (success)
                {
                    await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
                }
            }
        }