예제 #1
0
        private static LambdaConfigInfo LoadLambdaConfigInfo(string configFile, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory, RunConfiguration runConfiguration)
        {
            LambdaConfigInfo configInfo;

            if (configFile != null)
            {
                runConfiguration.OutputWriter.WriteLine($"... Using config file {configFile}");
                configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);
            }
            else
            {
                // If no config files or function handler are set then we don't know what code to call and must give up.
                if (string.IsNullOrEmpty(commandOptions.FunctionHandler))
                {
                    throw new CommandLineParseException("No config file or function handler specified to test tool is unable to identify the Lambda code to execute.");
                }

                // No config files were found so create a temporary config file and use the function handler value that was set on the command line.
                configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(new LambdaConfigFile
                {
                    FunctionHandler    = commandOptions.FunctionHandler,
                    ConfigFileLocation = lambdaProjectDirectory ?? lambdaAssemblyDirectory
                });
            }

            return(configInfo);
        }
        public ConfigFileSummary GetFunctions(string configFile)
        {
            var fullConfigFilePath = this.LambdaOptions.LambdaConfigFiles.FirstOrDefault(x =>
                                                                                         string.Equals(configFile, Path.GetFileName(x), StringComparison.OrdinalIgnoreCase));

            if (fullConfigFilePath == null)
            {
                throw new Exception($"{configFile} is not a config file for this project");
            }

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(fullConfigFilePath);
            var functions  = this.LambdaOptions.LambdaRuntime.LoadLambdaFunctions(configInfo.FunctionInfos);

            var summary = new ConfigFileSummary
            {
                AWSProfile = configInfo.AWSProfile,
                AWSRegion  = configInfo.AWSRegion,
                Functions  = new List <FunctionSummary>()
            };

            foreach (var function in functions)
            {
                summary.Functions.Add(new FunctionSummary()
                {
                    FunctionName    = function.FunctionInfo.Name,
                    FunctionHandler = function.FunctionInfo.Handler,
                    ErrorMessage    = function.ErrorMessage
                });
            }

            return(summary);
        }
        public void SetRegion()
        {
            var jsonFile = WriteTempConfigFile("{\"region\" : \"us-west-2\"}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Equal("us-west-2", configInfo.AWSRegion);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public LambdaFunction LoadLambdaFuntion(string configFile, string functionHandler)
        {
            var fullConfigFilePath = this.LambdaConfigFiles.FirstOrDefault(x =>
                                                                           string.Equals(configFile, x, StringComparison.OrdinalIgnoreCase) || string.Equals(configFile, Path.GetFileName(x), StringComparison.OrdinalIgnoreCase));

            if (fullConfigFilePath == null)
            {
                throw new Exception($"{configFile} is not a config file for this project");
            }

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(fullConfigFilePath);

            return(LoadLambdaFuntion(configInfo, functionHandler));
        }
        public void NonDefaultProfile()
        {
            var jsonFile = WriteTempConfigFile("{\"profile\" : \"test-profile\"}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Equal("test-profile", configInfo.AWSProfile);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public void NoProfile()
        {
            var jsonFile = WriteTempConfigFile("{}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Equal("default", configInfo.AWSProfile);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public void NoRegion()
        {
            var jsonFile = WriteTempConfigFile("{}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Null(configInfo.AWSRegion);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public void LambdaFunctionWithImageCommand()
        {
            var jsonFile = WriteTempConfigFile("{\"image-command\" : \"Assembly::Type::Method\", \"function-name\" : \"TheFunc\"}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Single(configInfo.FunctionInfos);
                Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler);
                Assert.Equal("TheFunc", configInfo.FunctionInfos[0].Name);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public void LambdaFunctionWithName()
        {
            var jsonFile = WriteTempConfigFile("{'function-handler' : 'Assembly::Type::Method', 'function-name' : 'TheFunc'}");

            try
            {
                var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile);
                Assert.Single(configInfo.FunctionInfos);
                Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler);
                Assert.Equal("TheFunc", configInfo.FunctionInfos[0].Name);
            }
            finally
            {
                File.Delete(jsonFile);
            }
        }
        public void LoadServerlessResourceBasedYamlTemplateConfig()
        {
            var defaultsFilePath = Path.GetFullPath(@"../../../../LambdaFunctions/ServerlessTemplateYamlExample/aws-lambda-tools-defaults.json");

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath);

            Assert.Equal(2, configInfo.FunctionInfos.Count);
            Assert.Equal("default", configInfo.AWSProfile);
            Assert.Equal("us-west-2", configInfo.AWSRegion);

            Assert.Equal("MyHelloWorld", configInfo.FunctionInfos[0].Name);
            Assert.Equal("ServerlessTemplateYamlExample::ServerlessTemplateYamlExample.Functions::HelloWorld", configInfo.FunctionInfos[0].Handler);

            Assert.Equal("MyToUpper", configInfo.FunctionInfos[1].Name);
            Assert.Equal("ServerlessTemplateYamlExample::ServerlessTemplateYamlExample.Functions::ToUpper", configInfo.FunctionInfos[1].Handler);
        }
예제 #11
0
        public void LoadServerlessTemplateConfig()
        {
            var defaultsFilePath = TestUtils.GetLambdaFunctionSourceFile("ServerlessTemplateExample", "aws-lambda-tools-defaults.json");

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath);

            Assert.Equal(2, configInfo.FunctionInfos.Count);
            Assert.Equal("default", configInfo.AWSProfile);
            Assert.Equal("us-west-2", configInfo.AWSRegion);

            Assert.Equal("MyHelloWorld", configInfo.FunctionInfos[0].Name);
            Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::HelloWorld", configInfo.FunctionInfos[0].Handler);

            Assert.Equal("MyToUpper", configInfo.FunctionInfos[1].Name);
            Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::ToUpper", configInfo.FunctionInfos[1].Handler);
        }
예제 #12
0
        public static IList <string> SearchForConfigFiles(string lambdaFunctionDirectory)
        {
            var configFiles = new List <string>();

            // Look for JSON files that are .NET Lambda config files like aws-lambda-tools-defaults.json. The parameter
            // lambdaFunctionDirectory will be set to the build directory so the search goes up the directory hierarchy.
            do
            {
                foreach (var file in Directory.GetFiles(lambdaFunctionDirectory, "*.json", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        var configFile = System.Text.Json.JsonSerializer.Deserialize <LambdaConfigFile>(File.ReadAllText(file), new System.Text.Json.JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        });
                        configFile.ConfigFileLocation = file;

                        if (!string.IsNullOrEmpty(configFile.DetermineHandler()))
                        {
                            Console.WriteLine($"Found Lambda config file {file}");
                            configFiles.Add(file);
                        }
                        else if (!string.IsNullOrEmpty(configFile.Template) && File.Exists(Path.Combine(lambdaFunctionDirectory, configFile.Template)))
                        {
                            var config = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);
                            if (config.FunctionInfos?.Count > 0)
                            {
                                Console.WriteLine($"Found Lambda config file {file}");
                                configFiles.Add(file);
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine($"Error parsing JSON file: {file}");
                    }
                }

                lambdaFunctionDirectory = Directory.GetParent(lambdaFunctionDirectory)?.FullName;
            } while (lambdaFunctionDirectory != null && configFiles.Count == 0);

            return(configFiles);
        }
        public void LoadServerlessFunctionBasedYamlTemplateConfig()
        {
            var defaultsFilePath = TestUtils.GetLambdaFunctionSourceFile("ServerlessFunctionTemplateYamlExample", "aws-lambda-tools-defaults.json");

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath);

            Assert.Equal(3, configInfo.FunctionInfos.Count);
            Assert.Equal("default", configInfo.AWSProfile);
            Assert.Equal("us-west-2", configInfo.AWSRegion);

            Assert.Equal("create", configInfo.FunctionInfos[0].Name);
            Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.CreateItemFunction::Run", configInfo.FunctionInfos[0].Handler);

            Assert.Equal("get", configInfo.FunctionInfos[1].Name);
            Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.GetItemFunction::Run", configInfo.FunctionInfos[1].Handler);


            Assert.Equal("update", configInfo.FunctionInfos[2].Name);
            Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.UpdateItemFunction::Run", configInfo.FunctionInfos[2].Handler);
        }
예제 #14
0
        private static LambdaFunction LoadLambdaFunction(LambdaConfigInfo configInfo, LocalLambdaOptions localLambdaOptions, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory, RunConfiguration runConfiguration)
        {
            // If no function handler was explicitly set and there is only one function defined in the config file then assume the user wants to debug that function.
            var functionHandler = commandOptions.FunctionHandler;

            if (string.IsNullOrEmpty(commandOptions.FunctionHandler))
            {
                if (configInfo.FunctionInfos.Count == 1)
                {
                    functionHandler = configInfo.FunctionInfos[0].Handler;
                }
                else
                {
                    throw new CommandLineParseException("Project has more then one Lambda function defined. Use the --function-handler switch to identify the Lambda code to execute.");
                }
            }

            LambdaFunction lambdaFunction;

            if (!localLambdaOptions.TryLoadLambdaFuntion(configInfo, functionHandler, out lambdaFunction))
            {
                // The user has explicitly set a function handler value that is not in the config file or CloudFormation template.
                // To support users testing add hoc methods create a temporary config object using explicit function handler value.
                runConfiguration.OutputWriter.WriteLine($"... Info: function handler {functionHandler} is not defined in config file.");
                var temporaryConfigInfo = LambdaDefaultsConfigFileParser.LoadFromFile(new LambdaConfigFile
                {
                    FunctionHandler    = functionHandler,
                    ConfigFileLocation = Utils.FindLambdaProjectDirectory(lambdaAssemblyDirectory) ?? lambdaAssemblyDirectory
                });

                temporaryConfigInfo.AWSProfile = configInfo.AWSProfile;
                temporaryConfigInfo.AWSRegion  = configInfo.AWSRegion;
                configInfo     = temporaryConfigInfo;
                lambdaFunction = localLambdaOptions.LoadLambdaFuntion(configInfo, functionHandler);
            }

            runConfiguration.OutputWriter.WriteLine($"... Using function handler {functionHandler}");
            return(lambdaFunction);
        }
        public void LoadStaticMethodWithMethodSerializer()
        {
            var configFile = TestUtils.GetLambdaFunctionSourceFile("ToUpperFunc", "aws-lambda-tools-defaults.json");
            var buildPath  = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc");

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);

            Assert.Single(configInfo.FunctionInfos);

            var runtime = LocalLambdaRuntime.Initialize(buildPath);

            var functions = runtime.LoadLambdaFunctions(configInfo.FunctionInfos);

            Assert.Equal(1, functions.Count);

            var function = functions[0];

            Assert.True(function.IsSuccess);
            Assert.NotNull(function.LambdaAssembly);
            Assert.NotNull(function.LambdaType);
            Assert.NotNull(function.LambdaMethod);

            Assert.NotNull(function.Serializer);
        }
        public void LoadStaticMethodWithMethodSerializer()
        {
            var configFile = Path.GetFullPath(@"../../../../LambdaFunctions/ToUpperFunc/aws-lambda-tools-defaults.json");
            var buildPath  = Path.GetFullPath(@"../../../../LambdaFunctions/ToUpperFunc/bin/debug/netcoreapp2.1");

            var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);

            Assert.Single(configInfo.FunctionInfos);

            var runtime = LocalLambdaRuntime.Initialize(buildPath);

            var functions = runtime.LoadLambdaFunctions(configInfo.FunctionInfos);

            Assert.Equal(1, functions.Count);

            var function = functions[0];

            Assert.True(function.IsSuccess);
            Assert.NotNull(function.LambdaAssembly);
            Assert.NotNull(function.LambdaType);
            Assert.NotNull(function.LambdaMethod);

            Assert.NotNull(function.Serializer);
        }
예제 #17
0
        public LambdaFunction LoadLambdaFuntion(string configFile, string functionHandler)
        {
            var fullConfigFilePath = this.LambdaConfigFiles.FirstOrDefault(x =>
                                                                           string.Equals(configFile, Path.GetFileName(x), StringComparison.OrdinalIgnoreCase));

            if (fullConfigFilePath == null)
            {
                throw new Exception($"{configFile} is not a config file for this project");
            }

            var configInfo   = LambdaDefaultsConfigFileParser.LoadFromFile(fullConfigFilePath);
            var functionInfo = configInfo.FunctionInfos.FirstOrDefault(x =>
                                                                       string.Equals(functionHandler, x.Handler, StringComparison.OrdinalIgnoreCase));

            if (functionInfo == null)
            {
                throw new Exception($"Failed to find function {functionHandler}");
            }


            var function = this.LambdaRuntime.LoadLambdaFunction(functionInfo);

            return(function);
        }
        public async Task DlqIntegTest()
        {
            const int WAIT_TIME = 5000;
            var       queueName = "local-dlq-list-queue-test-" + DateTime.Now.Ticks;

            using (var client = new AmazonSQSClient(TestUtils.GetAWSCredentials(), TestUtils.TestRegion))
            {
                var createResponse = await client.CreateQueueAsync(new CreateQueueRequest { QueueName = queueName });

                await TestUtils.WaitTillQueueIsCreatedAsync(client, createResponse.QueueUrl);

                try
                {
                    var configFile = Path.GetFullPath(@"../../../../LambdaFunctions/ToUpperFunc/aws-lambda-tools-defaults.json");
                    var buildPath  = Path.GetFullPath(@"../../../../LambdaFunctions/ToUpperFunc/bin/debug/netcoreapp2.1");
                    var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile);
                    var runtime    = LocalLambdaRuntime.Initialize(buildPath);
                    var function   = runtime.LoadLambdaFunctions(configInfo.FunctionInfos)[0];

                    var monitor = new DlqMonitor(runtime, function, TestUtils.TestProfile, TestUtils.TestRegion.SystemName, createResponse.QueueUrl);

                    monitor.Start();
                    await client.SendMessageAsync(new SendMessageRequest
                    {
                        QueueUrl    = createResponse.QueueUrl,
                        MessageBody = "\"testing dlq\""
                    });

                    Thread.Sleep(WAIT_TIME);
                    var logs = monitor.FetchNewLogs();
                    Assert.Single(logs);

                    Assert.Contains("testing dlq", logs[0].Logs);
                    Assert.NotNull(logs[0].ReceiptHandle);
                    Assert.NotEqual(DateTime.MinValue, logs[0].ProcessTime);

                    logs = monitor.FetchNewLogs();
                    Assert.Equal(0, logs.Count);

                    await client.SendMessageAsync(new SendMessageRequest
                    {
                        QueueUrl    = createResponse.QueueUrl,
                        MessageBody = "\"testing dlq1\""
                    });

                    await client.SendMessageAsync(new SendMessageRequest
                    {
                        QueueUrl    = createResponse.QueueUrl,
                        MessageBody = "\"testing dlq2\""
                    });

                    Thread.Sleep(WAIT_TIME);

                    logs = monitor.FetchNewLogs();
                    Assert.Equal(2, logs.Count);

                    monitor.Stop();
                    Thread.Sleep(WAIT_TIME);
                    await client.SendMessageAsync(new SendMessageRequest
                    {
                        QueueUrl    = createResponse.QueueUrl,
                        MessageBody = "\"testing dlq3\""
                    });

                    Thread.Sleep(WAIT_TIME);

                    logs = monitor.FetchNewLogs();
                    Assert.Equal(0, logs.Count);
                }
                finally
                {
                    await client.DeleteQueueAsync(createResponse.QueueUrl);
                }
            }
        }