public async Task NegativeBootstrapInitTestsAsync() { var ucl = new UserCodeLoader("NonExistentAssembly::HandlerTest.CustomerType::ZeroInZeroOut", _internalLogger); var ex = Assert.Throws <LambdaValidationException>(() => ucl.Init(NoOpLoggingAction)); Assert.Contains("Could not find the specified handler", ex.Message); await TestHandlerFailAsync($"HandlerTest2::Type::Method", "Could not find the specified handler assembly with the file name"); await TestHandlerFailAsync("HandlerTest::HandlerTest.FakeCustomerType::PocoInPocoOut", "Unable to load type"); await TestHandlerFailAsync("HandlerTest::HandlerTest.GenericCustomerType`1::PocoInPocoOut", "Handler methods cannot be located in generic types."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::FakeMethod", "Found no methods matching method name 'FakeMethod'"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::HandlerTest.CustomerPoco FakeMethod(HandlerTest.CustomerPoco)", "Found no methods matching method name '"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::OverloadedMethod", "appears to have a number of overloads. To call this method please specify a complete method signature."); await TestHandlerFailAsync("HandlerTest::HandlerTest.AbstractCustomerType::AbstractMethod", "Please specify a non-abstract handler method."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::GenericMethod", "Handler methods cannot be generic."); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::TwoInputsNoContextMethod", "is not supported: the method has 2 parameters, but the second parameter is not of type"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::TooManyInputsMethod", "is not supported: the method has more than 2 parameters."); await TestHandlerFailAsync("HandlerTestNoSerializer::HandlerTestNoSerializer.CustomerType::PocoInPocoOut", "To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with Amazon.Lambda.LambdaSerializerAttribute."); await TestHandlerFailAsync("HandlerTestNoSerializer::HandlerTestNoSerializer.CustomerType::PocoInPocoOut", "To use types other than System.IO.Stream as input/output parameters, the assembly or Lambda function should be annotated with Amazon.Lambda.LambdaSerializerAttribute."); var noZeroParamTypeEx = await TestHandlerFailAsync("HandlerTest::HandlerTest.NoZeroParamConstructorCustomerType::SimpleMethod", "No parameterless constructor defined for this object."); Assert.IsAssignableFrom <MissingMethodException>(noZeroParamTypeEx); var customerConstructorEx = TestHandlerFailAsync("HandlerTest::HandlerTest.ConstructorExceptionCustomerType::SimpleMethod", "An exception was thrown when the constructor for type"); Assert.NotNull(customerConstructorEx); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::NoZeroParameterConstructorCustomerTypeSerializerMethod", "does not define a public zero-parameter constructor"); await TestHandlerFailAsync("HandlerTest::HandlerTest.CustomerType::NoInterfaceCustomerTypeSerializerMethod", "it does not implement the 'ILambdaSerializer' interface."); await TestHandlerFailAsync("HandlerTest::HandlerTest.StaticCustomerTypeThrows::StaticCustomerMethodZeroOut", "StaticCustomerTypeThrows static constructor has thrown an exception."); }
public ExecutionInfo(LambdaBootstrap bootstrap, string dataIn, string dataOut, string loggingActionTest, Exception exception, UserCodeLoader userCodeLoader) { Bootstrap = bootstrap; DataIn = dataIn; DataOut = dataOut; LoggingActionText = loggingActionTest; Exception = exception; UserCodeLoader = userCodeLoader; }
/// <summary> /// Initializes the UserCodeLoader using the Function Handler and runs LambdaBootstrap asynchronously. /// </summary> public async Task RunLambdaBootstrap() { await _debugAttacher.TryAttachDebugger(); var userCodeLoader = new UserCodeLoader(_handler, _logger); var initializer = new UserCodeInitializer(userCodeLoader, _logger); using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke)) using (var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync)) { await bootstrap.RunAsync(); } }
public async Task LoadConfigurationForGivenProjectShouldReturnDefinedConfig() { AnalyzerManager manager = new AnalyzerManager(); IProjectAnalyzer analyzer = manager.GetProject(@"..\..\..\..\Tests.Assets.WebApi2022\Tests.Assets.WebApi2022.csproj"); AdhocWorkspace workspace = analyzer.GetWorkspace(false); var project = workspace.CurrentSolution.Projects.Where(x => x.Name == "Tests.Assets.WebApi2022").First(); var output = new IOutputMock(); var loader = new UserCodeLoader(output, new IFileSearcherMock()); var userCode = await loader.LoadUserCodeForGivenProject(workspace.CurrentSolution, project.FilePath); var config = userCode.Config; Assert.AreEqual(false, config.AddGeneratedFilesToVSProject); config.ProjectsToBeSearched.ShouldBe(new[] { "Tests.Assets.WebApi2022" }); }
/// Program entry point static void Main(string[] args) { AssemblyLoadContext.Default.Resolving += OnAssemblyResolving; var handler = GetFunctionHandler(args); var body = GetEventBody(args); var lambdaContext = new MockLambdaContext(handler, body); var userCodeLoader = new UserCodeLoader(handler, InternalLogger.NO_OP_LOGGER); userCodeLoader.Init(Console.Error.WriteLine); var lambdaContextInternal = new LambdaContextInternal(lambdaContext.RemainingTime, LogAction, new Lazy <CognitoClientContextInternal>(), lambdaContext.RequestId, new Lazy <string>(lambdaContext.Arn), new Lazy <string>(string.Empty), new Lazy <string>(string.Empty), Environment.GetEnvironmentVariables()); Exception lambdaException = null; LogRequestStart(lambdaContext); try { userCodeLoader.Invoke(lambdaContext.InputStream, lambdaContext.OutputStream, lambdaContextInternal); } catch (Exception ex) { lambdaException = ex; } LogRequestEnd(lambdaContext); if (lambdaException == null) { Console.WriteLine(lambdaContext.OutputText); } else { Console.Error.WriteLine(lambdaException); } }
private async Task <Exception> TestHandlerFailAsync(string handler, string expectedPartialMessage, bool?expectAggregateException = null) { _output.WriteLine($"Testing handler {handler}"); var testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables, _headers); var userCodeLoader = new UserCodeLoader(handler, _internalLogger); var initializer = new UserCodeInitializer(userCodeLoader, _internalLogger); var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke); var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync) { Client = testRuntimeApiClient }; using (var cancellationTokenSource = new CancellationTokenSource()) { var exceptionWaiterTask = Task.Run(() => { _output.WriteLine($"Waiting for an exception."); while (testRuntimeApiClient.LastRecordedException == null) { } _output.WriteLine($"Exception available."); cancellationTokenSource.Cancel(); return(testRuntimeApiClient.LastRecordedException); }); await Record.ExceptionAsync(async() => { await bootstrap.RunAsync(cancellationTokenSource.Token); }); var exception = await exceptionWaiterTask; Assert.NotNull(exception); Common.CheckException(exception, expectedPartialMessage); Common.CheckForAggregateException(exception, expectAggregateException); return(exception); } }
public async Task Execute(Solution solution, IList <TemplateToRender> templates) { await status.Update("Rendering", 0, templates.Count); for (int i = 0; i < templates.Count; ++i) { var template = templates[i]; output.Info(new String('-', 69)); output.Info("Rendering started : " + System.IO.Path.GetFileName(template.FilePath)); await status.Update("Rendering", i + 1, templates.Count); var userCodeLoader = new UserCodeLoader(output, fileSearcher); var userCode = await userCodeLoader.LoadUserCodeForGivenProject(solution, template.ProjectPath).ConfigureAwait(false); var editorConfig = new EditorConfig(userCode.Config); var codeModelBuilder = new CodeModelBuilder(); var codeModel = new LazyCodeModel(() => codeModelBuilder.Build(solution, editorConfig)); output.Info($"Loading template : {template.FilePath}"); var templateContent = template.Content ?? await fileReaderWriter.Read(template.FilePath).ConfigureAwait(false); var templateRenderer = new TemplateRenderer(errorList, output); var renderedItems = await templateRenderer.RenderAsync(template.FilePath, templateContent, codeModel, userCode.TypesThatMayContainCustomFunctions, editorConfig).ConfigureAwait(false); var fileSaver = new FileSaver(output, sourceControl, fileReaderWriter); await fileSaver.Save(renderedItems).ConfigureAwait(false); if (editorConfig.AddGeneratedFilesToVSProject) { output.Info("Updating VisualStudio solution"); await solutionItemsManager.UpdateSolution(template.FilePath, renderedItems.Select(x => x.FilePath)).ConfigureAwait(false); output.Info("VisualStudio solution updated successfully"); } await status.Update("Rendering succeed"); } }
private async Task <ExecutionInfo> ExecHandlerAsync(string handler, string dataIn, string assertLoggedByInitialize) { // The actionWriter using (var actionWriter = new StringWriter()) { var testRuntimeApiClient = new TestRuntimeApiClient(_environmentVariables, _headers); var loggerAction = actionWriter.ToLoggingAction(); var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(UserCodeLoader.LambdaCoreAssemblyName)); UserCodeLoader.SetCustomerLoggerLogAction(assembly, loggerAction, _internalLogger); var userCodeLoader = new UserCodeLoader(handler, _internalLogger); var handlerWrapper = HandlerWrapper.GetHandlerWrapper(userCodeLoader.Invoke); var initializer = new UserCodeInitializer(userCodeLoader, _internalLogger); var bootstrap = new LambdaBootstrap(handlerWrapper, initializer.InitializeAsync) { Client = testRuntimeApiClient }; if (assertLoggedByInitialize != null) { Assert.False(actionWriter.ToString().Contains($"^^[{assertLoggedByInitialize}]^^")); } await bootstrap.InitializeAsync(); if (assertLoggedByInitialize != null) { Assert.True(actionWriter.ToString().Contains($"^^[{assertLoggedByInitialize}]^^")); } var dataOut = await InvokeAsync(bootstrap, dataIn, testRuntimeApiClient); var actionText = actionWriter.ToString(); return(new ExecutionInfo(bootstrap, dataIn, dataOut, actionText, null, userCodeLoader)); } }
/// Program entry point static void Main(string[] args) { AssemblyLoadContext.Default.Resolving += OnAssemblyResolving; try { var shouldWaitForDebugger = GetShouldWaitForDebuggerFlag(args, out var positionalArgs); var handler = GetFunctionHandler(positionalArgs); var body = GetEventBody(positionalArgs); if (shouldWaitForDebugger) { Console.Error.WriteLine("Waiting for the debugger to attach..."); if (!DebuggerExtensions.TryWaitForAttaching( _debuggerStatusQueryInterval, _debuggerStatusQueryTimeout)) { Console.Error.WriteLine("Timeout. Proceeding without debugger."); } } var lambdaContext = new MockLambdaContext(handler, body); var userCodeLoader = new UserCodeLoader(handler, InternalLogger.NO_OP_LOGGER); userCodeLoader.Init(Console.Error.WriteLine); var lambdaContextInternal = new LambdaContextInternal(lambdaContext.RemainingTime, LogAction, new Lazy <CognitoClientContextInternal>(), lambdaContext.RequestId, new Lazy <string>(lambdaContext.Arn), new Lazy <string>(string.Empty), new Lazy <string>(string.Empty), Environment.GetEnvironmentVariables()); Exception lambdaException = null; LogRequestStart(lambdaContext); try { userCodeLoader.Invoke(lambdaContext.InputStream, lambdaContext.OutputStream, lambdaContextInternal); } catch (Exception ex) { lambdaException = ex; } LogRequestEnd(lambdaContext); if (lambdaException == null) { Console.WriteLine(lambdaContext.OutputText); } else { Console.Error.WriteLine(lambdaException); } } // Catch all unhandled exceptions from runtime, to prevent user from hanging on them while debugging catch (Exception ex) { Console.Error.WriteLine($"\nUnhandled exception occured in runner:\n{ex}"); } }