Skip to content

refactor(testing): clean up and simplify LambdaApplicationFactory#221

Merged
j-d-ha merged 7 commits into
feature/#185-add-testing-packagefrom
feature/#185-add-testing-package-update-factory
Dec 7, 2025
Merged

refactor(testing): clean up and simplify LambdaApplicationFactory#221
j-d-ha merged 7 commits into
feature/#185-add-testing-packagefrom
feature/#185-add-testing-package-update-factory

Conversation

@j-d-ha

@j-d-ha j-d-ha commented Dec 7, 2025

Copy link
Copy Markdown
Collaborator

🚀 Pull Request

📋 Summary

This PR refactors and simplifies the LambdaApplicationFactory class, making it more maintainable and easier to use. The changes include:

  • Removed redundant logic and commented-out code
  • Simplified server initialization process
  • Renamed WithWebHostBuilder to WithHostBuilder for better clarity
  • Removed unused methods and client configuration
  • Updated default RuntimeApiEndpoint value
  • Streamlined overall factory implementation

The refactoring reduces the codebase by ~87 lines while maintaining all functionality.


✅ Checklist

  • My changes build cleanly
  • I've added/updated relevant tests
  • I've added/updated documentation or README
  • I've followed the coding style for this project
  • I've tested the changes locally (if applicable)

🧪 Related Issues or PRs

Part of #185


💬 Notes for Reviewers

Focus areas:

  • Verify that the simplified initialization logic maintains the same behavior
  • Check that the WithHostBuilder rename is consistent throughout
  • Ensure no functionality was lost in the cleanup process

…server creation

- Deleted `ConfigureClient(HttpClient client)` method and related XML documentation.
- Removed commented-out and redundant `_createServer` and `ConfigureClient` references.
- Introduced `CreateServer` for internal use in `LambdaApplicationFactory`.
- Updated `DelegatedLambdaApplicationFactory` to simplify server initialization logic.
…ostOptions

- Changed default `RuntimeApiEndpoint` from `localhost:3002` to `localhost` in `LambdaApplicationFactory`.
…ambdaApplicationFactory

- Deleted unused and commented-out `EnsureServer` and `Return Services` logic.
- Simplified `SetContentRoot` by removing conditional file checks.
- Updated `GetContentRoot` to always use `GetContentRootFromAssembly`.
…ApplicationFactory

- Deleted `GetContentRootFromFile` and replaced all usage with `GetContentRootFromAssembly`.
- Updated `GetContentRootFromAssembly` to use a `foreach` loop for clarity.
- Returned `[]` instead of `Array.Empty<Assembly>` to simplify empty array initialization.
- Rearranged fields in `DelegatedLambdaApplicationFactory` for consistent ordering.
- Added comments to ignored exceptions for better readability.
…mbdaApplicationFactory

- Renamed `WithWebHostBuilder` and `WithWebHostBuilderCore` to `WithHostBuilder` and `WithHostBuilderCore`.
- Updated XML documentation comments to reflect the new method names.
- Removed unused and commented-out server creation code in `DelegatedLambdaApplicationFactory`.
- Updated example tests in `LambdaHostTest` to use the renamed `WithHostBuilder` method.
…nFactory

- Replaced inline server creation logic with a call to `CreateServer`.
- Removed unused variables `serializerOptions` and `routeManager` during initialization.
- Removed commented-out and unused code, including `_clients` disposal and `CustomJsonSerializerContext`.
- Dropped `partial` keyword from `LambdaApplicationFactory` class declaration.
- Replaced `?.Name ?? string.Empty` with `.Name` for assembly name retrieval.
- Updated array initialization to use brackets instead of `new[]`.
- Simplified disposal logic for `Dispose` and `DisposeAsync` methods.
@github-actions github-actions Bot added the type: refactor Code refactoring label Dec 7, 2025
@j-d-ha
j-d-ha merged commit 69e158f into feature/#185-add-testing-package Dec 7, 2025
3 checks passed
@j-d-ha
j-d-ha deleted the feature/#185-add-testing-package-update-factory branch December 7, 2025 21:10
j-d-ha added a commit that referenced this pull request Dec 10, 2025
* refactor(testing): remove unused client configuration and streamline server creation

- Deleted `ConfigureClient(HttpClient client)` method and related XML documentation.
- Removed commented-out and redundant `_createServer` and `ConfigureClient` references.
- Introduced `CreateServer` for internal use in `LambdaApplicationFactory`.
- Updated `DelegatedLambdaApplicationFactory` to simplify server initialization logic.

* refactor(testing): update default RuntimeApiEndpoint value in LambdaHostOptions

- Changed default `RuntimeApiEndpoint` from `localhost:3002` to `localhost` in `LambdaApplicationFactory`.

* refactor(testing): remove redundant logic and commented-out code in LambdaApplicationFactory

- Deleted unused and commented-out `EnsureServer` and `Return Services` logic.
- Simplified `SetContentRoot` by removing conditional file checks.
- Updated `GetContentRoot` to always use `GetContentRootFromAssembly`.

* refactor(testing): remove unused methods and simplify logic in LambdaApplicationFactory

- Deleted `GetContentRootFromFile` and replaced all usage with `GetContentRootFromAssembly`.
- Updated `GetContentRootFromAssembly` to use a `foreach` loop for clarity.
- Returned `[]` instead of `Array.Empty<Assembly>` to simplify empty array initialization.
- Rearranged fields in `DelegatedLambdaApplicationFactory` for consistent ordering.
- Added comments to ignored exceptions for better readability.

* refactor(testing): rename WithWebHostBuilder to WithHostBuilder in LambdaApplicationFactory

- Renamed `WithWebHostBuilder` and `WithWebHostBuilderCore` to `WithHostBuilder` and `WithHostBuilderCore`.
- Updated XML documentation comments to reflect the new method names.
- Removed unused and commented-out server creation code in `DelegatedLambdaApplicationFactory`.
- Updated example tests in `LambdaHostTest` to use the renamed `WithHostBuilder` method.

* refactor(testing): simplify server initialization in LambdaApplicationFactory

- Replaced inline server creation logic with a call to `CreateServer`.
- Removed unused variables `serializerOptions` and `routeManager` during initialization.

* refactor(testing): clean up and simplify LambdaApplicationFactory

- Removed commented-out and unused code, including `_clients` disposal and `CustomJsonSerializerContext`.
- Dropped `partial` keyword from `LambdaApplicationFactory` class declaration.
- Replaced `?.Name ?? string.Empty` with `.Name` for assembly name retrieval.
- Updated array initialization to use brackets instead of `new[]`.
- Simplified disposal logic for `Dispose` and `DisposeAsync` methods.
j-d-ha added a commit that referenced this pull request Dec 12, 2025
* refactor(testing): remove unused client configuration and streamline server creation

- Deleted `ConfigureClient(HttpClient client)` method and related XML documentation.
- Removed commented-out and redundant `_createServer` and `ConfigureClient` references.
- Introduced `CreateServer` for internal use in `LambdaApplicationFactory`.
- Updated `DelegatedLambdaApplicationFactory` to simplify server initialization logic.

* refactor(testing): update default RuntimeApiEndpoint value in LambdaHostOptions

- Changed default `RuntimeApiEndpoint` from `localhost:3002` to `localhost` in `LambdaApplicationFactory`.

* refactor(testing): remove redundant logic and commented-out code in LambdaApplicationFactory

- Deleted unused and commented-out `EnsureServer` and `Return Services` logic.
- Simplified `SetContentRoot` by removing conditional file checks.
- Updated `GetContentRoot` to always use `GetContentRootFromAssembly`.

* refactor(testing): remove unused methods and simplify logic in LambdaApplicationFactory

- Deleted `GetContentRootFromFile` and replaced all usage with `GetContentRootFromAssembly`.
- Updated `GetContentRootFromAssembly` to use a `foreach` loop for clarity.
- Returned `[]` instead of `Array.Empty<Assembly>` to simplify empty array initialization.
- Rearranged fields in `DelegatedLambdaApplicationFactory` for consistent ordering.
- Added comments to ignored exceptions for better readability.

* refactor(testing): rename WithWebHostBuilder to WithHostBuilder in LambdaApplicationFactory

- Renamed `WithWebHostBuilder` and `WithWebHostBuilderCore` to `WithHostBuilder` and `WithHostBuilderCore`.
- Updated XML documentation comments to reflect the new method names.
- Removed unused and commented-out server creation code in `DelegatedLambdaApplicationFactory`.
- Updated example tests in `LambdaHostTest` to use the renamed `WithHostBuilder` method.

* refactor(testing): simplify server initialization in LambdaApplicationFactory

- Replaced inline server creation logic with a call to `CreateServer`.
- Removed unused variables `serializerOptions` and `routeManager` during initialization.

* refactor(testing): clean up and simplify LambdaApplicationFactory

- Removed commented-out and unused code, including `_clients` disposal and `CustomJsonSerializerContext`.
- Dropped `partial` keyword from `LambdaApplicationFactory` class declaration.
- Replaced `?.Name ?? string.Empty` with `.Name` for assembly name retrieval.
- Updated array initialization to use brackets instead of `new[]`.
- Simplified disposal logic for `Dispose` and `DisposeAsync` methods.
j-d-ha added a commit that referenced this pull request Dec 12, 2025
* refactor(testing): remove unused client configuration and streamline server creation

- Deleted `ConfigureClient(HttpClient client)` method and related XML documentation.
- Removed commented-out and redundant `_createServer` and `ConfigureClient` references.
- Introduced `CreateServer` for internal use in `LambdaApplicationFactory`.
- Updated `DelegatedLambdaApplicationFactory` to simplify server initialization logic.

* refactor(testing): update default RuntimeApiEndpoint value in LambdaHostOptions

- Changed default `RuntimeApiEndpoint` from `localhost:3002` to `localhost` in `LambdaApplicationFactory`.

* refactor(testing): remove redundant logic and commented-out code in LambdaApplicationFactory

- Deleted unused and commented-out `EnsureServer` and `Return Services` logic.
- Simplified `SetContentRoot` by removing conditional file checks.
- Updated `GetContentRoot` to always use `GetContentRootFromAssembly`.

* refactor(testing): remove unused methods and simplify logic in LambdaApplicationFactory

- Deleted `GetContentRootFromFile` and replaced all usage with `GetContentRootFromAssembly`.
- Updated `GetContentRootFromAssembly` to use a `foreach` loop for clarity.
- Returned `[]` instead of `Array.Empty<Assembly>` to simplify empty array initialization.
- Rearranged fields in `DelegatedLambdaApplicationFactory` for consistent ordering.
- Added comments to ignored exceptions for better readability.

* refactor(testing): rename WithWebHostBuilder to WithHostBuilder in LambdaApplicationFactory

- Renamed `WithWebHostBuilder` and `WithWebHostBuilderCore` to `WithHostBuilder` and `WithHostBuilderCore`.
- Updated XML documentation comments to reflect the new method names.
- Removed unused and commented-out server creation code in `DelegatedLambdaApplicationFactory`.
- Updated example tests in `LambdaHostTest` to use the renamed `WithHostBuilder` method.

* refactor(testing): simplify server initialization in LambdaApplicationFactory

- Replaced inline server creation logic with a call to `CreateServer`.
- Removed unused variables `serializerOptions` and `routeManager` during initialization.

* refactor(testing): clean up and simplify LambdaApplicationFactory

- Removed commented-out and unused code, including `_clients` disposal and `CustomJsonSerializerContext`.
- Dropped `partial` keyword from `LambdaApplicationFactory` class declaration.
- Replaced `?.Name ?? string.Empty` with `.Name` for assembly name retrieval.
- Updated array initialization to use brackets instead of `new[]`.
- Simplified disposal logic for `Dispose` and `DisposeAsync` methods.
j-d-ha added a commit that referenced this pull request Dec 13, 2025
* feat(testing): add AwsLambda.Host.Testing project

- Added a new project `AwsLambda.Host.Testing` to support unit testing for AwsLambda.Host.
- Configured multi-targeting for .NET 8.0, 9.0, and 10.0 with preview language features.
- Included necessary metadata for NuGet packaging, including README file support.
- Updated solution file to include the new project.

* feat(examples): add AwsLambda.Host.Examples.Testing project

- Introduced new example project to demonstrate testing with AwsLambda.Host.
- Configured the project to target .NET 10.0 with appropriate properties and metadata.
- Added basic Lambda handler implementation with a `name` parameter.
- Included `appsettings.json` for logging configuration.
- Configured `launchSettings.json` for local testing with mock runtime.
- Updated solution to include the new example project.

* feat(testing): enhance AwsLambda.Host.Examples.Testing with unit testing setup

- Added `LambdaHostTest` class with a sample test for validating Lambda host functionality.
- Configured necessary testing dependencies like xUnit, NSubstitute, and coverlet.collector.
- Included `appsettings.json` with `PreserveNewest` copy directive for output directory.

* feat(testing): add DeferredHostBuilder to AwsLambda.Host.Testing

- Introduced `DeferredHostBuilder` to enable deferred execution of IHostBuilder configuration.
- Added support for capturing and replaying configuration calls with `ConfigureHostBuilder`.
- Implemented `DeferredHost` to manage deferred host startup and ensure proper disposal.
- Linked implementation with MIT-licensed parts from aspnetcore, providing proper attribution.

* feat(testing): add LambdaApplicationFactory to AwsLambda.Host.Testing

- Introduced `LambdaApplicationFactory` for managing and testing Lambda application lifecycle.
- Implemented proper disposal handling with `Dispose` and `DisposeAsync` methods.
- Ensured compatibility with `IHost` for seamless integration and teardown.

* docs(testing): update README with HTTP request/response examples

- Added detailed examples for AWS Lambda local invocation happy and error paths.
- Included formatted HTTP request and response content for better understanding.
- Documented the error handling flow, including stack traces and error serialization.

* docs(testing): add licensing attribution for LambdaApplicationFactory

- Added attribution to aspnetcore's `WebApplicationFactory.cs` under the MIT license.
- Included reference to the source repository and license file for transparency.
- Updated header comments in `LambdaApplicationFactory.cs` for proper acknowledgment.

* feat(examples): add HTTP request/response logging to testing example

- Introduced `LoggingHttpHandler` for detailed HTTP request and response logging.
- Updated `Program.cs` to configure `BootstrapHttpClient` using `LoggingHttpHandler`.
- Enabled `ClearLambdaOutputFormatting` for better Lambda output readability.

* fix(scripts): update version extraction logic in validate-version.sh

- Changed version extraction from `<VersionPrefix>` to `<Version>` in `Directory.Build.props`.
- Updated error message to reflect the new version tag.

* feat(testing): add HostFactoryResolver to AwsLambda.Host.Testing

- Added `HostFactoryResolver`, copied and adapted from .NET runtime's implementation.
- Enables dynamic resolution and creation of `IHost` and `IServiceProvider` for testing scenarios.
- Included proper licensing attribution in the file header.
- Ensures compatibility with diagnostic event-based host building patterns.

* chore(licenses): update copyright and licensing attributions

- Updated copyright notices to include ".NET Foundation and Contributors" in relevant files.
- Added new entry for the .NET runtime license to THIRD-PARTY-LICENSES.txt.
- Ensured consistency in licensing attribution across files for proper acknowledgment.

* chore(config): add .csharpierignore and update .editorconfig settings

- Added `.csharpierignore` to exclude specific files from formatting checks.
- Updated `.editorconfig` to disable formatting for `HostFactoryResolver.cs`.
- Included `.csharpierignore` and `.editorconfig` in the solution file (`AwsLambda.Host.sln`).

* feat(testing): add LambdaApplicationFactoryClientOptions and LambdaTestingHttpHandler

- Introduced `LambdaApplicationFactoryClientOptions` for customizing test client configurations.
- Added `LambdaTestingHttpHandler` for handling HTTP-specific test scenarios.
- Extended `LambdaApplicationFactory` to improve support for Lambda app testing workflows.

* feat(testing): migrate LambdaApplicationFactory to use IHostBuilder

- Replaced IWebHostBuilder with IHostBuilder across LambdaApplicationFactory.
- Updated documentation to reflect the use of IHostBuilder methods and patterns.
- Simplified host configuration by deprecating IWebHostBuilder-specific logic.

* feat(testing): add Microsoft.AspNetCore.Routing package

- Added `Microsoft.AspNetCore.Routing` as a package reference in the Testing project.
- Updated `Directory.Packages.props` to include `Microsoft.AspNetCore.Routing` version 2.3.0.

* feat(testing): add ErrorResponse model to represent structured error data

- Introduced `ErrorResponse` model for consistent error representation in testing scenarios.
- Added nested `ErrorCause` class to handle detailed error information with potential nested causes.
- Included JSON serialization attributes for seamless JSON handling.

* feat(testing): add LambdaRuntimeRouteManager with route matching implementation

- Introduced `LambdaRuntimeRouteManager` and `ILambdaRuntimeRouteManager` for route matching logic.
- Implemented support for matching HTTP requests to specific Lambda runtime routes.
- Defined route templates for `/invocation/next`, `/invocation/{requestId}/response`, and `/invocation/{requestId}/error`.
- Utilized `TemplateMatcher` for parsing and matching route templates.

* feat(testing): add RequestType enum for Lambda runtime request classification

- Introduced `RequestType` enum with values: `GetNextInvocation`, `PostResponse`, and `PostError`.
- Enables clear categorization of Lambda runtime request types in testing scenarios.

* feat(testing): add InvocationResponse model for Lambda testing

- Introduced `InvocationResponse<TResponse>` for modeling Lambda invocation outcomes.
- Added `WasSuccess`, `Response`, and `Error` properties for detailed testing scenarios.

* feat(testing): add LambdaBootstrapRequest model for request handling

- Introduced `LambdaBootstrapRequest` model to encapsulate Lambda runtime request data.
- Added `RequestType`, `RequestMessage`, and `RouteValue` properties as required fields.
- Implemented `RequestId` property using `RouteValueDictionary` for request identification.

* feat(testing): add LambdaClient for managing Lambda runtime requests

- Introduced `LambdaClient` to handle Lambda runtime requests in testing scenarios.
- Implemented `WaitForBootstrapAsync` to process bootstrap-specific requests.
- Added `WaitForRequestAsync` with support for route matching using `ILambdaRuntimeRouteManager`.
- Included `Invoke<TEvent, TResponse>` method for serializing events and initiating invocation responses.

* feat(testing): enhance LambdaTestingHttpHandler with request/response channel support

- Added constructor to `LambdaTestingHttpHandler` accepting request and response channels.
- Implemented `SendAsync` to pass requests to `requestChannel` and receive responses from `responseChannel`.

* feat(testing): update route templates to support version-based paths

- Replaced hardcoded "2018-06-01" route version with a dynamic "{version}" placeholder.
- Updated route templates for `GetNextInvocation`, `PostResponse`, and `PostError` requests.
- Improved flexibility and compatibility for handling versioned Lambda runtime paths.

* feat(testing): add customizable Lambda invocation headers and response handling

- Introduced `LambdaClientOptions` to configure response headers for Lambda invocations.
- Added `LambdaInvocationHeaders` to customize attributes like date, chunked transfer, and AWS metadata.
- Enhanced `Invoke` method to return a mocked `HttpResponseMessage` with serialized invocation data.

* feat(testing): add configuration support to LambdaClient

- Added `LambdaClientOptions` as a configurable option for `LambdaClient`.
- Implemented `ConfigureOptions` method to allow runtime customization of `LambdaClientOptions`.
- Ensured null-check for `configureOptions` to prevent potential null reference exceptions.

* refactor(testing): extract request creation logic into `CreateRequest` method in `LambdaClient`

- Moved request creation code from `Invoke<TEvent, TResponse>` to a new private method `CreateRequest<TEvent>`.
- Simplified `Invoke` by reusing the `CreateRequest` method.
- Improved maintainability and readability by centralizing HTTP response setup logic.
- Updated to use values from `LambdaClientOptions.InvocationHeaders` for response headers.

* feat(testing): add options for customizing Lambda invocation headers and client configuration

- Introduced `LambdaInvocationHeaderOptions` to define additional headers, metadata, and timeouts.
- Added `LambdaClientOptions` to encapsulate and configure invocation header options.

* refactor(testing): improve response header configuration and LambdaClient options

- Reorganized `LambdaClientOptions` within `LambdaClient` for clarity and proper initialization.
- Refactored response header setup to use `InvocationHeaderOptions` for better flexibility.
- Added support for calculating dynamic `DeadlineMs` header based on function timeout.
- Enabled adding custom additional headers via `InvocationHeaderOptions.AdditionalHeaders`.

* feat(testing): improve request ID generation and invocation handling in LambdaClient

- Replaced `RequestId` with `InvocationCounter` to generate zero-padded 12-digit request IDs.
- Incremented `InvocationCounter` after each invocation to ensure unique request IDs.
- Renamed `Invoke` to `InvokeAsync` for consistency with asynchronous method naming conventions.

* feat(testing): enhance Lambda request/response handling in LambdaClient

- Renamed `WaitForBootstrapAsync` to `WaitForNextRequestAsync` for improved clarity.
- Refactored `Invoke` response logic to handle success and error scenarios more robustly.
- Added support for serializing invocation responses including success status and error details.
- Simplified the invocation flow to improve readability and maintainability.

* fix(testing): handle null deserialization fallback in LambdaClient response handling

- Added null fallback handling for `ReadFromJsonAsync` to avoid potential null reference exceptions.
- Ensured default value (`default` or `null`) is used when no content is available to deserialize.

* refactor(testing): remove unnecessary WaitForNextRequestAsync call

- Eliminated redundant `WaitForNextRequestAsync` invocation in `InvokeAsync`.
- Simplified invocation flow for improved readability and maintainability.

* fix(testing): allow null RequestId and update fallback logic

- Changed `RequestId` property to nullable to correctly reflect potential absence of value.
- Updated fallback logic to return `null` instead of an empty string when no `RequestId` is found.

* refactor(testing): simplify request ID generation and remove unused invocation counter

- Added `GetRequestId` method to centralize and simplify request ID generation logic.
- Removed `InvocationCounter` property from `LambdaInvocationHeaderOptions` as it is no longer used.
- Updated `LambdaClient` to increment and zero-pad request counter directly via `GetRequestId` method.
- Improved code clarity and maintainability by eliminating redundant properties and methods.

* refactor(testing): replace DelegatingHandler with HttpMessageHandler in LambdaTestingHttpHandler

- Changed base class of `LambdaTestingHttpHandler` from `DelegatingHandler` to `HttpMessageHandler`.
- Simplified class implementation for improved compatibility and maintainability.

* feat(testing): add LambdaTestServer implementation and update dependencies

- Introduced `LambdaTestServer` class as an `IServer` implementation for testing purposes.
- Added required `Microsoft.AspNetCore.Hosting.Abstractions` package reference to project and props files.
- Updated `AwsLambda.Host.Testing.csproj` and `Directory.Packages.props` to include new dependency.

* refactor(testing): replace TestServer with LambdaTestServer in LambdaApplicationFactory

- Updated `LambdaApplicationFactory` to use `LambdaTestServer` instead of `TestServer` for consistency.
- Modified related methods, properties, and comments to reflect the change.
- Adjusted `DelegatedWebApplicationFactory` to align with the updated server type.

* refactor(testing): remove redundant TestServer configuration in LambdaApplicationFactory

- Simplified `ConfigureHostBuilder` by consolidating configuration logic.
- Removed duplicate `ConfigureWebHost` calls with `TestServer` setup.
- Updated comments to reflect the introduction of Lambda-specific logic.

* feat(testing): add System.Net.Http and System.Text.RegularExpressions to test projects

- Updated multiple test project files to include `System.Net.Http` and `System.Text.RegularExpressions`.
- Ensured consistent dependencies across unit test and example projects.

* refactor(testing): update class access modifiers and refactor LambdaTestServer

- Changed `LambdaTestingHttpHandler` and `LambdaTestServer` classes from public to internal.
- Removed unused `_isBootstrappingComplete` field from `LambdaClient`.
- Added request and response channel initialization in `LambdaTestServer`.
- Created helper methods `CreateTestingHandler` and `CreateLambdaClient` in `LambdaTestServer`.

* feat(testing): replace TestServer with LambdaTestServer and add bootstrap HTTP client setup

- Modified `LambdaApplicationFactory` to instantiate `LambdaTestServer` directly.
- Configured Lambda bootstrap HTTP client with testing handler in `ConfigureHostBuilder`.
- Removed unused `TestServer` logic and related comments.
- Updated dependencies to include `AwsLambda.Host.Builder.Extensions`.

* feat(testing): add LambdaApplicationFactoryContentRootAttribute implementation

- Introduced `LambdaApplicationFactoryContentRootAttribute` to configure content root for testing.
- Enables content root path and marker validation in `WebApplicationFactory` instances.
- Supports priority-based attribute handling for better content root resolution.

* feat(testing): add Microsoft.Extensions.DependencyModel package to project

- Added `Microsoft.Extensions.DependencyModel` to `AwsLambda.Host.Testing.csproj` as a package reference.
- Updated `Directory.Packages.props` to include version `10.0.0` of `Microsoft.Extensions.DependencyModel`.

* refactor(testing): clean up and optimize LambdaApplicationFactory content root resolution

- Replaced `SetContentRootFromSetting` logic with enhanced `UseSolutionRelativeContentRoot` method.
- Updated to use `LambdaApplicationFactoryContentRootAttribute` instead of `WebApplicationFactoryContentRootAttribute`.
- Simplified content root resolution by removing redundant logic and improving error handling.
- Changed visibility of `Server` property from public to internal for consistent access control.

* refactor(testing): simplify exception handling in LambdaApplicationFactory

- Replaced resource-based error messages with inline string format for clarity.
- Simplified `InvalidOperationException` messages for missing entry points and dependency files.
- Removed dependency on `Resources` for improved maintainability.

* refactor(testing): comment out unused methods and clean up HttpClient logic in LambdaApplicationFactory

- Commented out unused methods, including `CreateWebHostBuilder`, `CreateClient`, and `CreateDefaultClient`.
- Updated `EnsureServices` method with safer null-forgiving operator for `_host`.
- Commented out `CreateServer` method and related lambda factory logic.
- Cleaned up redundant `HttpClient` creation and disposal logic.
- Removed references to deprecated or redundant WebHost-related logic in DelegatedWebApplicationFactory.

* refactor(testing): remove LoggingHttpHandler and streamline HTTP client configuration

- Commented out `LoggingHttpHandler` class and associated logic in `Program.cs`.
- Added reference to `AwsLambda.Host.Testing.csproj` in the example project.
- Refactored HTTP client configuration by disabling commented-out custom handlers.

* refactor(testing): update method visibility and parameter order in LambdaClient

- Changed `WaitForNextRequestAsync` method visibility from `internal` to `public`.
- Updated `InvokeAsync` method to switch parameter order of `TResponse` and `TEvent`.
- Adjusted the placement of response channel write logic for improved readability.

* feat(testing): add LambdaClient creation and enhance Lambda bootstrap HTTP client setup

- Added `GetClient` method in `LambdaApplicationFactory` for easier `LambdaClient` instantiation.
- Enhanced Lambda bootstrap HTTP client logic with base address and improved endpoint configuration.
- Introduced post-configuration for `LambdaHostOptions` to set default `RuntimeApiEndpoint`.

* refactor(testing): remove unimplemented Dispose method in LambdaTestServer

- Replaced `NotImplementedException` in `Dispose` method with an empty implementation.

* feat(testing): add integration test for LambdaHost

- Implemented a test case to verify `LambdaHost` startup without errors.
- Utilized `WebApplicationFactory<Program>` to bootstrap the application.
- Added assertions for client response and successful invocation.

* refactor(testing): simplify path extraction logic in LambdaRuntimeRouteManager

- Removed unnecessary `TrimStart` method from `RequestUri.AbsolutePath`.
- Updated path extraction to ensure the original value remains intact.

* refactor(testing): remove unimplemented server methods in LambdaTestServer

- Removed `StartAsync` and `StopAsync` methods as they were not implemented.
- Deleted unused `Features` property from the class.
- Updated `LambdaTestServer` to implement `IDisposable` for proper resource cleanup.

* refactor(testing): rename `GetClient` to `CreateClient` and remove unused/commented-out methods

- Renamed `GetClient` to `CreateClient` for better semantics and consistency.
- Removed unused and commented-out methods like `CreateServer`, `CreateDefaultClient`, and others.
- Cleaned up redundant XML documentation for removed methods.

* feat(testing): enhance LambdaTestServer with transaction-based architecture (#220)

* refactor(testing): implement transaction-based architecture with active server processing

Transform the Lambda testing infrastructure from a passive dual-channel model to an active
server-based architecture with transactional HTTP handling. This refactoring enables FIFO
processing of concurrent invocations and provides automatic request-response correlation.

BREAKING CHANGE: Removed `LambdaClient.WaitForNextRequestAsync()` method. The server now
automatically handles the initial Bootstrap request, so users only need to call `InvokeAsync()`.

## Architecture Changes

### Before (Passive Dual-Channel Model)
- Two separate channels (request + response) requiring manual correlation
- LambdaClient handled all routing logic (SRP violation)
- No FIFO guarantee for concurrent requests
- Users required to call `WaitForNextRequestAsync()` before invoking

### After (Active Server-Based Model)
- Single channel carrying self-contained transactions (automatic correlation)
- Active LambdaTestServer manages routing and state in background processing loop
- FIFO processing via ConcurrentQueue + ConcurrentDictionary
- Simplified user API - only `InvokeAsync()` needed

## New Components

- **LambdaHttpTransaction**: Bundles HTTP request with TaskCompletionSource for automatic
  correlation. Uses `TaskCreationOptions.RunContinuationsAsynchronously` to prevent deadlocks.

- **PendingInvocation**: Tracks invocations awaiting Bootstrap processing. Stores event
  response, request ID, and completion TCS.

## Modified Components

- **LambdaTestingHttpHandler**: Creates transactions instead of writing to separate channels.
  Single channel communication with proper cancellation handling.

- **LambdaTestServer**: Transformed into active server with:
  - Background processing loop (`ProcessTransactionsAsync`)
  - Request routing logic (GET /next, POST /response, POST /error)
  - FIFO queue for concurrent invocations
  - Automatic queuing of `/next` requests when no work available
  - Server creates and manages client instance

- **LambdaClient**: Simplified to delegate to server:
  - Removed `WaitForNextRequestAsync()` (BREAKING)
  - Removed `WaitForRequestAsync()` helper
  - Now references server instead of channels
  - Clean API that only exposes `InvokeAsync()`

- **LambdaApplicationFactory**: Updated to start server's background processing loop after
  host creation. Fixed URI schemes for BaseAddress and RuntimeApiEndpoint.

## Test Changes

- Removed `WaitForNextRequestAsync()` call from integration test
- Added test for concurrent invocations with FIFO ordering verification
- Tests now demonstrate simplified user experience

## Key Benefits

1. **Simplified User API**: Users only call `InvokeAsync()` - everything else automatic
2. **FIFO Processing**: Concurrent invocations processed in first-in-first-out order
3. **Automatic Correlation**: Transaction-based design eliminates manual matching
4. **Server in the Middle**: Clear separation of concerns (client/server/handler)
5. **Better Concurrency**: Handles multiple concurrent requests correctly with queuing

* refactor(models): reorder properties and clean up XML comments in model classes

- Reordered properties in `ErrorResponse`, `InvocationResponse`, and others for better readability.
- Updated or removed redundant XML documentation in multiple classes.
- Simplified property initializations and declarations.
- Moved nested class definitions for clarity and consistency.

* refactor(testing): change LambdaTestServer to use IAsyncDisposable instead of IDisposable

Since the server has a background processing task that needs to be awaited during shutdown,
it's more appropriate to implement IAsyncDisposable rather than IDisposable.

## Changes

- **LambdaTestServer**: Changed from `IDisposable` to `IAsyncDisposable`
  - Replaced `Dispose()` with `DisposeAsync()`
  - Use `await _shutdownCts.CancelAsync()` instead of `Cancel()`
  - Properly await `_processingTask` instead of blocking with `Wait()`
  - Catch and suppress expected `OperationCanceledException`

- **LambdaApplicationFactory**: Updated `DisposeAsync()` to properly dispose server
  - Changed from `_server?.Dispose()` to `await _server.DisposeAsync()`

## Benefits

1. **Proper async cleanup**: No more blocking `Wait()` calls during disposal
2. **Better exception handling**: Explicitly catches expected `OperationCanceledException`
3. **Follows best practices**: Async operations should use async disposal pattern
4. **No blocking**: Prevents potential thread pool starvation during shutdown

* feat(testing): buffer request content for re-readability in LambdaTestingHttpHandler

- Added logic to read and buffer the request content as a byte array.
- Wrapped buffered content in a `ByteArrayContent` instance for downstream consumers.

* refactor(testing): improve cleanup and transaction handling in LambdaTestServer

- Enhanced `DisposeAsync` to properly handle shutdown with error propagation and cancellation.
- Added `TryDequeuePendingInvocation` and `CancelPendingInvocation` methods for clarity and reuse.
- Improved transaction handling to prevent orphaned or unprocessed requests upon shutdown.
- Simplified transaction queuing and invocation dequeue logic.
- Replaced repetitive error handling with consolidated helper methods for better maintainability.

* feat(testing): handle shutdown gracefully when transaction queue is full

- Added cancellation handling when `TryWrite` fails due to a full transaction queue.
- Ensured proper cleanup by canceling `TaskCompletionSource` during shutdown scenarios.
- Replaced `WriteAsync` with `TryWrite` for improved queuing performance.

* feat(testing): add return values to transaction completion methods

- Updated `Respond`, `Fail`, and `Cancel` methods in `LambdaHttpTransaction` to return `bool`
  indicating success or failure of the operation.
- Enhanced `RespondToNextRequest` to handle cases where transactions fail to complete:
  - Re-enqueues pending invocations if transaction was canceled to prevent data loss.

* feat(testing): preserve headers when buffering request content in LambdaTestingHttpHandler

- Updated buffering logic to copy headers from the original content to the buffered content.
- Disposed of the original content after creating the buffered `ByteArrayContent`.

* refactor(testing): simplify LambdaTestServer and factory client creation

- Removed dependency injection of serializer options and route manager during `CreateClient` call.
- Updated `LambdaTestServer` to accept optional parameters for serializer options and route manager.
- Adjusted `LambdaApplicationFactory` to initialize `LambdaTestServer` with parameters instead.
- Modified example tests to include cancellation token when invoking Lambda functions.

* feat(testing): enhance invocation handling with metadata and response type

- Added `InvocationCompletion` model to encapsulate Lambda invocation completion metadata.
- Updated `PendingInvocation.ResponseTcs` to use `InvocationCompletion` instead of `HttpRequestMessage`.
- Refactored `LambdaClient` to parse response type directly from `InvocationCompletion`.
- Simplified response processing by removing `DetermineSuccess` helper method.
- Modified `LambdaTestServer.QueueInvocationAsync` to complete responses with `InvocationCompletion`.

* feat(testing): add invocation timeout and enhance pending invocation handling

- Introduced `InvocationTimeout` in `LambdaInvocationHeaderOptions` with default timeout + buffer.
- Added `DeadlineUtc` to `PendingInvocation` to manage expiration of invocations.
- Updated `PendingInvocation.Create` to accept and initialize `DeadlineUtc`.
- Enhanced `TryDequeuePendingInvocation` to cancel expired invocations.
- Refactored `LambdaTestServer` for bounded channels with capacity limits and queuing improvements.
- Handled `ChannelClosedException` in `LambdaTestingHttpHandler` and `OperationCanceledException` during shutdown gracefully in `QueueInvocationAsync`.
- Updated `LambdaClient` to include `DeadlineUtc` in invocations and use linked cancellation tokens.

* feat(testing): add new tests for invocation error and cancellation scenarios

- Added test to validate behavior when invoking with an invalid payload.
- Implemented test to handle invocation cancellation with a pre-canceled token.
- Added test to verify cancellation with zero timeout during invocation.

* refactor(testing): centralize invocation completion creation in LambdaTestServer

- Added `CreateCompletion` helper method to encapsulate invocation completion object creation.
- Replaced inline object initializations with `CreateCompletion` in `PostResponse` and `PostError` handling.
- Improved readability by reducing redundancy in response completion logic.

* fix(testing): address disposal and exception type in LambdaTestServer and examples

- Fixed disposal in `LambdaTestServer` by marking cancellation registration as `await using`.
- Updated example test to assert `AggregateException` instead of `OperationCanceledException`.

* refactor(examples): restructure AwsLambda.Host example and testing projects

- Moved `AwsLambda.Host.Examples.Testing` to `AwsLambda.Host.Example.Testing` for a more consistent naming convention.
- Split the project into separate `Lambda` and `Tests` projects for better organization.
- Updated solution file to reflect the new structure and project references.
- Renamed and relocated files to adhere to the new structure.

* test(examples): uncomment and include `LambdaHostTest` in the project

- Uncommented the `LambdaHostTest` implementation in the example testing project.
- Added `Lambda` project reference to `Tests.csproj` for proper dependency resolution.

* fix(testing): update exception type in LambdaHostTest assertion

- Changed exception type from `TaskCanceledException` to `AggregateException` in assertion.
- Ensures consistency with updated error handling in invocation scenarios.

* refactor(testing): simplify async handling and invocation completion logic

- Updated `HandlePostResponseAsync` and `HandlePostErrorAsync` to use `async` methods for clarity.
- Refactored `CreateCompletion` to `CreateCompletionAsync` to streamline response creation.
- Improved invocation handling by removing redundant `Task.CompletedTask` returns.
- Fixed nullability issue in `TryDequeuePendingInvocation` by marking `pendingInvocation` as non-nullable.
- Preserved `HttpRequestMessage.Options` during cloning for request consistency.

* refactor(models): enforce required properties and initialize collections in ErrorResponse

- Marked `ErrorMessage` and `ErrorType` properties as `required` in `ErrorResponse`.
- Updated `StackTrace` collections to initialize with an empty list by default.

* refactor(testing): replace `InvocationTimeout` with `ClientWaitTimeout` in Lambda header options

- Renamed `InvocationTimeout` to `ClientWaitTimeout` in `LambdaInvocationHeaderOptions`.
- Added `[Obsolete]` attribute to `InvocationTimeout` for backward compatibility.
- Updated `LambdaClient` to use `ClientWaitTimeout` for deadlines and timeouts.

* refactor(testing): simplify `InvokeAsync_WithZeroTimeout_CancelsInvocation` in LambdaHostTest

- Refactored the test to use an expression-bodied method for brevity and clarity.
- Streamlined aggregation exception assertion logic with `Assert.ThrowsAsync`.

* refactor(testing): replace `WebApplicationFactory` with `LambdaApplicationFactory`

- Updated all test cases in `LambdaHostTest` to use `LambdaApplicationFactory` for consistency.
- Renamed all instances of `WebApplicationFactory` in `LambdaApplicationFactory.cs`.
- Updated XML comments and references to align with the new naming convention.
- Refactored derived factory to `DelegatedLambdaApplicationFactory`.
- Improved clarity and adherence to the Lambda application testing framework.

* fix(testing): throw exception after setting `TrySetException` in `DeferredHostBuilder`

- Ensures the exception is re-thrown for proper error propagation.
- Adds a missing code block to handle exception scenarios consistently.
- Prevents potential silent failures when `_hostStartTcs` is set.

* refactor(testing): simplify `DeferredHost` by consolidating parameters

- Replaced private fields `_host` and `_hostStartedTcs` with primary constructor parameters.
- Simplified disposal logic by removing redundant `_host` access.
- Updated cancellation registration and task handling to use new constructor parameters.
- Improved overall code readability and reduced redundancy in `DeferredHost`.

* test(lambda-host): add new test for handling bad configuration

- Added `LambdaHost_CrashesWithBadConfiguration_ThrowsException` test to validate configuration errors.
- Used `LambdaApplicationFactory` to simulate runtime environment and verify exception handling.
- Enhanced test coverage for invalid `LambdaHostOptions` scenarios.

* fix(testing): handle deferred host task completion consistently

- Added missing `else` block to ensure `_hostStartTcs.TrySetResult()` only runs when no exception occurs.
- Prevents unexpected behavior by separating successful and exceptional task completion scenarios.

* fix(testing): throw exception for invalid or unexpected transactions in `LambdaTestServer`

- Replaced `transaction.Respond` with `InvalidOperationException` for unmatched requests.
- Ensures clearer error messages for unexpected HTTP methods or unknown request types.
- Improves debugging by including request info in exception details.

* refactor(testing): rename testing handler and client for clarity

- Renamed `LambdaTestingHttpHandler` to `LambdaHttpHandler` for consistency.
- Renamed `LambdaClient` to `LambdaTestClient` to better reflect its testing purpose.

* refactor(testing): clean up and simplify LambdaApplicationFactory (#221)

* refactor(testing): remove unused client configuration and streamline server creation

- Deleted `ConfigureClient(HttpClient client)` method and related XML documentation.
- Removed commented-out and redundant `_createServer` and `ConfigureClient` references.
- Introduced `CreateServer` for internal use in `LambdaApplicationFactory`.
- Updated `DelegatedLambdaApplicationFactory` to simplify server initialization logic.

* refactor(testing): update default RuntimeApiEndpoint value in LambdaHostOptions

- Changed default `RuntimeApiEndpoint` from `localhost:3002` to `localhost` in `LambdaApplicationFactory`.

* refactor(testing): remove redundant logic and commented-out code in LambdaApplicationFactory

- Deleted unused and commented-out `EnsureServer` and `Return Services` logic.
- Simplified `SetContentRoot` by removing conditional file checks.
- Updated `GetContentRoot` to always use `GetContentRootFromAssembly`.

* refactor(testing): remove unused methods and simplify logic in LambdaApplicationFactory

- Deleted `GetContentRootFromFile` and replaced all usage with `GetContentRootFromAssembly`.
- Updated `GetContentRootFromAssembly` to use a `foreach` loop for clarity.
- Returned `[]` instead of `Array.Empty<Assembly>` to simplify empty array initialization.
- Rearranged fields in `DelegatedLambdaApplicationFactory` for consistent ordering.
- Added comments to ignored exceptions for better readability.

* refactor(testing): rename WithWebHostBuilder to WithHostBuilder in LambdaApplicationFactory

- Renamed `WithWebHostBuilder` and `WithWebHostBuilderCore` to `WithHostBuilder` and `WithHostBuilderCore`.
- Updated XML documentation comments to reflect the new method names.
- Removed unused and commented-out server creation code in `DelegatedLambdaApplicationFactory`.
- Updated example tests in `LambdaHostTest` to use the renamed `WithHostBuilder` method.

* refactor(testing): simplify server initialization in LambdaApplicationFactory

- Replaced inline server creation logic with a call to `CreateServer`.
- Removed unused variables `serializerOptions` and `routeManager` during initialization.

* refactor(testing): clean up and simplify LambdaApplicationFactory

- Removed commented-out and unused code, including `_clients` disposal and `CustomJsonSerializerContext`.
- Dropped `partial` keyword from `LambdaApplicationFactory` class declaration.
- Replaced `?.Name ?? string.Empty` with `.Name` for assembly name retrieval.
- Updated array initialization to use brackets instead of `new[]`.
- Simplified disposal logic for `Dispose` and `DisposeAsync` methods.

* feat(testing): update server implementation and enhance testing infrastructure (#230)

* fix(ci): remove sign-commits from changelog workflow (#223)

* chore(changelog): update for v1.3.0 release

- Add new features, bug fixes, and refactoring notes.
- Document maintenance updates and improvements.
- Prepare for the next release iteration.

* chore(workflows): update changelog workflow settings

- Remove `sign-commits` option from changelog workflow.
- Adjust minor formatting inconsistency in `id` field.

* feat(context): add TenantId and TraceId properties to DefaultLambdaHostContext (#224)

- Expose TenantId and TraceId from the lambda context.
- Helps in identifying tenant-specific and traceable context data.

* chore: update changelog for v1.3.1 (#225)

Co-authored-by: j-d-ha <61319894+j-d-ha@users.noreply.github.com>

* refactor(testing): replace LambdaClient with InvocationProcessor and enhance test server

- Replaced `LambdaClient` with `InvocationProcessor` for improved invocation handling and clarity.
- Updated `LambdaTestServer` to manage lifecycle and invocation processing via `InvocationProcessor`.
- Removed `LambdaClient` creation logic from `LambdaApplicationFactory`.
- Consolidated redundant methods in `LambdaTestServer` for a streamlined design.
- Introduced the `ServerState` enum to represent `LambdaTestServer`'s state transitions.

* fix(testing): correct exception type assertion and re-throw caught exception in disposal

- Updated `LambdaHostTest` to assert `AggregateException` instead of `TaskCanceledException`.
- Re-added a `throw` statement in `LambdaTestServer` to propagate caught exceptions during disposal.

* feat(testing): enhance entry point completion handling and exception propagation

- Added `FailPendingInvocations` in `InvocationProcessor` to handle failed invocations gracefully.
- Updated `ConfigureHostBuilder` to accommodate `entryPointCompletion` for better fault handling.
- Enhanced `LambdaTestServer` with entry point completion monitoring and fault propagation methods.
- Introduced `_entryPointCompletionTcs` in `DeferredHostBuilder` for tracking entry point execution state.

* feat(testing): enhance lifecycle handling and initialization in InvocationProcessor and LambdaTestServer

- Introduced `ProcessorState` enum to track `InvocationProcessor` lifecycle states.
- Enhanced `InvocationProcessor` with initialization error handling and server state transitions.
- Added `HandlePostInitErrorAsync` in `InvocationProcessor` to process initialization errors.
- Updated `LambdaTestServer.StartAsync` to wait for or fail on host initialization.
- Created `InitResponse` model to encapsulate initialization result in testing framework.
- Updated `runtime-api.yaml` with new POST `/runtime/init/error` endpoint specification.
- Extended `RequestType` and `LambdaRuntimeRouteManager` to support `PostInitError` requests.

* feat(testing): add LambdaServerV2 for async server lifecycle management

- Implemented `LambdaServerV2` class with async start, invoke, and stop methods.
- Added `DisposeAsync` method for proper resource cleanup.
- Introduced `InvokeAsync` operation with generic request/response handling.

* feat(abstractions): introduce DefaultLambdaJsonSerializerOptions for standardized JSON setup

- Added `DefaultLambdaJsonSerializerOptions` to centralize JSON serializer configuration for AWS Lambda.
- Updated `EnvelopeOptions` to use `DefaultLambdaJsonSerializerOptions.Create()` for default JSON setup.
- Removed redundant inline JSON configuration in `EnvelopeOptions`.

* refactor(testing): simplify InvocationProcessor and update related tests

- Removed unused parameters from `InvocationProcessor` constructor.
- Updated `LambdaApplicationFactory` to use `LambdaServerV2` instead of `LambdaTestServer`.
- Commented out unused test methods in `LambdaHostTest`.
- Modified `Program.cs` to comment out unneeded initialization logic.
- Enhanced `LambdaServerV2` with improved request processing methods.
- Added private methods to handle internal server logic in `LambdaServerV2`.

* refactor(testing): update InvocationProcessor and enhance LambdaServerV2 initialization

- Replaced `InitSuccess` with `InitStatus` in `InitResponse` for more detailed server initialization status.
- Enhanced `InvocationProcessor` state transitions and updated related handling to accommodate `InitStatus`.
- Refactored `LambdaServerV2` to improve lifecycle methods and handle entry point completion gracefully.
- Reinstated and updated `LambdaHostTest` method to verify exception handling on bad configuration.
- Added `InitStatus` enum to standardize server initialization state representation.

* test(testing): reinstate and update LambdaHost tests for functionality verification

- Re-enabled and updated `LambdaHost_ProcessesConcurrentInvocationsInFifoOrder` test for concurrency validation.
- Reinstated logic in `LambdaHostTest` to verify response handling and assertion correctness.
- Updated comments in `Program.cs` and adjusted initialization-related code.
- Added XML documentation to `InitResponse` and `InitStatus` for clarity and better maintainability.
- Refactored `LambdaServerV2` with internal method enhancements and exception processing optimizations.

* feat(testing): enhance LambdaServerV2 request handling and header management

- Introduced `_clientOptions` field to centralize Lambda client configuration.
- Added `GetRequestId` method for unique request ID generation with padding.
- Implemented `CreateEventResponse` to generate event responses with headers and JSON content.
- Replaced `ConcurrentDictionary` with `Channel` for `PendingInvocation` management.
- Enhanced `InvokeAsync` to process and return invocation responses with error handling.

* feat(testing): refactor LambdaServerV2 and update LambdaHostTest assertions

- Simplified `LambdaServerV2` by replacing `ConcurrentQueue` with `Channel` for invocation management.
- Refactored variable initialization and lifecycle handling for clarity and reuse.
- Updated `LambdaHostTest` to use Fluent Assertions for improved readability and maintainability.
- Introduced a private method, `CreateCompletionAsync`, for cloning and processing HTTP requests.
- Added safeguards against duplicate request IDs in `LambdaServerV2`.

* refactor(testing): extract common success response creation in LambdaServerV2

- Introduced `CreateSuccessResponse` method to centralize success response generation.
- Updated `HandlePostErrorAsync` and related methods to use `CreateSuccessResponse`.
- Improved code reuse and reduced duplication in response creation logic.

* test(lambda-host): add test case for LambdaHost error response validation

- Introduced `LambdaHost_HandlerReturnsError` to verify error handling with missing name parameter.
- Asserted error response properties, including error message and success flag.
- Ensured proper server initialization and invocation flow.

* feat(lambda-host): add validation for empty name parameter in handler

- Updated handler to throw `ArgumentNullException` if the name parameter is null or whitespace.
- Enhanced input validation to ensure proper error handling during Lambda execution.

* feat(testing): enhance LambdaServerV2 lifecycle and application management

- Added `_applicationLifetime` to manage host application lifecycle.
- Updated `Services` property to use null-forgiving operator on `_host`.
- Integrated `_applicationLifetime.StopApplication()` during server shutdown.
- Ensured proper server stop handling with `_entryPointCompletion` await logic.

* test(lambda-host): add test for verifying LambdaHost shutdown process

- Introduced `LambdaHost_CanBeShutdown` to verify proper server initialization and shutdown handling.
- Asserted initialization status, response properties, and server shutdown behavior.
- Added `OnShutdown` callback in `Program.cs` to log shutdown event.

* feat(testing): enhance LambdaServerV2 lifecycle and shutdown process

- Improved member initialization in `LambdaServerV2` for clarity and consistency.
- Added XML documentation to fields and methods for better code maintainability.
- Updated shutdown logic to use `_shutdownCts.CancelAsync()` for proper task cancellation.
- Refactored unused or duplicated logic in constructor.
- Enhanced server state management during shutdown to enforce lifecycle rules.
- Integrated `DefaultLambdaJsonSerializerOptions.Create()` for standardized JSON serialization.

* feat(testing): add `TaskHelpers` utility for task exception handling

- Introduced `WhenAny` and `WhenAll` methods to extract exceptions from completed tasks.
- Added `UnwrapAndThrow` extension for awaiting tasks and throwing aggregate exceptions.
- Improved task exception handling for testing scenarios in `AwsLambda.Host.Testing`.

* feat(testing): add DictionaryExtensions for dictionary operations

- Introduced `AddRequired` method to ensure unique key addition and throw on duplicates.
- Added `GetRequired` method to retrieve values by key and enforce key existence.
- Improved error handling for dictionary operations in testing scenarios.

* feat(testing): replace exception-handling utilities and improve invocation handling in LambdaServerV2

- Replaced custom exception-extracting methods with `TaskHelpers` utility methods (`WhenAny`, `WhenAll`).
- Simplified exception handling using `UnwrapAndThrow` for consistent error reporting.
- Streamlined `InvokeAsync` response handling by splitting success and error processing.
- Replaced duplicate `TryAdd` and `TryGetValue` calls with `AddRequired` and `GetRequired`.
- Cleaned up unused methods and redundant logic to enhance maintainability.

* feat(testing): improve error handling and lifecycle management in LambdaServerV2

- Added specific error messages for invalid state transitions during lifecycle operations.
- Enhanced `DisposeAsync` to prevent redundant `StopAsync` calls when the server is not running.
- Improved state validation logic with descriptive exceptions for `StartAsync`, `InvokeAsync`, and `StopAsync`.
- Streamlined shutdown behavior to enforce consistent state management and avoid silent failures.

* feat(testing): enhance cancellation handling and error safety in LambdaServerV2

- Added `_shutdownCts.Token` to `CancellationTokenSource.CreateLinkedTokenSource` for consistency.
- Improved `ProcessTransactionsAsync` with try-catch to handle task cancellations gracefully.
- Ensured proper cancellation behavior in `StopAsync` with `.WaitAsync(cancellationToken)`.

* feat(testing): remove unused Lambda server testing infrastructure

- Deleted `ILambdaRuntimeRouteManager`, `InvocationProcessor`, and `_ProcessorState`.
- Removed `LambdaTestServer` class and its related models and methods.
- Cleared redundant internal classes like `LambdaBootstrapRequest` from `AwsLambda.Host.Testing`.
- Cleaned up unnecessary internal abstractions to streamline testing code and reduce maintenance burden.

* refactor(testing): rename LambdaServerV2 to LambdaTestServer for clarity

- Replaced all occurrences of `LambdaServerV2` with `LambdaTestServer` across testing infrastructure.
- Updated references in `LambdaApplicationFactory` and related methods to use `LambdaTestServer`.
- Adjusted test cases to align with the updated `LambdaTestServer` naming convention.
- Updated XML documentation and comments to reflect the new naming.

* feat(testing): update Lambda server options and invocation handling

- Renamed `LambdaClientOptions` to `LambdaServerOptions` and refactored related usage.
- Updated invocation timeout handling to use `FunctionTimeout` in `LambdaServerOptions`.
- Refined `InvokeAsync` method to include `traceId` and improved error handling for pending IDs.
- Enhanced response creation with additional headers and updated `traceId` logic.
- Removed unused properties like `Date`, `InvocationTimeout`, and `TransferEncodingChunked`.
- Improved cancellation logic with `LinkedCtsWithInvocationDeadline` and `LinkedCts` methods.
- Introduced `LambdaTestServerExtensions` for simplified invocation in test cases.

* feat(testing): remove LambdaInvocationOptions class

- Deleted `LambdaInvocationOptions` class from `AwsLambda.Host.Testing`.
- Removed related properties like `AdditionalHeaders`, `FunctionArn`, `FunctionTimeout`, and `TraceId`.
- Streamlined testing code by eliminating unused infrastructure.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* refactor(testing): rename namespaces and project for consistency

- Renamed `AwsLambda.Host.Testing` namespace to `MinimalLambda.Testing` across all files.
- Updated project file to reflect the new project name: `MinimalLambda.Testing`.
- Adjusted solution references and project paths to align with the renamed project and namespace.
- Added `DefaultLambdaJsonSerializerOptions` in `MinimalLambda.Abstractions` and updated related dependencies.
- Replaced all usages of `AwsLambda.Host.Testing` namespace in related files and tests.
- Updated `README.md` to reflect the new project name and namespace.

* feat(testing): update dependencies and project references for MinimalLambda

- Added references to `MinimalLambda.Options` and `MinimalLambda.Builder.Extensions`.
- Updated project description in `.csproj` to align with `MinimalLambda`.
- Replaced `AwsLambda.Host` references with `MinimalLambda` in project and solution files.

* feat(testing): add MinimalLambda project references and update usages

- Added project references to `MinimalLambda.Abstractions` and `MinimalLambda` in the `.csproj`.
- Replaced `AwsLambda.Host` with `MinimalLambda` namespaces in `Program.cs`.
- Added `MinimalLambda.Options` to dependencies in `LambdaHostTest.cs` for new functionality.

* chore(deps): update Microsoft.Extensions.Hosting package versions

- Bumped `Microsoft.Extensions.Hosting` to `10.0.1`.
- Bumped `Microsoft.Extensions.Hosting.Abstractions` to `10.0.1`.
- Simplified `Directory.Packages.props` by consolidating package version entries.

* refactor(testing): update project references and namespaces for MinimalLambda

- Replaced `AwsLambda.Host` project references with `MinimalLambda` in `.csproj` files.
- Updated namespaces from `Lambda.Host.Example.HelloWorld` to `MinimalLambda.Example.HelloWorld`.
- Removed unused dependencies `System.Net.Http` and `System.Text.RegularExpressions` from `Tests.csproj`.

* refactor(testing): replace ClientOptions with ServerOptions across factory and server

- Replaced `LambdaApplicationFactoryClientOptions` with `LambdaServerOptions` for consistency.
- Updated `LambdaTestServer` constructor to accept `LambdaServerOptions`.
- Propagated `ServerOptions` throughout related classes and methods.
- Removed commented-out and unused code for better clarity and maintenance.

* refactor(testing): enhance resource cleanup and documentation in factory and server

- Added support for async and sync disposal of `_host` in `LambdaTestServer`.
- Improved inline XML documentation across `LambdaApplicationFactory` and related classes.
- Removed unused and redundant `ServerOptions` getter in `LambdaApplicationFactory`.
- Refactored `WithHostBuilderCore` to enhance flexibility and clarity in factory chaining.
- Updated comments to better describe factory behaviors and Lambda testing configurations.

* feat(testing): enhance XML documentation for Lambda test server and invocation response

- Added comprehensive XML summaries, remarks, and examples to `LambdaTestServer` methods.
- Documented the lifecycle, invocation handling, and state transitions in `LambdaTestServer`.
- Improved `InvocationResponse` class documentation with clear descriptions and usage guidelines.

* refactor(testing): reorder fields and add null-forgiveness in LambdaTestServer

- Reordered `_serverOptions` field initialization for logical grouping of fields.
- Added null-forgiveness operator (`!`) for `StopApplication()` to ensure runtime safety.
- Removed unnecessary null-forgiveness usages with non-null values in `switch` statements.

* refactor(testing): improve shutdown and resource disposal in LambdaTestServer

- Added completion of `_pendingInvocationIds` channel during shutdown for consistency.
- Canceled and disposed `_shutdownCts` to enhance resource cleanup.
- Updated host disposal logic to prefer async disposal and fallback to sync.
- Removed unused `LambdaApplicationFactoryClientOptions` class.

* refactor(testing): simplify README for MinimalLambda.Testing

- Replaced verbose documentation with a concise project overview.
- Updated project name and namespace to reflect `MinimalLambda.Testing`.
- Removed outdated examples and implementation details.

* docs(testing): expand README with usage details and examples

- Added detailed documentation for MinimalLambda.Testing features and setup.
- Included quick start guide with code examples for end-to-end testing.
- Highlighted key features such as host customization and runtime simulation.
- Provided installation instructions and links to related packages.
- Improved clarity by organizing examples and feature explanations.

* docs(testing): clarify README description for LambdaApplicationFactory and LambdaTestServer

- Expanded explanation of `LambdaApplicationFactory` and `LambdaTestServer` alignment with ASP.NET Core `WebApplicationFactory`.
- Improved documentation clarity with updated descriptions of runtime simulation and invocation flow.

* docs(testing): remove outdated examples section from README

- Removed the `Examples` section from `README.md` referring to `AwsLambda.Host.Example.Testing`.
- Simplified documentation to focus on high-level features and related packages.

* docs(testing): update package description in project file

- Revised `<Description>` in `MinimalLambda.Testing.csproj` to better reflect its purpose.
- Changed description to "In-memory testing harness for MinimalLambda."

* docs(testing): update example in README to use "Hello World"

- Modified the invocation example in the `README.md` for consistency with typical greetings.
- Replaced "Jonas" with "World" in test case to align with standard conventions for examples.

* refactor(testing): improve accessibility, disposal, and route handling

- Changed `TryMatch` method to `internal` for improved encapsulation.
- Adjusted `RouteTemplate` class to `sealed` for better performance and clarity.
- Updated cancellation handling in `LambdaHttpHandler` to use `await using` for proper disposal.
- Added support for cancellation tokens in `TaskCompletionSource.TrySetCanceled`.

* feat(testing): add unit tests and new support features for MinimalLambda

- Introduced `MinimalLambda.Testing.UnitTests` project with `SimpleLambdaTests`.
- Added tests for `SimpleLambda`, covering input validation and response handling.
- Refactored `InvocationResponse` class to support inheritance and centralized error handling.
- Updated `LambdaTestServer` with options for no-response and no-event invocation scenarios.
- Enhanced `LambdaApplicationFactory` to support cancellation tokens.
- Included new XML documentation for additional methods and response scenarios.
- Updated solution and project files to include the new unit tests and dependencies.

* feat(testing): add unit tests for new lambda scenarios

- Added projects for `NoEventLambda`, `DiLambda`, and `NoResponseLambda`.
- Introduced unit test setup with corresponding `Program.cs` and `appsettings.json` files.
- Updated `LambdaTestServer` to use public `State` property instead of private `_state` field.
- Enhanced solution file to include new lambda project references and build configurations.

* feat(testing): add internal visibility for unit testing in lambda projects

- Introduced `AssemblyInfo.cs` files to enable `InternalsVisibleTo` for unit testing.
- Applied changes to `NoResponseLambda`, `NoEventLambda`, `SimpleLambda`, and `DiLambda` projects.

* feat(DiLambda): implement dependency injection and lifecycle management

- Added `ILifecycleService` and `IService` interfaces with corresponding implementations.
- Integrated `Startup` and `Shutdown` hooks using `OnInit` and `OnShutdown` methods.
- Enhanced handler to process `Request` and generate `Response` with timestamp.
- Updated `Program.cs` to register services and manage lifecycle events.

* feat(tests): update NoEventLambda handler to return detailed response

- Refactored handler to produce a `Response` object with message and UTC timestamp.
- Added `Response` record to encapsulate response message and timestamp fields.

* feat(tests): update NoResponseLambda to process Request type

- Modified `MapHandler` to accept a `Request` record instead of a string.
- Added internal `Request` record definition with a `Name` property.

* feat(DiLambda): add logging and middleware support

- Injected `ILogger<DiLambda>` into lifecycle events, middleware, and lambda handler.
- Added logging to `OnInit`, `OnShutdown`, middleware, and handler for better traceability.
- Introduced middleware to log execution timing before and after handler invocation.

* feat(testing): enhance disposal and cancellation handling in test infrastructure

- Added `_disposed` flag to `LambdaTestServer` to prevent repeated disposal operations.
- Updated `DisposeAsync` in `LambdaTestServer` to suppress finalization and ensure safe disposal.
- Introduced `_stoppingToken` property in `LambdaApplicationFactory` for improved cancellation handling.
- Added `WithCancelationToken` method to propagate cancellation signals to `LambdaTestServer` components.
- Enhanced `DisposeAsync` in `LambdaApplicationFactory` to stop and dispose of the host instance gracefully.
- Updated `LambdaTestServer` instantiation to accept the stopping token for efficient shutdown.

* feat(tests): refactor `SimpleLambdaTests` for improved cancellation handling

- Updated `SimpleLambdaTests` to use `LambdaApplicationFactory` with cancellation tokens.
- Replaced constructor injection of `LambdaApplicationFactory` with `await using` pattern.
- Simplified test setup by initializing factory and test server inline.

* feat(tests): validate input for `SimpleLambda` handler

- Updated `SimpleLambda` handler to throw an exception if the input name is null or whitespace.
- Added input validation for better error handling and robustness.

* feat(testing): extend `LambdaTestServer` methods with event response and default flags

- Updated `InvokeAsync` and `InvokeNoEventAsync` to include a default flag parameter.
- Enhanced method signatures to provide consistent behavior with explicit flag control.

* feat(tests): add concurrency and error propagation tests for `SimpleLambda`

- Introduced new tests to verify `SimpleLambda` behavior under concurrent invocations.
- Added tests to ensure proper error propagation and handling in `SimpleLambda`.
- Updated `SimpleLambdaTests` to utilize `LambdaApplicationFactory` for consistent setup and teardown.

* feat(testing): improve `LambdaTestServer` lifecycle handling and initialization concurrency

- Added `_startSemaphore` to enforce concurrency during server initialization.
- Moved `_disposed` flag and `State` property declarations for improved organization.
- Updated `DisposeAsync` to use a switch-case for better null checks and disposal handling.
- Adjusted `StartAsync` to ensure proper lifecycle state validation with semaphore protection.
- Modified `InvokeAsync` to handle server initialization if invoked in the `Created` state.

* feat(tests): add cancellation test for `SimpleLambda` with pre-canceled token

- Introduced `SimpleLambda_WithPreCanceledToken_CancelsInvocation` test.
- Verified invocation is canceled when provided with a pre-canceled `CancellationToken`.
- Used `LambdaApplicationFactory` to simplify setup and ensure consistent test behavior.

* refactor(examples): remove `AwsLambda.Host.Example.Testing` examples and related tests

- Deleted `Lambda` and `Tests` directories under the `examples` folder.
- Removed Lambda example dependencies from the solution file.
- Updated `MinimalLambda.sln` to exclude the `AwsLambda.Host.Example.Testing` projects.
- Cleaned up unused resources, configurations, and project references.

* refactor(testing): reorganize properties and add missing members to `DeferredHostBuilder` and `PendingInvocation`

- Reordered private fields in `DeferredHostBuilder` for consistency and clarity.
- Added `EntryPointCompletion` to `DeferredHostBuilder` for external access to completion status.
- Adjusted property order in `PendingInvocation` to align with coding standards.
- Added `DeadlineUtc` initialization in `PendingInvocation` with a concise summary.
- Improved whitespace and code formatting in `HostFactoryResolver` for better readability.
- Optimized lambda expressions and argument parsing logic in `HostFactoryResolver`.

* feat(tests): add support for multiple frameworks and enhance testing for lambdas

- Updated projects to target `net8.0`, `net9.0`, and `net10.0` for broader framework compatibility.
- Added `NoResponseLambdaTests` to verify `NoResponseLambda` behavior and response handling.
- Refactored `SimpleLambdaTests` to improve error validation and ensure proper exception handling.
- Fixed incorrect lambda mapping in `NoResponseLambda` for request handling.
- Enhanced project references to include `NoResponseLambda` for accurate test coverage.

* feat(tests): add `NoEventLambdaTests` and expand framework compatibility

- Added `NoEventLambdaTests` to validate `NoEventLambda` responses and behavior.
- Updated `MinimalLambda.Testing.UnitTests.NoEventLambda` to target `net8.0`, `net9.0`, and `net10.0`.
- Modified project references to include `NoEventLambda` for improved test coverage.
- Replaced `Response` model with `NoEventLambdaResponse` in `NoEventLambda` handler mapping.

* feat(tests): add `DiLambdaTests` and update framework compatibility

- Introduced `DiLambdaTests` to validate `DiLambda` behavior and response mapping.
- Updated `MinimalLambda.Testing.UnitTests.DiLambda` to target `net8.0`, `net9.0`, and `net10.0`.
- Modified project references to include `DiLambda` for extended test coverage.
- Refactored lambda mapping in `DiLambda` to use `DiLambdaRequest` and `DiLambdaResponse`.
- Improved `LambdaTestServer` disposal logic with better error handling during shutdown.
- Fixed parameter order in `InvokeAsync` and related extension methods for consistent usage.

* feat(tests): add advanced lifecycle tests for `DiLambda`

- Introduced tests for initialization states, error handling, and shutdown behavior in `DiLambda`.
- Added `DiLambda_InitStopped`, `DiLambda_InitThrowsException`, and `DiLambda_ShutdownThrowsException`.
- Created `AutoNSubstituteDataAttribute` for simplified test data generation with AutoFixture and NSubstitute.
- Updated `LambdaTestServer` to handle post-init errors and improved shutdown concurrency checks.
- Modified project references to include `AutoFixture.Xunit3` and `AutoFixture.AutoNSubstitute`.
- Enhanced `AssemblyInfo` for proxy generation support with `DynamicProxyGenAssembly2`.

* fix(runtime): handle `TaskCanceledException` more accurately during Lambda shutdown

- Added conditional check to distinguish cancellation due to timeout from LambdaBootstrap-related exceptions.
- Improved error reporting for graceful shutdown failures caused by cancellation.

* feat(testing): add cancellation token support to `LambdaTestingHttpHandler`

- Added `CancellationToken` to `LambdaTestingHttpHandler` constructor for better shutdown handling.
- Updated `SendAsync` to use a combined cancellation token for proper transaction management.
- Modified `LambdaTestServer` to pass `_shutdownCts.Token` to `LambdaTestingHttpHandler`.

* fix(testing): improve exception handling and shutdown reliability

- Updated `DiLambdaTests` to include better validation with nested `AggregateException`.
- Refactored `TaskHelpers` to handle additional exception scenarios and improve fault handling.
- Simplified shutdown logic in `LambdaTestServer` by removing unused `shutdownTask`.

* fix(tests): simplify exception assertion in `SimpleLambdaTests`

- Updated exception validation to directly assert `InvalidOperationException` instead of `AggregateException`.
- Used `WithMessage` for improved readability and precision in error message checks.

* fix(tests): refactor `DiLambdaTests` and improve test configuration

- Replaced `[Theory]` with `[Fact]` for `DiLambda_InitStopped` and `DiLambda_InitThrowsException`.
- Introduced `Substitute.For<ILifecycleService>` for proper mocking in both tests.
- Adjusted lifecycle service initialization to enhance test independence.
- Fixed test assembly settings to disable parallelization in `AssemblyInfo.cs`.
- Adjusted method call order in `LambdaTestServer` for improved lifecycle state handling.

* feat(tests): enhance `NoEventLambda` configuration and add new test case

- Updated `NoEventLambda` to utilize `IConfiguration` for dynamic message handling in the handler.
- Added a new test, `NoEvent_ConfigurationCanBeOverwritten`, to validate custom configuration support.
- Introduced in-memory configuration dictionary for improved test flexibility and coverage.

* feat(tests): extend `DiLambdaTests` with Autofac container support

- Added tests to verify that the DI container in `DiLambda` can be replaced with Autofac.
- Introduced `DiLambda_DiContainerCanBeReplaced` and `DiLambda_DiContainerCanBeReplacedWithFactory`.
- Updated project files to reference `Autofac.Extensions.DependencyInjection` package (version 10.0.0).

* feat(tests): improve `NoResponseLambda` test coverage and enhance shutdown reliability

- Added `NoResponseLambda_ServicesIsAccessible` to ensure DI services can be resolved.
- Introduced `NoResponseLambda_DisposeCanBeCalledMultipleTimes` to validate safe multi-disposal.
- Updated `LambdaTestServer` shutdown to suppress exceptions for better reliability.

* refactor(testing): remove unused `Fail` method from `LambdaHttpTransaction`

- Deleted the `Fail` method, which is no longer used in the codebase.
- Simplified the `LambdaHttpTransaction` class by reducing unnecessary methods.

* refactor(testing): remove unused `CreateHostBuilder` method and simplify `LambdaApplicationFactory`

- Removed the `CreateHostBuilder` method, which was no longer being used in the codebase.
- Eliminated references to `CreateHostBuilder` in the `DelegatedLambdaApplicationFactory` class.
- Updated `GlobalUsings.cs` by removing …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: refactor Code refactoring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant