diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 281043f636..78b65a0e74 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,261 +1,1018 @@ -# GitHub Copilot Instructions for TUnit - -## IMPORTANT: Read This First - -When assisting with TUnit development: -1. **ALWAYS** maintain behavioral parity between source-generated and reflection modes -2. **ALWAYS** run `dotnet test TUnit.PublicAPI` when modifying public APIs in TUnit.Core, TUnit.Engine, or TUnit.Playwright -3. **ALWAYS** run source generator tests when changing source generator output -4. **NEVER** use VSTest APIs - use Microsoft.Testing.Platform instead -5. **PREFER** performance over convenience - this framework may be used by millions -6. **FOLLOW** modern C# patterns and the coding standards outlined below - -## Repository Overview - -TUnit is a modern .NET testing framework designed as an alternative to xUnit, NUnit, and MSTest. It leverages the newer Microsoft.Testing.Platform instead of the legacy VSTest framework, providing improved performance and modern .NET capabilities. - -## Key Architecture Concepts - -### Dual Execution Modes -TUnit operates in two distinct execution modes that must maintain behavioral parity: - -1. **Source Generated Mode**: Uses compile-time source generation for optimal performance -2. **Reflection Mode**: Uses runtime reflection for dynamic scenarios - -**Critical Rule**: Both modes must produce identical end-user behavior. Any feature or bug fix must be implemented consistently across both execution paths. - -### Core Components -- **TUnit.Core**: Core abstractions and interfaces -- **TUnit.Engine**: Test discovery and execution engine -- **TUnit.Core.SourceGenerator**: Compile-time test generation -- **TUnit.Assertions**: Fluent assertion library -- **TUnit.Analyzers**: Roslyn analyzers for compile-time validation - -## Coding Standards and Best Practices - -### .NET Modern Syntax -- Use collection initializers: `List list = []` instead of `List list = new()` -- Leverage pattern matching, records, and modern C# features -- Use file-scoped namespaces where appropriate -- Prefer `var` for local variables when type is obvious - -### Code Formatting -- Always use braces for control structures, even single-line statements: - ```csharp - if (condition) - { - DoSomething(); - } - ``` -- Maintain consistent spacing between methods and logical code blocks -- Use expression-bodied members for simple properties and methods -- Follow standard .NET naming conventions (PascalCase for public members, _camelCase for private fields) -- Don't pollute code with unnecessary comments; use meaningful names instead - -### Performance Considerations -- **Critical**: TUnit may be used by millions of developers - performance is paramount -- Avoid unnecessary allocations in hot paths -- Use `ValueTask` over `Task` for potentially synchronous operations -- Leverage object pooling for frequently created objects -- Consider memory usage patterns, especially in test discovery and execution - -### Architecture Principles -- **Single Responsibility Principle**: Classes should have one reason to change -- **Avoid Over-engineering**: Prefer simple, maintainable solutions -- **Composition over Inheritance**: Use dependency injection and composition patterns -- **Immutability**: Prefer immutable data structures where possible - -## Testing Framework Specifics - -### Microsoft.Testing.Platform Integration -- Use Microsoft.Testing.Platform APIs instead of VSTest -- Test filtering syntax: `dotnet test -- --treenode-filter /Assembly/Namespace/ClassName/TestName` -- Understand the platform's execution model and lifecycle hooks - -### Data Generation and Attributes -- Support multiple data source attributes: `[Arguments]`, `[MethodDataSource]`, `[ClassDataSource]`, etc. -- Reuse existing data generation logic instead of duplicating code -- Maintain consistency between reflection and source-generated approaches - -### Test Discovery and Execution -- Test discovery should be fast and efficient -- Support dynamic test generation while maintaining type safety -- Handle edge cases gracefully (generic types, inheritance, etc.) - -## Common Patterns and Conventions - -### Error Handling -- Use specific exception types with meaningful messages -- Provide contextual information in error messages for debugging -- Handle reflection failures gracefully with fallback mechanisms - -### Async/Await -- Use `ValueTask` for performance-critical async operations -- Properly handle `CancellationToken` throughout the pipeline -- Avoid async void except for event handlers - -### Reflection Usage -- Use `[UnconditionalSuppressMessage]` attributes appropriately for AOT/trimming -- Cache reflection results where possible for performance -- Provide both reflection and source-generated code paths - -## Code Review Guidelines - -### When Adding New Features -1. Implement in both source-generated and reflection modes -2. Add corresponding analyzer rules if applicable -3. Include comprehensive tests covering edge cases -4. Verify performance impact with benchmarks if relevant -5. Update documentation and ensure API consistency - -### When Fixing Bugs -1. Identify if the issue affects one or both execution modes -2. Write a failing test that reproduces the issue -3. Fix the bug in all affected code paths -4. Verify the fix doesn't introduce performance regressions - -### Code Quality Checklist -- [ ] No unused using statements -- [ ] Proper null handling (nullable reference types) -- [ ] Appropriate access modifiers -- [ ] XML documentation for public APIs -- [ ] No magic strings or numbers (use constants) -- [ ] Proper disposal of resources - -## Testing and Validation +# TUnit Development Guide for AI Assistants + +## Table of Contents +- [Critical Rules - READ FIRST](#critical-rules---read-first) +- [Quick Reference](#quick-reference) +- [Project Overview](#project-overview) +- [Architecture](#architecture) +- [Development Workflow](#development-workflow) +- [Code Style Standards](#code-style-standards) +- [Testing Guidelines](#testing-guidelines) +- [Performance Requirements](#performance-requirements) +- [Common Patterns](#common-patterns) +- [Troubleshooting](#troubleshooting) + +--- + +## Critical Rules - READ FIRST + +### The Five Commandments + +1. **DUAL-MODE IMPLEMENTATION IS MANDATORY** + - Every feature MUST work identically in both execution modes: + - **Source-Generated Mode**: Compile-time code generation via `TUnit.Core.SourceGenerator` + - **Reflection Mode**: Runtime discovery via `TUnit.Engine` + - Test both modes explicitly. Never assume parity without verification. + - If you only implement in one mode, the feature is incomplete and MUST NOT be merged. + +2. **SNAPSHOT TESTS ARE NON-NEGOTIABLE** + - After ANY change to source generator output: + ```bash + dotnet test TUnit.Core.SourceGenerator.Tests + # Review .received.txt files, then: + for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done # Linux/macOS + for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" # Windows + ``` + - After ANY public API change (TUnit.Core, TUnit.Engine, TUnit.Assertions): + ```bash + dotnet test TUnit.PublicAPI + # Review and accept snapshots as above + ``` + - Commit ALL `.verified.txt` files. These are the source of truth. -### Test Categories -- Unit tests for individual components -- Integration tests for cross-component functionality -- Performance benchmarks for critical paths -- Analyzer tests for compile-time validation -- Source generator snapshot tests -- Public API snapshot tests +3. **NEVER USE VSTest APIs** + - This project uses **Microsoft.Testing.Platform** exclusively + - VSTest is legacy and incompatible with TUnit's architecture + - If you see `Microsoft.VisualStudio.TestPlatform`, it's wrong + +4. **PERFORMANCE IS A FEATURE** + - TUnit is used by millions of tests daily + - Every allocation in discovery/execution hot paths matters + - Profile before and after for any changes in critical paths + - Use `ValueTask`, object pooling, and cached reflection + +5. **AOT/TRIMMING COMPATIBILITY IS REQUIRED** + - All code must work with Native AOT and IL trimming + - Use `[DynamicallyAccessedMembers]` and `[UnconditionalSuppressMessage]` appropriately + - Test changes with AOT-compiled projects when touching reflection + +--- + +## Quick Reference + +### ⚠️ CRITICAL: TUnit.TestProject Testing Rules + +**DO NOT run `TUnit.TestProject` without filters!** Many tests are intentionally designed to fail to verify error handling, diagnostics, and edge cases. + +```bash +# ❌ WRONG - Will show many "failures" (this is expected behavior) +cd TUnit.TestProject && dotnet run +cd TUnit.TestProject && dotnet test + +# ✅ CORRECT - Always use targeted filters when testing TUnit.TestProject +cd TUnit.TestProject && dotnet run -- --treenode-filter "/*/*/SpecificClass/*" +cd TUnit.TestProject && dotnet run -- --treenode-filter "/*/*/*/*[Category!=Performance]" + +# ✅ CORRECT - Test other test projects normally (they don't have intentional failures) +dotnet test TUnit.Engine.Tests +dotnet test TUnit.Assertions.Tests +dotnet test TUnit.Core.SourceGenerator.Tests +``` + +**Why TUnit.TestProject is special:** +- Contains negative test cases (tests that verify failures work correctly) +- Tests error messages, diagnostics, and exception handling +- Performance tests excluded by default +- Integration tests covering all edge cases + +**Golden Rule**: When verifying changes, use `dotnet test` (which excludes TUnit.TestProject), OR run TUnit.TestProject with specific `--treenode-filter` patterns. + +--- + +### Most Common Commands +```bash +# Run all tests (automatically excludes TUnit.TestProject integration tests) +dotnet test + +# Test source generator + accept snapshots +dotnet test TUnit.Core.SourceGenerator.Tests +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done + +# Test public API + accept snapshots +dotnet test TUnit.PublicAPI +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done + +# Run specific test by tree node filter +dotnet test -- --treenode-filter "/Assembly/Namespace/ClassName/TestName" + +# Run tests excluding performance tests +dotnet test -- --treenode-filter "/*/*/*/*[Category!=Performance]" + +# Build in release mode +dotnet build -c Release + +# Test AOT compilation +dotnet publish -c Release -p:PublishAot=true +``` + +### Snapshot Workflow Quick Ref +``` +┌─────────────────────────────────────────────────────────┐ +│ 1. Make change to source generator or public API │ +│ 2. Run relevant test: dotnet test [Project] │ +│ 3. If snapshots differ, review .received.txt files │ +│ 4. If changes are correct, rename to .verified.txt │ +│ 5. Commit .verified.txt files │ +│ 6. NEVER commit .received.txt files │ +└─────────────────────────────────────────────────────────┘ +``` + +### Test Filter Syntax +```bash +# Single test +--treenode-filter "/TUnit.TestProject/Namespace/ClassName/TestMethodName" + +# All tests in a class +--treenode-filter "/*/*/ClassName/*" + +# Multiple patterns (OR logic) +--treenode-filter "Pattern1|Pattern2" + +# Exclude by category +--treenode-filter "/*/*/*/*[Category!=Performance]" +``` + +--- + +## Project Overview + +### What is TUnit? + +TUnit is a **modern .NET testing framework** that prioritizes: +- **Performance**: Source-generated tests, parallel by default +- **Modern .NET**: Native AOT, trimming, latest C# features +- **Microsoft.Testing.Platform**: Not VSTest (legacy) +- **Developer Experience**: Fluent assertions, minimal boilerplate + +### Key Differentiators +- **Compile-time test discovery** via source generators +- **Parallel execution** by default with dependency management +- **Dual execution modes** (source-gen + reflection) for flexibility +- **Built-in assertions** with detailed failure messages +- **Property-based testing** support +- **Dynamic test variants** for data-driven scenarios -### Source Generator Changes +--- -**CRITICAL**: When modifying what the source generator emits: +## Architecture + +### Execution Modes + +TUnit has two execution paths that **MUST** behave identically: + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ USER TEST CODE │ +│ [Test] public void MyTest() { ... } │ +└────────────┬────────────────────────────────┬───────────────────┘ + │ │ + ▼ ▼ + ┌────────────────────┐ ┌─────────────────────┐ + │ SOURCE-GENERATED │ │ REFLECTION MODE │ + │ MODE │ │ │ + │ │ │ │ + │ TUnit.Core. │ │ TUnit.Engine │ + │ SourceGenerator │ │ │ + │ │ │ │ + │ Generates code at │ │ Discovers tests at │ + │ compile time │ │ runtime via │ + │ │ │ reflection │ + └─────────┬──────────┘ └──────────┬──────────┘ + │ │ + │ │ + └───────────────┬───────────────┘ + ▼ + ┌──────────────────┐ + │ TUnit.Engine │ + │ (Execution) │ + └──────────────────┘ + │ + ▼ + ┌──────────────────┐ + │ Microsoft.Testing│ + │ .Platform │ + └──────────────────┘ +``` -1. **Run the source generator tests**: +### Core Projects + +| Project | Purpose | Notes | +|---------|---------|-------| +| **TUnit.Core** | Abstractions, interfaces, attributes | Public API surface | +| **TUnit.Engine** | Test discovery & execution (reflection) | Runtime path | +| **TUnit.Core.SourceGenerator** | Compile-time test generation | Compile-time path | +| **TUnit.Assertions** | Fluent assertion library | Separate from core | +| **TUnit.Assertions.SourceGenerator** | Generates custom assertions | Extensibility | +| **TUnit.Analyzers** | Roslyn analyzers & code fixes | Compile-time safety | +| **TUnit.PropertyTesting** | Property-based testing support | New feature | +| **TUnit.Playwright** | Playwright integration | Browser testing | + +### Roslyn Version Projects +- `*.Roslyn414`, `*.Roslyn44`, `*.Roslyn47`: Multi-targeting for different Roslyn versions +- Ensures compatibility across VS versions and .NET SDK versions + +### Test Projects +- **TUnit.TestProject**: Integration tests (uses TUnit to test itself) +- **TUnit.Engine.Tests**: Engine-specific tests +- **TUnit.Assertions.Tests**: Assertion library tests +- **TUnit.Core.SourceGenerator.Tests**: Source generator snapshot tests +- **TUnit.PublicAPI**: Public API snapshot tests (prevents breaking changes) + +--- + +## Development Workflow + +### Adding a New Feature + +#### Step-by-Step Process + +1. **Design Phase** + ``` + ┌─────────────────────────────────────────────────────┐ + │ Ask yourself: │ + │ • Does this require dual-mode implementation? │ + │ • Will this affect public API? │ + │ • Does this need an analyzer rule? │ + │ • What's the performance impact? │ + │ • Is this AOT/trimming compatible? │ + └─────────────────────────────────────────────────────┘ + ``` + +2. **Implementation** + - **Write tests FIRST** (TDD approach) + - Implement in `TUnit.Core` (if new abstractions needed) + - Implement in `TUnit.Core.SourceGenerator` (source-gen path) + - Implement in `TUnit.Engine` (reflection path) + - Add analyzer rule if misuse is possible + +3. **Verification** ```bash - dotnet test TUnit.Core.SourceGenerator.Tests + # Run all tests + dotnet test + + # If source generator changed, accept snapshots + cd TUnit.Core.SourceGenerator.Tests + dotnet test + # Review .received.txt files + for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done + + # If public API changed, accept snapshots + cd TUnit.PublicAPI + dotnet test + # Review .received.txt files + for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done ``` -2. **Accept any changed snapshots**: - - The test will generate `.received.txt` files showing the new generated output - - Review these files to ensure your changes are intentional and correct - - Convert the received files to verified files: - ```bash - # Windows - for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" - - # Linux/macOS - for file in *.received.txt; do mv "$file" "${file%.received.txt}.verified.txt"; done - ``` - - Or manually rename each `.received.txt` file to `.verified.txt` +4. **Performance Check** + ```bash + # Run benchmarks (if touching hot paths) + cd TUnit.Performance.Tests + dotnet run -c Release --framework net9.0 + ``` + +5. **AOT Verification** (if touching reflection) + ```bash + cd TUnit.TestProject + dotnet publish -c Release -p:PublishAot=true --use-current-runtime + ``` + +### Fixing a Bug -3. **Commit the updated snapshots**: - - Include the updated `.verified.txt` files in your commit - - These snapshots ensure source generation consistency +#### Step-by-Step Process -### Public API Changes +1. **Reproduce** + - Write a failing test that demonstrates the bug + - Identify which execution mode(s) are affected -**CRITICAL**: When modifying any public API in TUnit.Core, TUnit.Engine, or TUnit.Playwright (adding, removing, or changing public methods, properties, or types): +2. **Fix** + - Fix in source generator (if affected) + - Fix in reflection engine (if affected) + - Ensure both modes now pass the test -1. **Run the Public API test**: +3. **Verify No Regression** ```bash - dotnet test TUnit.PublicAPI + # Run full test suite + dotnet test + + # Check performance hasn't regressed + # (if fix is in hot path) ``` -2. **Update the API snapshots**: - - The test will generate `.received.txt` files showing the current API surface - - Review these files to ensure your changes are intentional - - Convert the received files to verified files: - ```bash - # Windows - for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" - - # Linux/macOS - for file in *.received.txt; do mv "$file" "${file%.received.txt}.verified.txt"; done - ``` - - Or manually rename each `.received.txt` file to `.verified.txt` +4. **Accept Snapshots** (if applicable) + - Follow snapshot workflow above + +--- + +## Code Style Standards + +### Modern C# - Required Syntax + +```csharp +// ✅ CORRECT: Use collection expressions (C# 12+) +List items = []; +string[] array = ["a", "b", "c"]; +Dictionary dict = []; + +// ❌ WRONG: Don't use old initialization syntax +List items = new List(); +string[] array = new string[] { "a", "b", "c" }; + +// ✅ CORRECT: Use var when type is obvious +var testName = GetTestName(); +var results = ExecuteTests(); + +// ❌ WRONG: Explicit types for obvious cases +string testName = GetTestName(); +List results = ExecuteTests(); + +// ✅ CORRECT: Always use braces, even for single lines +if (condition) +{ + DoSomething(); +} + +// ❌ WRONG: No braces +if (condition) + DoSomething(); + +// ✅ CORRECT: File-scoped namespaces +namespace TUnit.Core.Features; + +public class MyClass { } + +// ❌ WRONG: Traditional namespace blocks (unless multiple namespaces in file) +namespace TUnit.Core.Features +{ + public class MyClass { } +} + +// ✅ CORRECT: Pattern matching +if (obj is TestContext context) +{ + ProcessContext(context); +} + +// ✅ CORRECT: Switch expressions +var result = status switch +{ + TestStatus.Passed => "✓", + TestStatus.Failed => "✗", + TestStatus.Skipped => "⊘", + _ => "?" +}; + +// ✅ CORRECT: Target-typed new +TestContext context = new(testName, metadata); + +// ✅ CORRECT: Record types for immutable data +public record TestMetadata(string Name, string FilePath, int LineNumber); + +// ✅ CORRECT: Required properties (C# 11+) +public required string TestName { get; init; } + +// ✅ CORRECT: Raw string literals for multi-line strings +string code = """ + public void TestMethod() + { + Assert.That(value).IsEqualTo(expected); + } + """; +``` + +### Naming Conventions + +```csharp +// Public members: PascalCase +public string TestName { get; } +public void ExecuteTest() { } +public const int MaxRetries = 3; + +// Private fields: _camelCase +private readonly ITestExecutor _executor; +private string _cachedResult; + +// Local variables: camelCase +var testContext = new TestContext(); +int retryCount = 0; + +// Type parameters: T prefix for single, descriptive for multiple +public class Repository { } +public class Converter { } + +// Interfaces: I prefix +public interface ITestExecutor { } -3. **Commit the updated snapshots**: - - Include the updated `.verified.txt` files in your commit - - These snapshots track the public API surface and prevent accidental breaking changes +// Async methods: Async suffix +public async Task ExecuteTestAsync(CancellationToken ct) { } +``` -### Compatibility Testing -- Test against multiple .NET versions (.NET 6, 8, 9+) -- Verify AOT and trimming compatibility -- Test source generation in various project configurations +### Async/Await Patterns + +```csharp +// ✅ CORRECT: Use ValueTask for potentially sync operations +public ValueTask ExecuteAsync(CancellationToken ct) +{ + if (IsCached) + { + return new ValueTask(cachedResult); + } + + return ExecuteAsyncCore(ct); +} + +// ✅ CORRECT: Always accept CancellationToken +public async Task RunTestAsync(CancellationToken cancellationToken) +{ + await PrepareAsync(cancellationToken); + return await ExecuteAsync(cancellationToken); +} + +// ✅ CORRECT: ConfigureAwait(false) in library code +var result = await ExecuteAsync().ConfigureAwait(false); + +// ❌ WRONG: NEVER block on async code +var result = ExecuteAsync().Result; // DEADLOCK RISK +var result = ExecuteAsync().GetAwaiter().GetResult(); // DEADLOCK RISK +``` -## Common Gotchas and Pitfalls +### Nullable Reference Types -1. **Execution Mode Inconsistency**: Always verify behavior matches between modes -2. **Performance Regressions**: Profile code changes in test discovery and execution -3. **AOT/Trimming Issues**: Be careful with reflection usage and dynamic code -4. **Thread Safety**: Ensure thread-safe patterns in concurrent test execution -5. **Memory Leaks**: Properly dispose of resources and avoid circular references +```csharp +// ✅ CORRECT: Explicit nullability annotations +public string? TryGetTestName(TestContext context) +{ + return context.Metadata?.Name; +} -## Dependencies and Third-Party Libraries +// ✅ CORRECT: Null-forgiving operator when you know it's safe +var testName = context.Metadata!.Name; -- Minimize external dependencies for core functionality -- Use Microsoft.Extensions.* packages for common functionality -- Prefer .NET BCL types over third-party alternatives -- Keep analyzer dependencies minimal to avoid version conflicts +// ✅ CORRECT: Null-coalescing +var name = context.Metadata?.Name ?? "UnknownTest"; -## Documentation Standards +// ✅ CORRECT: Required non-nullable properties +public required string TestName { get; init; } +``` -- Use triple-slash comments for public APIs -- Include code examples in documentation -- Document performance characteristics for critical APIs -- Maintain README files for major components +### Performance-Critical Code + +```csharp +// ✅ CORRECT: Object pooling for frequently allocated objects +private static readonly ObjectPool StringBuilderPool = + ObjectPool.Create(); + +public string BuildMessage() +{ + var builder = StringBuilderPool.Get(); + try + { + builder.Append("Test: "); + builder.Append(TestName); + return builder.ToString(); + } + finally + { + builder.Clear(); + StringBuilderPool.Return(builder); + } +} + +// ✅ CORRECT: Span for stack-allocated buffers +Span buffer = stackalloc char[256]; + +// ✅ CORRECT: Avoid allocations in hot paths +// Cache reflection results +private static readonly MethodInfo ExecuteMethod = + typeof(TestRunner).GetMethod(nameof(Execute))!; + +// ✅ CORRECT: Use static readonly for constant data +private static readonly string[] ReservedNames = ["Test", "Setup", "Cleanup"]; +``` -## Questions to Ask When Making Changes +### Anti-Patterns to Avoid + +```csharp +// ❌ WRONG: Catching generic exceptions without re-throwing +try { } +catch (Exception) { } // Swallows all errors + +// ✅ CORRECT: Catch specific exceptions or re-throw +try { } +catch (InvalidOperationException ex) +{ + Log(ex); + throw; +} + +// ❌ WRONG: Using Task.Run in library code (pushes threading choice to consumers) +public Task DoWorkAsync() => Task.Run(() => DoWork()); + +// ✅ CORRECT: Properly async all the way +public async Task DoWorkAsync() => await ActualAsyncWork(); + +// ❌ WRONG: Unnecessary LINQ in hot paths +var count = tests.Where(t => t.IsPassed).Count(); + +// ✅ CORRECT: Direct iteration +int count = 0; +foreach (var test in tests) +{ + if (test.IsPassed) count++; +} + +// ❌ WRONG: String concatenation in loops +string result = ""; +foreach (var item in items) +{ + result += item; +} + +// ✅ CORRECT: StringBuilder or collection expressions +var builder = new StringBuilder(); +foreach (var item in items) +{ + builder.Append(item); +} +``` -1. Does this change affect both execution modes? -2. Is this the most performant approach? -3. Does this follow established patterns in the codebase? -4. Are there any breaking changes or compatibility concerns? -5. How will this behave under high load or with many tests? -6. Does this require new analyzer rules or diagnostics? +--- -## IDE and Tooling +## Testing Guidelines -- Use EditorConfig settings for consistent formatting -- Leverage Roslyn analyzers for code quality -- Run performance benchmarks for critical changes -- Use the project's specific MSBuild properties and targets +### Test Categories -## Critical Reminders for Every Change +1. **Unit Tests** (`TUnit.Core.Tests`, `TUnit.UnitTests`) + - Test individual components in isolation + - Fast execution, no external dependencies + - Mock dependencies + +2. **Integration Tests** (`TUnit.TestProject`, `TUnit.Engine.Tests`) + - Test interactions between components + - Use TUnit to test itself (dogfooding) + - Verify dual-mode parity + +3. **Snapshot Tests** (`TUnit.Core.SourceGenerator.Tests`, `TUnit.PublicAPI`) + - Verify source generator output + - Track public API surface + - Prevent unintended breaking changes + +4. **Performance Tests** (`TUnit.Performance.Tests`) + - Benchmark critical paths + - Compare against other frameworks + - Track performance regressions + +### Writing Tests + +```csharp +// ✅ CORRECT: Descriptive test names +[Test] +public async Task ExecuteTest_WhenTestPasses_ReturnsPassedStatus() +{ + // Arrange + var test = CreatePassingTest(); + + // Act + var result = await test.ExecuteAsync(); + + // Assert + await Assert.That(result.Status).IsEqualTo(TestStatus.Passed); +} + +// ✅ CORRECT: Test both execution modes explicitly +[Test] +[Arguments(ExecutionMode.SourceGenerated)] +[Arguments(ExecutionMode.Reflection)] +public async Task MyFeature_WorksInBothModes(ExecutionMode mode) +{ + // Test implementation +} + +// ✅ CORRECT: Use Categories for grouping +[Test] +[Category("Performance")] +public void MyPerformanceTest() { } + +// Run without performance tests: +// dotnet test -- --treenode-filter "/*/*/*/*[Category!=Performance]" +``` -### Before Submitting Any Code: -1. **Test Both Modes**: Verify your changes work identically in both source-generated and reflection modes -2. **Check Source Generator**: If changing source generator output, run `dotnet test TUnit.Core.SourceGenerator.Tests` and accept snapshots -3. **Check Public API**: If modifying TUnit.Core, TUnit.Engine, or TUnit.Playwright public APIs, run `dotnet test TUnit.PublicAPI` and accept snapshots -4. **Performance Impact**: Consider if your change affects test discovery or execution performance -5. **Breaking Changes**: Ensure no unintentional breaking changes to the public API -6. **Documentation**: Update relevant documentation for any public API changes +### Snapshot Testing + +```csharp +// In TUnit.Core.SourceGenerator.Tests + +[Test] +public Task GeneratesCorrectCode_ForSimpleTest() +{ + string source = """ + using TUnit.Core; + + public class MyTests + { + [Test] + public void SimpleTest() { } + } + """; + + return VerifySourceGenerator(source); +} + +// This will: +// 1. Run the source generator +// 2. Capture the generated code +// 3. Compare to MyTestName.verified.txt +// 4. Create MyTestName.received.txt if different +// 5. Fail test if difference found +``` -### Quick Commands Reference: +**Accepting Snapshots:** ```bash -# Run all tests -dotnet test +# After verifying .received.txt files are correct: +cd TUnit.Core.SourceGenerator.Tests +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done -# Run source generator tests -dotnet test TUnit.Core.SourceGenerator.Tests +# Commit the .verified.txt files +git add *.verified.txt +git commit -m "Update source generator snapshots" +``` -# Run public API tests -dotnet test TUnit.PublicAPI +--- -# Convert received to verified files (Windows) -for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" +## Performance Requirements -# Convert received to verified files (Linux/macOS) -for file in *.received.txt; do mv "$file" "${file%.received.txt}.verified.txt"; done +### Performance Budget -# Run specific test -dotnet test -- --treenode-filter "/Assembly/Namespace/ClassName/TestName" +| Operation | Target | Critical | +|-----------|--------|----------| +| Test discovery | < 100ms per 1000 tests | Hot path | +| Test execution overhead | < 1ms per test | Hot path | +| Source generation | < 1s per 1000 tests | Compile-time | +| Memory per test | < 1KB average | At scale | + +### Hot Paths (Optimize Aggressively) + +1. **Test Discovery** + - Source generator: Generating test registration code + - Reflection engine: Scanning assemblies for test attributes + +2. **Test Execution** + - Test invocation + - Assertion evaluation + - Result collection + +3. **Data Generation** + - Argument expansion + - Data source evaluation + +### Performance Checklist + +``` +┌─────────────────────────────────────────────────────────┐ +│ Before committing changes to hot paths: │ +│ □ Profiled with BenchmarkDotNet │ +│ □ No new allocations in tight loops │ +│ □ Reflection results cached │ +│ □ String operations minimized │ +│ □ LINQ avoided in hot paths (use loops) │ +│ □ ValueTask used for potentially sync operations │ +│ □ Compared before/after performance │ +└─────────────────────────────────────────────────────────┘ +``` + +### Performance Patterns + +```csharp +// ✅ CORRECT: Cache reflection results +private static readonly Dictionary TestMethodCache = new(); + +public MethodInfo[] GetTestMethods(Type type) +{ + if (!TestMethodCache.TryGetValue(type, out var methods)) + { + methods = type.GetMethods() + .Where(m => m.GetCustomAttribute() != null) + .ToArray(); + TestMethodCache[type] = methods; + } + return methods; +} + +// ✅ CORRECT: Use spans to avoid allocations +public void ProcessTestName(ReadOnlySpan name) +{ + // Work with span, no string allocation +} + +// ✅ CORRECT: ArrayPool for temporary buffers +var buffer = ArrayPool.Shared.Rent(size); +try +{ + // Use buffer +} +finally +{ + ArrayPool.Shared.Return(buffer); +} +``` + +--- + +## Common Patterns + +### Implementing Dual-Mode Features + +#### Pattern: New Test Lifecycle Hook + +```csharp +// 1. Define in TUnit.Core (abstraction) +namespace TUnit.Core; + +[AttributeUsage(AttributeTargets.Method)] +public class BeforeAllTestsAttribute : Attribute +{ +} + +// 2. Implement in TUnit.Core.SourceGenerator +// Generates code like: +/* +await MyTestClass.GlobalSetup(); +*/ + +// 3. Implement in TUnit.Engine (reflection) +public class ReflectionTestDiscoverer +{ + private async Task DiscoverHooksAsync(Type testClass) + { + var hookMethods = testClass.GetMethods() + .Where(m => m.GetCustomAttribute() != null); + + foreach (var method in hookMethods) + { + RegisterHook(method); + } + } +} + +// 4. Write tests for BOTH modes +[Test] +[Arguments(ExecutionMode.SourceGenerated)] +[Arguments(ExecutionMode.Reflection)] +public async Task BeforeAllTestsHook_ExecutesOnce(ExecutionMode mode) +{ + // Test implementation +} +``` + +### Adding Analyzer Rules + +```csharp +// TUnit.Analyzers/Rules/TestMethodMustBePublic.cs + +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public class TestMethodMustBePublicAnalyzer : DiagnosticAnalyzer +{ + public const string DiagnosticId = "TUNIT0001"; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + title: "Test method must be public", + messageFormat: "Test method '{0}' must be public", + category: "Design", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + public override void Initialize(AnalysisContext context) + { + context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method); + } + + private void AnalyzeMethod(SymbolAnalysisContext context) + { + var method = (IMethodSymbol)context.Symbol; + + if (method.GetAttributes().Any(a => a.AttributeClass?.Name == "TestAttribute")) + { + if (method.DeclaredAccessibility != Accessibility.Public) + { + context.ReportDiagnostic(Diagnostic.Create( + Rule, + method.Locations[0], + method.Name)); + } + } + } +} +``` + +### Adding Assertions + +```csharp +// TUnit.Assertions/Extensions/NumericAssertions.cs + +public static class NumericAssertions +{ + public static InvokableValueAssertionBuilder IsPositive( + this IValueSource valueSource) + where TActual : IComparable + { + return valueSource.RegisterAssertion( + new DelegateAssertion( + (value, _, _) => + { + if (value.CompareTo(default!) <= 0) + { + return AssertionResult.Failed($"Expected positive value but was {value}"); + } + return AssertionResult.Passed; + }, + (actual, expected) => $"{actual} is positive")); + } +} + +// Usage: +await Assert.That(value).IsPositive(); +``` + +--- + +## Troubleshooting + +### Snapshot Tests Failing + +**Problem**: `TUnit.Core.SourceGenerator.Tests` or `TUnit.PublicAPI` failing with "Snapshots don't match" + +**Solution**: +```bash +# 1. Review the .received.txt files to see what changed +cd TUnit.Core.SourceGenerator.Tests # or TUnit.PublicAPI +ls *.received.txt + +# 2. If changes are intentional (you modified the generator or public API): +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done + +# 3. Commit the updated .verified.txt files +git add *.verified.txt +git commit -m "Update snapshots after [your change]" + +# 4. NEVER commit .received.txt files +git status # Ensure no .received.txt files are staged +``` + +### Tests Pass Locally But Fail in CI + +**Common Causes**: +1. **Snapshot mismatch**: Forgot to commit `.verified.txt` files +2. **Platform differences**: Line ending issues (CRLF vs LF) +3. **Timing issues**: Race conditions in parallel tests +4. **Environment differences**: Missing dependencies + +**Solution**: +```bash +# Check for uncommitted snapshots +git status | grep verified.txt + +# Check line endings +git config core.autocrlf # Should be consistent + +# Run tests with same parallelization as CI +dotnet test --parallel ``` -Remember: TUnit aims to be a fast, modern, and reliable testing framework. Every change should contribute to these goals while maintaining the simplicity and developer experience that makes testing enjoyable. +### Dual-Mode Behavior Differs + +**Problem**: Test passes in source-generated mode but fails in reflection mode (or vice versa) + +**Diagnostic Process**: +```bash +# 1. Run test in specific mode +dotnet test -- --treenode-filter "/*/*/*/YourTest*" + +# 2. Check generated code +# Look in obj/Debug/net9.0/generated/TUnit.Core.SourceGenerator/ + +# 3. Debug reflection path +# Set breakpoint in TUnit.Engine code + +# 4. Common issues: +# - Attribute not checked in reflection path +# - Different data expansion logic +# - Missing hook invocation +# - Incorrect test metadata +``` + +**Solution**: Implement missing logic in the other execution mode + +### AOT Compilation Fails + +**Problem**: `dotnet publish -p:PublishAot=true` fails + +**Common Causes**: +1. Dynamic code generation (not supported in AOT) +2. Reflection without proper annotations +3. Missing `[DynamicallyAccessedMembers]` attributes + +**Solution**: +```csharp +// ✅ CORRECT: Annotate methods that use reflection +public void DiscoverTests( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type testClass) +{ + var methods = testClass.GetMethods(); // Safe - annotated +} + +// ✅ CORRECT: Suppress warnings when you know it's safe +[UnconditionalSuppressMessage("Trimming", "IL2070", + Justification = "Test methods are preserved by source generator")] +public void InvokeTestMethod(MethodInfo method) { } +``` + +### Performance Regression + +**Problem**: Tests run slower after changes + +**Diagnostic**: +```bash +# Run performance benchmarks +cd TUnit.Performance.Tests +dotnet run -c Release --framework net9.0 + +# Profile with dotnet-trace +dotnet trace collect -- dotnet test + +# Analyze with PerfView or similar +``` + +**Common Causes**: +- Added LINQ in hot path (use loops instead) +- Missing caching of reflection results +- Unnecessary allocations (use object pooling) +- Synchronous blocking on async code + +--- + +## Pre-Commit Checklist + +Before committing ANY code, verify: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ □ All tests pass: dotnet test │ +│ □ If source generator changed: │ +│ • Ran TUnit.Core.SourceGenerator.Tests │ +│ • Reviewed and accepted snapshots (.verified.txt) │ +│ • Committed .verified.txt files │ +│ □ If public API changed: │ +│ • Ran TUnit.PublicAPI tests │ +│ • Reviewed and accepted snapshots │ +│ • Committed .verified.txt files │ +│ □ If dual-mode feature: │ +│ • Implemented in BOTH source-gen and reflection │ +│ • Tested both modes explicitly │ +│ • Verified identical behavior │ +│ □ If performance-critical: │ +│ • Profiled before and after │ +│ • No performance regression │ +│ • Minimized allocations │ +│ □ If touching reflection: │ +│ • Tested with AOT: dotnet publish -p:PublishAot=true │ +│ • Added proper DynamicallyAccessedMembers annotations │ +│ □ Code follows style guide │ +│ □ No breaking changes (or documented if unavoidable) │ +└─────────────────────────────────────────────────────────────┘ +``` + +--- + +## Additional Resources + +- **Documentation**: https://tunit.dev +- **Contributing Guide**: `.github/CONTRIBUTING.md` +- **Issues**: https://github.com/thomhurst/TUnit/issues +- **Discussions**: https://github.com/thomhurst/TUnit/discussions + +--- + +## Philosophy + +TUnit aims to be: **fast, modern, reliable, and enjoyable to use**. + +Every change should advance these goals: +- **Fast**: Optimize for performance. Millions of tests depend on it. +- **Modern**: Leverage latest .NET features. Support AOT, trimming, latest C#. +- **Reliable**: Dual-mode parity. Comprehensive tests. No breaking changes without major version bump. +- **Enjoyable**: Great error messages. Intuitive API. Minimal boilerplate. + +When in doubt, ask: "Does this make TUnit faster, more modern, more reliable, or more enjoyable to use?" + +If the answer is no, reconsider the change. diff --git a/.github/workflows/deploy-pages-test.yml b/.github/workflows/deploy-pages-test.yml index 4ae2a0a1f9..261a136ea7 100644 --- a/.github/workflows/deploy-pages-test.yml +++ b/.github/workflows/deploy-pages-test.yml @@ -18,7 +18,7 @@ jobs: fetch-depth: 0 - uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: yarn cache-dependency-path: 'docs/yarn.lock' diff --git a/.github/workflows/deploy-pages.yml b/.github/workflows/deploy-pages.yml index f3b44cd88a..e41288cdef 100644 --- a/.github/workflows/deploy-pages.yml +++ b/.github/workflows/deploy-pages.yml @@ -21,7 +21,7 @@ jobs: fetch-depth: 0 - uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: yarn cache-dependency-path: 'docs/yarn.lock' diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index cccd3c3dac..5f97b49f56 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -53,15 +53,40 @@ jobs: with: dotnet-version: 10.0.x + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: | + ~/.nuget/packages + ~/.local/share/NuGet + %LocalAppData%\NuGet\v3-cache + key: nuget-${{ runner.os }}-${{ hashFiles('**/Directory.Packages.props', '**/*.csproj') }} + restore-keys: | + nuget-${{ runner.os }}- + - name: Docker Setup Docker if: matrix.os == 'ubuntu-latest' uses: docker/setup-docker-action@v4.4.0 - - name: Install Playwright Dependencies - run: npx playwright install-deps - - - name: Install Playwright Browsers + - name: Cache Playwright Browsers + uses: actions/cache@v4 + id: playwright-cache + with: + path: | + ~/.cache/ms-playwright + ~/Library/Caches/ms-playwright + ~/AppData/Local/ms-playwright + key: playwright-${{ runner.os }}-${{ hashFiles('**/package-lock.json', '**/package.json', '**/Directory.Packages.props') }} + restore-keys: | + playwright-${{ runner.os }}- + + - name: Install Playwright + run: npx playwright install --with-deps + if: steps.playwright-cache.outputs.cache-hit != 'true' + + - name: Install Playwright (browsers only) run: npx playwright install + if: steps.playwright-cache.outputs.cache-hit == 'true' - name: Build run: dotnet build -c Release diff --git a/.github/workflows/generate-readme.yml b/.github/workflows/generate-readme.yml index 08bd9e860d..9b06bcf623 100644 --- a/.github/workflows/generate-readme.yml +++ b/.github/workflows/generate-readme.yml @@ -17,11 +17,11 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v5 with: - dotnet-version: 9.0.x + dotnet-version: 10.0.x - name: Generate ReadMe uses: ./.github/actions/execute-pipeline with: categories: ReadMe admin-token: ${{ secrets.ADMIN_TOKEN }} - environment: Development \ No newline at end of file + environment: Development diff --git a/.github/workflows/speed-comparison.yml b/.github/workflows/speed-comparison.yml index 96ae2d33e2..d2adcb9346 100644 --- a/.github/workflows/speed-comparison.yml +++ b/.github/workflows/speed-comparison.yml @@ -8,11 +8,7 @@ on: jobs: build-test-artifacts: environment: ${{ github.ref == 'refs/heads/main' && 'Production' || 'Pull Requests' }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - fail-fast: false - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 @@ -34,13 +30,13 @@ jobs: - name: Publish TUnit AOT run: | - dotnet publish -c Release -p:TestFramework=TUNIT -p:Aot=true --runtime ${{ matrix.os == 'windows-latest' && 'win-x64' || matrix.os == 'ubuntu-latest' && 'linux-x64' || 'osx-arm64' }} --output bin/Release-TUNIT-AOT/net10.0 + dotnet publish -c Release -p:TestFramework=TUNIT -p:Aot=true --use-current-runtime --output bin/Release-TUNIT-AOT/net10.0 working-directory: "tools/speed-comparison/UnifiedTests" - name: Upload Build Artifacts uses: actions/upload-artifact@v5 with: - name: test-builds-${{ matrix.os }} + name: test-builds-ubuntu path: tools/speed-comparison/UnifiedTests/bin/ retention-days: 1 @@ -49,12 +45,11 @@ jobs: environment: ${{ github.ref == 'refs/heads/main' && 'Production' || 'Pull Requests' }} strategy: matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - class: [DataDrivenTests, AsyncTests, ScaleTests, MatrixTests, LifecycleTests, MassiveParallelTests] + class: [DataDrivenTests, AsyncTests, ScaleTests, MatrixTests, MassiveParallelTests] fail-fast: false - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest concurrency: - group: "speed-comparison-run-time-${{matrix.os}}-${{matrix.class}}" + group: "speed-comparison-run-time-${{matrix.class}}" cancel-in-progress: true steps: @@ -70,11 +65,10 @@ jobs: - name: Download Build Artifacts uses: actions/download-artifact@v6 with: - name: test-builds-${{ matrix.os }} + name: test-builds-ubuntu path: tools/speed-comparison/UnifiedTests/bin/ - - name: Set Execute Permissions (Linux/macOS) - if: runner.os != 'Windows' + - name: Set Execute Permissions run: | find tools/speed-comparison/UnifiedTests/bin -type f -name "UnifiedTests" -exec chmod +x {} \; 2>/dev/null || true find tools/speed-comparison/UnifiedTests/bin -type f -name "xunit.v3.runner.console" -exec chmod +x {} \; 2>/dev/null || true @@ -90,21 +84,16 @@ jobs: uses: actions/upload-artifact@v5 if: always() with: - name: ${{ matrix.os }}_markdown_run_time_${{ matrix.class }} + name: ubuntu_markdown_run_time_${{ matrix.class }} path: | **/BenchmarkDotNet.Artifacts/** build-time-benchmarks: environment: ${{ github.ref == 'refs/heads/main' && 'Production' || 'Pull Requests' }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - # framework: [net8.0, net9.0] - fail-fast: false - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest concurrency: - group: "speed-comparison-build-time-${{matrix.os}}" + group: "speed-comparison-build-time" cancel-in-progress: true steps: @@ -130,7 +119,7 @@ jobs: uses: actions/upload-artifact@v5 if: always() with: - name: ${{ matrix.os }}_markdown_build_time + name: ubuntu_markdown_build_time path: | **/BenchmarkDotNet.Artifacts/** diff --git a/CLAUDE.md b/CLAUDE.md index fa287251a1..1ed9227dd1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,115 +1,706 @@ # TUnit Development Guide for LLM Agents -## MANDATORY RULES - ALWAYS FOLLOW -1. **Dual-mode implementation required**: ALL changes must work identically in both source-generated and reflection modes -2. **Snapshot tests are critical**: After ANY change to source generator or public APIs, you MUST run and accept snapshots -3. **Never use VSTest**: This project uses Microsoft.Testing.Platform exclusively -4. **Performance first**: Optimize for speed - this framework is used by millions - -## When You Make Changes - -### If you modify source generator code: -1. Run: `dotnet test TUnit.Core.SourceGenerator.Tests` -2. If snapshots differ, rename ALL `*.received.txt` files to `*.verified.txt` -3. Commit the updated `.verified.txt` files - -### If you modify public APIs: -1. Run: `dotnet test TUnit.PublicAPI` -2. If snapshots differ, rename ALL `*.received.txt` files to `*.verified.txt` -3. Commit the updated `.verified.txt` files - -### If you add a feature: -1. Implement in BOTH `TUnit.Core.SourceGenerator` AND `TUnit.Engine` (reflection path) -2. Verify identical behavior in both modes -3. Add tests covering both execution paths -4. Consider if an analyzer rule would help prevent misuse -5. Test performance impact - -### If you fix a bug: -1. Write a failing test first -2. Fix in BOTH execution modes (source-gen and reflection) -3. Verify no performance regression - -## Project Structure -- `TUnit.Core`: Abstractions, interfaces, attributes -- `TUnit.Engine`: Test discovery and execution (reflection mode) -- `TUnit.Core.SourceGenerator`: Compile-time code generation (source-gen mode) -- `TUnit.Assertions`: Fluent assertion library -- `TUnit.Analyzers`: Roslyn analyzers for compile-time validation - -## Code Style (REQUIRED) -```csharp -// Modern C# syntax - always use -List list = []; // Collection expressions -var result = GetValue(); // var for obvious types +> **Purpose**: This file contains essential instructions for AI assistants (Claude, Copilot, etc.) working on TUnit. +> **Audience**: LLM agents, AI coding assistants +> **Optimization**: Structured for rapid parsing, clear decision trees, explicit requirements -// Always use braces -if (condition) +--- + +## 🚨 MANDATORY RULES - ALWAYS FOLLOW + +### Rule 1: Dual-Mode Implementation (CRITICAL) + +**REQUIREMENT**: ALL changes must work identically in both execution modes. + +``` +User Test Code + │ + ├─► SOURCE-GENERATED MODE (TUnit.Core.SourceGenerator) + │ └─► Compile-time code generation + │ + └─► REFLECTION MODE (TUnit.Engine) + └─► Runtime test discovery + + Both modes MUST produce identical behavior +``` + +**Implementation Checklist**: +- [ ] Feature implemented in `TUnit.Core.SourceGenerator` (source-gen path) +- [ ] Feature implemented in `TUnit.Engine` (reflection path) +- [ ] Tests written for both modes +- [ ] Verified identical behavior in both modes + +**If you implement only ONE mode, the feature is INCOMPLETE and MUST NOT be committed.** + +--- + +### Rule 2: Snapshot Testing (NON-NEGOTIABLE) + +**TRIGGER CONDITIONS**: +1. ANY change to source generator output +2. ANY change to public APIs (TUnit.Core, TUnit.Engine, TUnit.Assertions) + +**WORKFLOW**: +```bash +# Source Generator Changes: +dotnet test TUnit.Core.SourceGenerator.Tests +# Review .received.txt files +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done # Linux/macOS +for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" # Windows + +# Public API Changes: +dotnet test TUnit.PublicAPI +# Review .received.txt files +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done # Linux/macOS +for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" # Windows + +# Commit .verified.txt files (NEVER commit .received.txt) +git add *.verified.txt +git commit -m "Update snapshots: [reason]" +``` + +**REMEMBER**: Snapshots are the source of truth. Failing to update them breaks CI. + +--- + +### Rule 3: No VSTest (ABSOLUTE) + +- ✅ **USE**: `Microsoft.Testing.Platform` +- ❌ **NEVER**: `Microsoft.VisualStudio.TestPlatform` (VSTest - legacy, incompatible) + +If you see VSTest references in new code, **STOP** and use Microsoft.Testing.Platform instead. + +--- + +### Rule 4: Performance First + +**Context**: TUnit processes millions of tests daily. Performance is not optional. + +**Requirements**: +- Minimize allocations in hot paths (test discovery, execution) +- Cache reflection results +- Use `ValueTask` for potentially-sync operations +- Profile before/after for changes in critical paths +- Use object pooling for frequent allocations + +**Hot Paths** (profile these): +1. Test discovery (source generation + reflection scanning) +2. Test execution (invocation, assertions, result collection) +3. Data generation (argument expansion, data sources) + +--- + +### Rule 5: AOT/Trimming Compatibility + +**Requirement**: All code must work with Native AOT and IL trimming. + +**Guidelines**: +```csharp +// ✅ CORRECT: Annotate reflection usage +public void DiscoverTests( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] + Type testClass) { - DoSomething(); + var methods = testClass.GetMethods(); } -// Naming -public string PublicField; // PascalCase -private string _privateField; // _camelCase +// ✅ CORRECT: Suppress warnings when safe +[UnconditionalSuppressMessage("Trimming", "IL2070", + Justification = "Test methods preserved by source generator")] +public void InvokeTest(MethodInfo method) { } +``` -// Async -async ValueTask DoWorkAsync(CancellationToken cancellationToken) // ValueTask when possibly sync +**Verification**: +```bash +cd TUnit.TestProject +dotnet publish -c Release -p:PublishAot=true --use-current-runtime ``` -## Performance Guidelines -- Minimize allocations in hot paths (discovery/execution) -- Use object pooling for frequent allocations -- Cache reflection results -- Benchmark critical paths before/after changes +--- + +## 📋 Quick Reference Card + +### ⚠️ CRITICAL: TUnit.TestProject Testing Rules + +**DO NOT run `TUnit.TestProject` without filters!** Many tests are intentionally designed to fail to verify error handling. + +```bash +# ❌ WRONG - Will show many "failures" (expected behavior) +cd TUnit.TestProject && dotnet run +cd TUnit.TestProject && dotnet test + +# ✅ CORRECT - Always use targeted filters +cd TUnit.TestProject && dotnet run -- --treenode-filter "/*/*/SpecificClass/*" +cd TUnit.TestProject && dotnet run -- --treenode-filter "/*/*/*/*[Category!=Performance]" + +# ✅ CORRECT - Test other projects normally +dotnet test TUnit.Engine.Tests +dotnet test TUnit.Assertions.Tests +dotnet test TUnit.Core.SourceGenerator.Tests +``` + +**Why?** TUnit.TestProject contains: +- Tests that verify failure scenarios (expected to fail) +- Tests for error messages and diagnostics +- Performance tests that should be excluded by default +- Integration tests covering edge cases + +**Rule**: Only run TUnit.TestProject with explicit `--treenode-filter` to target specific tests or classes. + +--- + +### Most Common Commands -## Common Commands ```bash -# Test everything +# Run all tests (excludes TUnit.TestProject integration tests) dotnet test -# Test source generator specifically +# Test source generator + accept snapshots dotnet test TUnit.Core.SourceGenerator.Tests +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done -# Test public API surface +# Test public API + accept snapshots dotnet test TUnit.PublicAPI +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done -# Accept snapshots (Windows - use this after verifying diffs are correct) -for %f in (*.received.txt) do move /Y "%f" "%~nf.verified.txt" - -# Run specific test by filter +# Run specific test dotnet test -- --treenode-filter "/Assembly/Namespace/ClassName/TestName" + +# Exclude performance tests +dotnet test -- --treenode-filter "/*/*/*/*[Category!=Performance]" + +# Build release +dotnet build -c Release + +# Test AOT +dotnet publish -c Release -p:PublishAot=true ``` -## AOT/Trimming Compatibility -- Use `[UnconditionalSuppressMessage]` for known-safe reflection -- Test with trimming/AOT enabled projects -- Avoid dynamic code generation at runtime (use source generators instead) - -## Threading and Safety -- All test execution must be thread-safe -- Use proper synchronization for shared state -- Dispose resources correctly (implement IDisposable/IAsyncDisposable) - -## Critical Mistakes to Avoid -1. ❌ Implementing a feature only in source-gen mode (must do BOTH) -2. ❌ Breaking change to public API without major version bump -3. ❌ Forgetting to accept snapshots after intentional generator changes -4. ❌ Performance regression in discovery or execution -5. ❌ Using reflection in ways incompatible with AOT/trimming - -## Verification Checklist -Before completing any task, verify: -- [ ] Works in both source-generated and reflection modes -- [ ] Snapshots accepted if generator/API changed -- [ ] Tests added and passing -- [ ] No performance regression -- [ ] AOT/trimming compatible -- [ ] Thread-safe if touching concurrent code - -## Target Frameworks -- .NET Standard 2.0 (library compatibility) -- .NET 6, 8, 9+ (current support) - -## Philosophy -TUnit aims to be: **fast, modern, reliable, and enjoyable to use**. Every change should advance these goals. \ No newline at end of file +### Test Filter Syntax + +```bash +# Single test +--treenode-filter "/TUnit.TestProject/Namespace/ClassName/TestMethodName" + +# All tests in a class +--treenode-filter "/*/*/ClassName/*" + +# Multiple patterns (OR) +--treenode-filter "Pattern1|Pattern2" + +# Exclude by category +--treenode-filter "/*/*/*/*[Category!=Performance]" +``` + +--- + +## 🏗️ Project Structure + +### Core Projects + +| Project | Purpose | Key Responsibility | +|---------|---------|-------------------| +| `TUnit.Core` | Abstractions, attributes, interfaces | Public API surface | +| `TUnit.Engine` | Test discovery & execution | **Reflection mode** | +| `TUnit.Core.SourceGenerator` | Compile-time test generation | **Source-gen mode** | +| `TUnit.Assertions` | Fluent assertion library | Separate from core | +| `TUnit.Assertions.SourceGenerator` | Custom assertion generation | Extensibility | +| `TUnit.Analyzers` | Roslyn analyzers & code fixes | Compile-time safety | +| `TUnit.PropertyTesting` | Property-based testing | New feature | +| `TUnit.Playwright` | Browser testing integration | Playwright wrapper | + +### Test Projects + +| Project | Purpose | +|---------|---------| +| `TUnit.TestProject` | Integration tests (dogfooding) | +| `TUnit.Engine.Tests` | Engine-specific tests | +| `TUnit.Assertions.Tests` | Assertion library tests | +| `TUnit.Core.SourceGenerator.Tests` | **Snapshot tests for source generator** | +| `TUnit.PublicAPI` | **Snapshot tests for public API** | + +### Roslyn Version Projects + +- `*.Roslyn414`, `*.Roslyn44`, `*.Roslyn47`: Multi-targeting for Roslyn API versions +- Ensures compatibility across Visual Studio and .NET SDK versions + +--- + +## 💻 Code Style (REQUIRED) + +### Modern C# Syntax (Mandatory) + +```csharp +// ✅ Collection expressions (C# 12+) +List items = []; +string[] array = ["a", "b", "c"]; + +// ❌ WRONG: Old syntax +List items = new List(); + +// ✅ var for obvious types +var testName = GetTestName(); + +// ✅ Always use braces +if (condition) +{ + DoSomething(); +} + +// ❌ WRONG: No braces +if (condition) + DoSomething(); + +// ✅ File-scoped namespaces +namespace TUnit.Core.Features; + +public class MyClass { } + +// ✅ Pattern matching +if (obj is TestContext context) +{ + ProcessContext(context); +} + +// ✅ Switch expressions +var result = status switch +{ + TestStatus.Passed => "✓", + TestStatus.Failed => "✗", + _ => "?" +}; + +// ✅ Raw string literals +string code = """ + public void Test() { } + """; +``` + +### Naming Conventions + +```csharp +// Public: PascalCase +public string TestName { get; } + +// Private fields: _camelCase +private readonly IExecutor _executor; + +// Local: camelCase +var testContext = new TestContext(); + +// Async: Async suffix +public async Task ExecuteTestAsync(CancellationToken ct) { } +``` + +### Async Patterns + +```csharp +// ✅ ValueTask for potentially-sync operations +public ValueTask ExecuteAsync(CancellationToken ct) +{ + if (IsCached) + return new ValueTask(cachedResult); + + return ExecuteAsyncCore(ct); +} + +// ✅ Always accept CancellationToken +public async Task RunAsync(CancellationToken cancellationToken) { } + +// ❌ NEVER block on async +var result = ExecuteAsync().Result; // DEADLOCK RISK +var result = ExecuteAsync().GetAwaiter().GetResult(); // DEADLOCK RISK +``` + +### Performance Patterns + +```csharp +// ✅ Cache reflection results +private static readonly Dictionary TestMethodCache = new(); + +// ✅ Object pooling +private static readonly ObjectPool StringBuilderPool = + ObjectPool.Create(); + +// ✅ Span to avoid allocations +public void ProcessTestName(ReadOnlySpan name) { } + +// ✅ ArrayPool for temporary buffers +var buffer = ArrayPool.Shared.Rent(size); +try { /* use buffer */ } +finally { ArrayPool.Shared.Return(buffer); } +``` + +### Anti-Patterns (NEVER DO THIS) + +```csharp +// ❌ Catching all exceptions without re-throw +try { } catch (Exception) { } // Swallows errors + +// ❌ LINQ in hot paths +var count = tests.Where(t => t.IsPassed).Count(); + +// ✅ Use loops instead +int count = 0; +foreach (var test in tests) + if (test.IsPassed) count++; + +// ❌ String concatenation in loops +string result = ""; +foreach (var item in items) result += item; + +// ✅ StringBuilder +var builder = new StringBuilder(); +foreach (var item in items) builder.Append(item); +``` + +--- + +## 🔄 Development Workflows + +### Adding a New Feature + +**Decision Tree**: +``` +Is this a new feature? + ├─► YES + │ ├─► Does it require dual-mode implementation? + │ │ ├─► YES: Implement in BOTH source-gen AND reflection + │ │ └─► NO: Still verify both modes aren't affected + │ │ + │ ├─► Does it change public API? + │ │ └─► YES: Run TUnit.PublicAPI tests + accept snapshots + │ │ + │ ├─► Does it change source generator output? + │ │ └─► YES: Run TUnit.Core.SourceGenerator.Tests + accept snapshots + │ │ + │ ├─► Does it touch hot paths? + │ │ └─► YES: Profile before/after, benchmark + │ │ + │ └─► Does it use reflection? + │ └─► YES: Test with AOT (dotnet publish -p:PublishAot=true) + │ + └─► NO: (Continue to bug fix workflow) +``` + +**Step-by-Step**: +1. **Write tests FIRST** (TDD) +2. Implement in `TUnit.Core` (if new abstractions needed) +3. Implement in `TUnit.Core.SourceGenerator` (source-gen path) +4. Implement in `TUnit.Engine` (reflection path) +5. Add analyzer rule (if misuse is possible) +6. Run all tests: `dotnet test` +7. Accept snapshots if needed (see Rule 2) +8. Benchmark if touching hot paths +9. Test AOT if using reflection + +### Fixing a Bug + +**Step-by-Step**: +1. **Write failing test** that reproduces the bug +2. Identify affected execution mode(s) +3. Fix in source generator (if affected) +4. Fix in reflection engine (if affected) +5. Verify both modes pass the test +6. Run full test suite: `dotnet test` +7. Accept snapshots if applicable +8. Check for performance regression (if in hot path) + +--- + +## 🎯 Common Patterns + +### Implementing Dual-Mode Feature + +```csharp +// 1. Define abstraction in TUnit.Core +[AttributeUsage(AttributeTargets.Method)] +public class BeforeAllTestsAttribute : Attribute { } + +// 2. Implement in TUnit.Core.SourceGenerator +// Generated code: +// await MyTestClass.GlobalSetup(); + +// 3. Implement in TUnit.Engine (reflection) +public class ReflectionTestDiscoverer +{ + private async Task DiscoverHooksAsync(Type testClass) + { + var hookMethods = testClass.GetMethods() + .Where(m => m.GetCustomAttribute() != null); + + foreach (var method in hookMethods) + RegisterHook(method); + } +} + +// 4. Test BOTH modes +[Test] +[Arguments(ExecutionMode.SourceGenerated)] +[Arguments(ExecutionMode.Reflection)] +public async Task BeforeAllTestsHook_ExecutesOnce(ExecutionMode mode) { } +``` + +### Adding Analyzer Rule + +```csharp +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public class TestMethodMustBePublicAnalyzer : DiagnosticAnalyzer +{ + public const string DiagnosticId = "TUNIT0001"; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + title: "Test method must be public", + messageFormat: "Test method '{0}' must be public", + category: "Design", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + public override void Initialize(AnalysisContext context) + { + context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method); + } + + private void AnalyzeMethod(SymbolAnalysisContext context) + { + var method = (IMethodSymbol)context.Symbol; + + if (method.GetAttributes().Any(a => a.AttributeClass?.Name == "TestAttribute")) + { + if (method.DeclaredAccessibility != Accessibility.Public) + { + context.ReportDiagnostic(Diagnostic.Create( + Rule, method.Locations[0], method.Name)); + } + } + } +} +``` + +### Adding Assertion + +```csharp +public static class NumericAssertions +{ + public static InvokableValueAssertionBuilder IsPositive( + this IValueSource valueSource) + where TActual : IComparable + { + return valueSource.RegisterAssertion( + new DelegateAssertion( + (value, _, _) => + { + if (value.CompareTo(default!) <= 0) + return AssertionResult.Failed($"Expected positive value but was {value}"); + return AssertionResult.Passed; + }, + (actual, expected) => $"{actual} is positive")); + } +} + +// Usage: +await Assert.That(value).IsPositive(); +``` + +--- + +## 🐛 Troubleshooting + +### Snapshot Tests Failing + +**Symptom**: `TUnit.Core.SourceGenerator.Tests` or `TUnit.PublicAPI` failing + +**Solution**: +```bash +# 1. Review .received.txt files +cd TUnit.Core.SourceGenerator.Tests # or TUnit.PublicAPI +ls *.received.txt + +# 2. If changes are intentional: +for f in *.received.txt; do mv "$f" "${f%.received.txt}.verified.txt"; done + +# 3. Commit .verified.txt files +git add *.verified.txt +git commit -m "Update snapshots: [reason]" + +# 4. NEVER commit .received.txt +git status # Verify no .received.txt staged +``` + +### Tests Pass Locally, Fail in CI + +**Common Causes**: +1. Forgot to commit `.verified.txt` files +2. Line ending differences (CRLF vs LF) +3. Race conditions in parallel tests +4. Missing dependencies + +**Solution**: +```bash +# Check for uncommitted snapshots +git status | grep verified.txt + +# Check line endings +git config core.autocrlf + +# Run with same parallelization as CI +dotnet test --parallel +``` + +### Dual-Mode Behavior Differs + +**Diagnostic**: +```bash +# Check generated code +# obj/Debug/net9.0/generated/TUnit.Core.SourceGenerator/ + +# Set breakpoint in TUnit.Engine for reflection path + +# Common issues: +# - Attribute not checked in reflection +# - Different data expansion logic +# - Missing hook invocation +``` + +**Solution**: Implement missing logic in other execution mode + +### AOT Compilation Fails + +**Common Causes**: +1. Dynamic code generation (not AOT-compatible) +2. Reflection without proper annotations +3. Missing `[DynamicallyAccessedMembers]` + +**Solution**: Add proper annotations (see Rule 5 above) + +### Performance Regression + +**Diagnostic**: +```bash +# Benchmark +cd TUnit.Performance.Tests +dotnet run -c Release --framework net9.0 + +# Profile +dotnet trace collect -- dotnet test +``` + +**Common Causes**: +- LINQ in hot path → use loops +- Missing reflection cache +- Unnecessary allocations → use object pooling +- Blocking on async + +--- + +## ✅ Pre-Commit Checklist + +**Before committing, verify ALL items**: + +``` +┌─────────────────────────────────────────────────────────┐ +│ □ All tests pass: dotnet test │ +│ │ +│ □ If source generator changed: │ +│ • Ran TUnit.Core.SourceGenerator.Tests │ +│ • Reviewed .received.txt files │ +│ • Accepted snapshots (.verified.txt) │ +│ • Committed .verified.txt files │ +│ │ +│ □ If public API changed: │ +│ • Ran TUnit.PublicAPI tests │ +│ • Reviewed .received.txt files │ +│ • Accepted snapshots (.verified.txt) │ +│ • Committed .verified.txt files │ +│ │ +│ □ If dual-mode feature: │ +│ • Implemented in BOTH source-gen AND reflection │ +│ • Tested both modes explicitly │ +│ • Verified identical behavior │ +│ │ +│ □ If performance-critical: │ +│ • Profiled before/after │ +│ • No performance regression │ +│ • Minimized allocations │ +│ │ +│ □ If touching reflection: │ +│ • Tested AOT: dotnet publish -p:PublishAot=true │ +│ • Added DynamicallyAccessedMembers annotations │ +│ │ +│ □ Code follows style guide │ +│ □ No breaking changes (or major version bump) │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## 🎓 Philosophy + +**TUnit Core Principles**: + +1. **Fast**: Performance is not optional. Millions of tests depend on it. +2. **Modern**: Latest .NET features, AOT support, C# 12+ syntax. +3. **Reliable**: Dual-mode parity, comprehensive tests, API stability. +4. **Enjoyable**: Great error messages, intuitive API, minimal boilerplate. + +**Decision Framework**: + +When considering any change, ask: + +> "Does this make TUnit faster, more modern, more reliable, or more enjoyable to use?" + +If the answer is **NO** → reconsider the change. + +--- + +## 📚 Additional Resources + +- **Documentation**: https://tunit.dev +- **Contributing**: `.github/CONTRIBUTING.md` +- **Issues**: https://github.com/thomhurst/TUnit/issues +- **Discussions**: https://github.com/thomhurst/TUnit/discussions +- **Detailed Guide**: `.github/copilot-instructions.md` + +--- + +## 🤖 LLM-Specific Notes + +**For AI Assistants**: + +1. **Always check Rule 1-5 first** before making changes +2. **Use Quick Reference Card** for common commands +3. **Follow Decision Trees** in Development Workflows section +4. **Consult Common Patterns** for implementation templates +5. **Run Pre-Commit Checklist** before suggesting changes to commit + +**High-Level Decision Process**: +``` +User Request + │ + ├─► Identify category: feature, bug, refactor + │ + ├─► Check if dual-mode implementation needed + │ + ├─► Check if snapshots need updating + │ + ├─► Implement with required style/patterns + │ + ├─► Run tests + accept snapshots + │ + └─► Verify pre-commit checklist +``` + +**Common Mistakes to Avoid**: +1. ❌ Implementing only one execution mode +2. ❌ Forgetting to update snapshots +3. ❌ Using old C# syntax +4. ❌ Adding allocations in hot paths +5. ❌ Using VSTest APIs +6. ❌ Blocking on async code +7. ❌ Committing .received.txt files + +--- + +**Last Updated**: 2025-01-28 +**Version**: 2.0 (LLM-optimized) diff --git a/Directory.Packages.props b/Directory.Packages.props index 09b555dc41..9438b3c71c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,7 +54,7 @@ - + @@ -81,12 +81,12 @@ - - - - - - + + + + + + diff --git a/Examples/CleanArchitectureExample.cs b/Examples/CleanArchitectureExample.cs deleted file mode 100644 index a940c75322..0000000000 --- a/Examples/CleanArchitectureExample.cs +++ /dev/null @@ -1,213 +0,0 @@ -using System; -using System.Collections.Generic; -using TUnit.Core; -using TUnit.Assertions; - -namespace TUnit.Examples; - -/// -/// Example demonstrating TUnit's clean architecture where: -/// - Source generator only emits TestMetadata (data structures) -/// - TestBuilder handles all complex runtime logic -/// -public class CleanArchitectureExample -{ - /// - /// Simple test - discovered by TestMetadataGenerator at compile time - /// - [Test] - public async Task SimpleTest() - { - // The source generator found this test and created TestMetadata for it - // TestBuilder expands it into a TestDefinition at runtime - var result = 2 + 2; - await Assert.That(result).IsEqualTo(4); - } - - /// - /// Data-driven test with inline arguments - /// - [Test] - [Arguments(1, 1, 2)] - [Arguments(2, 3, 5)] - [Arguments(10, -5, 5)] - public async Task ParameterizedTest(int a, int b, int expected) - { - // Source generator creates TestMetadata with InlineDataSourceProvider - // TestBuilder enumerates the data source and creates 3 test instances - var sum = a + b; - await Assert.That(sum).IsEqualTo(expected); - } - - /// - /// Data-driven test with method data source - /// - [Test] - [MethodDataSource(nameof(GetTestCases))] - public async Task MethodDataSourceTest(string input, int expectedLength) - { - // Source generator creates TestMetadata with MethodDataSourceProvider - // TestBuilder invokes GetTestCases() at runtime and creates test instances - await Assert.That(input.Length).IsEqualTo(expectedLength); - } - - public static IEnumerable<(string, int)> GetTestCases() - { - yield return ("hello", 5); - yield return ("world", 5); - yield return ("TUnit rocks!", 12); - } - - /// - /// Test with repeat functionality - /// - [Test] - [Repeat(3)] - public async Task RepeatedTest() - { - // Source generator sets RepeatCount = 3 in TestMetadata - // TestBuilder creates 3 instances of this test - var random = new Random(); - var value = random.Next(1, 100); - await Assert.That(value).IsGreaterThan(0).And.IsLessThanOrEqualTo(100); - } -} - -/// -/// Example with class-level data source and constructor injection -/// -[ClassDataSource(typeof(UserTestData))] -public class UserServiceTests -{ - private readonly User _testUser; - private readonly UserService _service; - - public UserServiceTests(User testUser) - { - // Source generator creates TestMetadata with ClassDataSources - // TestBuilder enumerates UserTestData and injects each user - _testUser = testUser; - _service = new UserService(); - } - - [Test] - public async Task ValidateUser_ShouldPass() - { - var isValid = _service.Validate(_testUser); - await Assert.That(isValid).IsTrue(); - } - - [Test] - public async Task GetUserAge_ShouldBePositive() - { - var age = _service.CalculateAge(_testUser); - await Assert.That(age).IsGreaterThanOrEqualTo(0); - } -} - -/// -/// Example with property injection -/// -public class PropertyInjectionExample -{ - [Arguments("Development")] - [Arguments("Staging")] - [Arguments("Production")] - public string Environment { get; set; } = ""; - - [Test] - public async Task EnvironmentSpecificTest() - { - // Source generator creates TestMetadata with PropertyDataSources - // TestBuilder injects the property value before test execution - await Assert.That(Environment).IsNotNullOrEmpty(); - - var config = new ConfigService(Environment); - var connectionString = config.GetConnectionString(); - - await Assert.That(connectionString).Contains(Environment); - } -} - -/// -/// Complex example showing how TestBuilder handles tuple unwrapping -/// -public class TupleUnwrappingExample -{ - [Test] - [MethodDataSource(nameof(GetComplexTestData))] - public async Task ComplexDataTest(int id, string name, DateTime birthDate, bool isActive) - { - // Source generator sees the method returns tuples - // TestBuilder unwraps the tuple into individual parameters at runtime - await Assert.That(id).IsGreaterThan(0); - await Assert.That(name).IsNotNullOrEmpty(); - await Assert.That(birthDate).IsLessThan(DateTime.Now); - await Assert.That(isActive).IsNotNull(); - } - - public static IEnumerable<(int, string, DateTime, bool)> GetComplexTestData() - { - yield return (1, "Alice", new DateTime(1990, 1, 1), true); - yield return (2, "Bob", new DateTime(1985, 6, 15), false); - yield return (3, "Charlie", new DateTime(2000, 12, 31), true); - } -} - -// Supporting classes for examples -public class User -{ - public string Name { get; set; } = ""; - public DateTime BirthDate { get; set; } -} - -public class UserService -{ - public bool Validate(User user) => !string.IsNullOrEmpty(user.Name); - public int CalculateAge(User user) => DateTime.Now.Year - user.BirthDate.Year; -} - -public class UserTestData : IEnumerable -{ - public IEnumerator GetEnumerator() - { - yield return new User { Name = "Test User 1", BirthDate = new DateTime(1990, 1, 1) }; - yield return new User { Name = "Test User 2", BirthDate = new DateTime(2000, 6, 15) }; - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); -} - -public class ConfigService -{ - private readonly string _environment; - - public ConfigService(string environment) => _environment = environment; - - public string GetConnectionString() => $"Server=db.{_environment.ToLower()}.example.com;Database=MyApp"; -} - -/// -/// Summary of the clean architecture: -/// -/// 1. Source Generation Phase (Compile Time): -/// - TestMetadataGenerator scans for [Test] attributes -/// - Emits only TestMetadata data structures -/// - No complex logic or execution code generated -/// -/// 2. Runtime Phase: -/// - TestSourceRegistrar registers TestMetadata -/// - TestBuilder expands metadata into executable tests -/// - Handles all complex logic: -/// * Data source enumeration -/// * Tuple unwrapping -/// * Property injection -/// * Constructor parameter resolution -/// * Test instance creation -/// -/// Benefits: -/// - Simpler source generator (easier to maintain) -/// - Better debugging (step through actual code, not generated strings) -/// - Improved performance (expression compilation, caching) -/// - Clear separation of concerns -/// \ No newline at end of file diff --git a/Examples/GenericTestExamples.cs b/Examples/GenericTestExamples.cs deleted file mode 100644 index 5ac9696f2e..0000000000 --- a/Examples/GenericTestExamples.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using TUnit.Core; -using TUnit.Assertions; - -namespace TUnit.Examples; - -/// -/// Examples demonstrating generic test resolution for AOT scenarios -/// -public class GenericTestExamples -{ - /// - /// Generic test class that needs explicit type instantiation for AOT - /// - [GenerateGenericTest(typeof(int))] - [GenerateGenericTest(typeof(string))] - [GenerateGenericTest(typeof(DateTime))] - public class GenericRepositoryTests where T : IComparable - { - private readonly List _items = new(); - - [Test] - public async Task CanAddAndRetrieveItem(T item) - { - // Arrange & Act - _items.Add(item); - - // Assert - await Assert.That(_items).Contains(item); - await Assert.That(_items.Count).IsEqualTo(1); - } - - [Test] - public void CanSortItems() - { - // This test will be generated for int, string, and DateTime - _items.Sort(); - - // Verify sorting doesn't throw - Assert.That(_items).IsNotNull(); - } - } - - /// - /// Generic method with explicit type generation - /// - public class GenericMethodTests - { - [Test] - [GenerateGenericTest(typeof(int), typeof(string))] - [GenerateGenericTest(typeof(double), typeof(decimal))] - public async Task GenericSwap(T1 first, T2 second) - { - // Simple test to verify generic method generation - var tuple = (first, second); - var swapped = (tuple.Item2, tuple.Item1); - - await Assert.That(swapped.Item1).IsEqualTo(second); - await Assert.That(swapped.Item2).IsEqualTo(first); - } - - [Test] - [GenerateGenericTest(typeof(List))] - [GenerateGenericTest(typeof(Dictionary))] - public void ComplexGenericTypes() where T : new() - { - var instance = new T(); - Assert.That(instance).IsNotNull(); - } - } - - /// - /// Example with generic constraints - /// - public interface IEntity - { - int Id { get; } - } - - public class User : IEntity - { - public int Id { get; set; } - public string Name { get; set; } = ""; - } - - public class Product : IEntity - { - public int Id { get; set; } - public decimal Price { get; set; } - } - - [GenerateGenericTest(typeof(User))] - [GenerateGenericTest(typeof(Product))] - public class EntityServiceTests where TEntity : IEntity, new() - { - private readonly List _entities = new(); - - [Test] - public async Task CanCreateEntity() - { - // Arrange - var entity = new TEntity(); - - // Act - _entities.Add(entity); - - // Assert - await Assert.That(_entities).HasCount(1); - await Assert.That(_entities[0]).IsNotNull(); - } - - [Test] - public void EntityHasValidId() - { - var entity = new TEntity(); - - // Default ID should be 0 - Assert.That(entity.Id).IsEqualTo(0); - } - } - - /// - /// Nested generic types example - /// - [GenerateGenericTest(typeof(string), typeof(int))] - [GenerateGenericTest(typeof(DateTime), typeof(bool))] - public class NestedGenericTests - where TKey : IComparable - { - private readonly Dictionary> _data = new(); - - [Test] - public async Task CanStoreNestedData(TKey key, TValue value) - { - // Arrange - if (!_data.ContainsKey(key)) - { - _data[key] = new List(); - } - - // Act - _data[key].Add(value); - - // Assert - await Assert.That(_data[key]).Contains(value); - } - } - - /// - /// Example showing that without [GenerateGenericTest], - /// generic tests won't work in AOT mode - /// - public class NonAotGenericTest - { - [Test] - public void ThisWontWorkInAot() - { - // This test class has no [GenerateGenericTest] attribute - // So it won't be instantiated in AOT mode - // The source generator will skip it or generate a warning - var typeName = typeof(T).Name; - Assert.That(typeName).IsNotNull(); - } - } -} \ No newline at end of file diff --git a/Examples/ReflectionFreeExamples.cs b/Examples/ReflectionFreeExamples.cs deleted file mode 100644 index 9d1749810c..0000000000 --- a/Examples/ReflectionFreeExamples.cs +++ /dev/null @@ -1,279 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using TUnit.Core; -using TUnit.Assertions; - -namespace TUnit.Examples; - -/// -/// Examples demonstrating reflection-free test patterns in TUnit -/// -public class ReflectionFreeExamples -{ - /// - /// Basic test - no reflection needed, delegates are pre-compiled - /// - [Test] - public async Task BasicAsyncTest() - { - await Task.Delay(10); - await Assert.That(1 + 1).IsEqualTo(2); - } - - /// - /// Synchronous test with compile-time delegate generation - /// - [Test] - public void SynchronousTest() - { - var result = PerformCalculation(5, 3); - Assert.That(result).IsEqualTo(8); - } - - /// - /// Parameterized test with static data - fully AOT compatible - /// - [Test] - [Arguments(1, 1, 2)] - [Arguments(2, 3, 5)] - [Arguments(5, 8, 13)] - public void ParameterizedTest(int a, int b, int expected) - { - var result = a + b; - Assert.That(result).IsEqualTo(expected); - } - - /// - /// Test with compile-time resolved data source - /// - [Test] - [MethodDataSource(typeof(TestDataProviders), nameof(TestDataProviders.GetMathTestCases))] - public async Task DataDrivenTest(int input, int expected) - { - var result = input * 2; - await Assert.That(result).IsEqualTo(expected); - } - - /// - /// Test with async data source - AOT friendly with pre-compiled factory - /// - [Test] - [MethodDataSource(typeof(TestDataProviders), nameof(TestDataProviders.GetAsyncTestData))] - public async Task AsyncDataSourceTest(string input, bool expectedValid) - { - var isValid = IsValidInput(input); - await Assert.That(isValid).IsEqualTo(expectedValid); - } - - /// - /// Test with property data source - no reflection at runtime - /// - [Test] - [PropertyDataSource(typeof(TestDataProviders), nameof(TestDataProviders.StaticTestData))] - public void PropertyDataSourceTest(TestCase testCase) - { - var result = ProcessTestCase(testCase); - Assert.That(result).IsNotNull(); - } - - /// - /// Test with complex argument types - fully type-safe at compile time - /// - [Test] - [Arguments(new[] { 1, 2, 3 }, 6)] - [Arguments(new[] { 5, 10, 15 }, 30)] - public void ComplexArgumentTest(int[] numbers, int expectedSum) - { - var sum = 0; - foreach (var num in numbers) - { - sum += num; - } - Assert.That(sum).IsEqualTo(expectedSum); - } - - /// - /// Test with class-level data source for multiple test methods - /// - [ClassDataSource] - public class UserTests(string username, int userId) - { - [Test] - public void ValidateUsername() - { - Assert.That(username).IsNotNull() - .And.IsNotEmpty() - .And.HasLengthGreaterThan(3); - } - - [Test] - public async Task ValidateUserId() - { - await Assert.That(userId).IsGreaterThan(0); - } - } - - /// - /// Test with custom timeout - no reflection needed for attribute processing - /// - [Test] - [Timeout(5000)] - public async Task TimeoutTest() - { - await Task.Delay(100); - await Assert.That(true).IsTrue(); - } - - /// - /// Test with categories for filtering - compile-time metadata - /// - [Test] - [Category("Unit")] - [Category("Fast")] - public void CategorizedTest() - { - var result = QuickCalculation(); - Assert.That(result).IsGreaterThan(0); - } - - /// - /// Test with retry logic - handled through pre-compiled metadata - /// - [Test] - [Retry(3)] - public void RetryableTest() - { - var random = new Random(); - var value = random.Next(0, 10); - - // This might fail sometimes, but retry logic will handle it - Assert.That(value).IsGreaterThan(5); - } - - /// - /// Test with dependencies - resolved at compile time - /// - [Test] - [DependsOn(nameof(BasicAsyncTest))] - public async Task DependentTest() - { - // This test runs after BasicAsyncTest completes - await Task.Delay(10); - await Assert.That(GetDependentValue()).IsEqualTo(42); - } - - #region Helper Methods - - private int PerformCalculation(int a, int b) => a + b; - - private bool IsValidInput(string input) => !string.IsNullOrWhiteSpace(input); - - private object ProcessTestCase(TestCase testCase) => new { testCase.Name, testCase.Value }; - - private int QuickCalculation() => 42; - - private int GetDependentValue() => 42; - - #endregion -} - -/// -/// Data providers for reflection-free tests -/// All methods are resolved at compile time and stored as factories -/// -public static class TestDataProviders -{ - /// - /// Static data source method - pre-compiled into factory - /// - public static IEnumerable GetMathTestCases() - { - yield return new object[] { 1, 2 }; - yield return new object[] { 5, 10 }; - yield return new object[] { 10, 20 }; - } - - /// - /// Async data source - AOT compatible through factory pattern - /// - public static async Task> GetAsyncTestData() - { - await Task.Delay(1); // Simulate async operation - - return new[] - { - new object[] { "valid", true }, - new object[] { "", false }, - new object[] { "test", true }, - new object[] { null!, false } - }; - } - - /// - /// Property data source - accessed without reflection at runtime - /// - public static IEnumerable StaticTestData { get; } = new[] - { - new TestCase { Name = "Test1", Value = 100 }, - new TestCase { Name = "Test2", Value = 200 }, - new TestCase { Name = "Test3", Value = 300 } - }; -} - -/// -/// Test data class for property data source -/// -public class TestCase -{ - public required string Name { get; init; } - public required int Value { get; init; } -} - -/// -/// Class data source implementation -/// -public class UserTestData : IClassDataSource -{ - public IEnumerable GetData() - { - yield return new object[] { "alice", 1 }; - yield return new object[] { "bob", 2 }; - yield return new object[] { "charlie", 3 }; - } -} - -/// -/// Example showing generic test class handling in AOT mode -/// Generic parameters must be resolved at compile time -/// -public class GenericTestExample where T : IComparable -{ - private readonly T _value; - - public GenericTestExample(T value) - { - _value = value; - } - - [Test] - public void GenericTest() - { - Assert.That(_value).IsNotNull(); - } -} - -/// -/// Concrete instantiations for AOT compilation -/// -[InheritsTests(typeof(GenericTestExample))] -public class IntGenericTests : GenericTestExample -{ - public IntGenericTests() : base(42) { } -} - -[InheritsTests(typeof(GenericTestExample))] -public class StringGenericTests : GenericTestExample -{ - public StringGenericTests() : base("test") { } -} \ No newline at end of file diff --git a/Examples/UnifiedTestBuilderExample.cs b/Examples/UnifiedTestBuilderExample.cs deleted file mode 100644 index 49b12783ee..0000000000 --- a/Examples/UnifiedTestBuilderExample.cs +++ /dev/null @@ -1,313 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using TUnit.Core; -using TUnit.Engine; -using TUnit.Engine.Building; -using TUnit.Engine.Framework; - -namespace TUnit.Examples; - -/// -/// Example showing how to use the unified test builder architecture -/// -public class UnifiedTestBuilderExample -{ - /// - /// Example 1: Using the unified test builder in AOT mode (default) - /// - public static async Task ExampleAotMode() - { - // Setup services - var services = new ServiceCollection(); - - // Register test invoker and hook invoker (normally done by the framework) - services.AddSingleton(); - services.AddSingleton(); - - // Create a test metadata source (normally from source generation) - var metadataSource = new SourceGeneratedTestMetadataSource(() => GetSampleTestMetadata()); - - // Register the unified test builder for AOT mode - services.AddUnifiedTestBuilderAot(metadataSource); - - // Build service provider - var serviceProvider = services.BuildServiceProvider(); - - // Get the test discovery service - var discoveryService = serviceProvider.GetRequiredService(); - - // Discover all tests - var tests = await discoveryService.DiscoverTests(); - - Console.WriteLine($"Discovered {tests.Count()} tests in AOT mode"); - foreach (var test in tests) - { - Console.WriteLine($" - {test.DisplayName} [{test.TestId}]"); - } - } - - /// - /// Example 2: Using the unified test builder in reflection mode - /// - public static async Task ExampleReflectionMode() - { - // Setup services - var services = new ServiceCollection(); - - // Register test invoker and hook invoker - services.AddSingleton(); - services.AddSingleton(); - - // Get assemblies to scan - var assemblies = new[] { typeof(SampleTestClass).Assembly }; - - // Register the unified test builder for reflection mode - services.AddUnifiedTestBuilderReflection(assemblies); - - // Build service provider - var serviceProvider = services.BuildServiceProvider(); - - // Get the test discovery service - var discoveryService = serviceProvider.GetRequiredService(); - - // Discover all tests - var tests = await discoveryService.DiscoverTests(); - - Console.WriteLine($"Discovered {tests.Count()} tests in reflection mode"); - foreach (var test in tests) - { - Console.WriteLine($" - {test.DisplayName} [{test.TestId}]"); - } - } - - /// - /// Example 3: Using the pipeline directly - /// - public static async Task ExampleDirectPipeline() - { - // Create metadata source - var metadataSource = new SourceGeneratedTestMetadataSource(() => GetSampleTestMetadata()); - - // Create test and hook invokers - var testInvoker = new DefaultTestInvoker(); - var hookInvoker = new DefaultHookInvoker(); - - // Create the pipeline for AOT mode - var pipeline = UnifiedTestBuilderPipelineFactory.CreateAotPipeline( - metadataSource, - testInvoker, - hookInvoker); - - // Build all tests - var tests = await pipeline.BuildTestsAsync(); - - Console.WriteLine($"Built {tests.Count()} tests using direct pipeline"); - foreach (var test in tests) - { - Console.WriteLine($" - {test.DisplayName}"); - Console.WriteLine($" ID: {test.TestId}"); - Console.WriteLine($" Can run in parallel: {test.Metadata.CanRunInParallel}"); - } - } - - /// - /// Example 4: Data-driven tests with the new factory pattern - /// - public static async Task ExampleDataDrivenTests() - { - // Create test metadata with data sources - var metadata = new TestMetadata - { - TestId = "ExampleTests.DataDrivenTest", - TestName = "DataDrivenTest", - TestClassType = typeof(SampleTestClass), - TestMethodName = "TestWithData", - Categories = new[] { "DataDriven" }, - IsSkipped = false, - CanRunInParallel = true, - DependsOn = Array.Empty(), - - // Static data source with factory pattern - DataSources = new TestDataSource[] - { - new StaticTestDataSource( - new object?[][] - { - new object?[] { 1, 2, 3 }, - new object?[] { 4, 5, 9 }, - new object?[] { 10, 20, 30 } - }) - }, - - // Class-level data for constructor - ClassDataSources = new TestDataSource[] - { - new StaticTestDataSource( - new object?[][] - { - new object?[] { "TestContext1" }, - new object?[] { "TestContext2" } - }) - }, - - // Property data sources (single values) - PropertyDataSources = new PropertyDataSource[] - { - new PropertyDataSource - { - PropertyName = "TestProperty", - PropertyType = typeof(string), - DataSource = new StaticTestDataSource( - new object?[][] - { - new object?[] { "PropertyValue1" }, - new object?[] { "PropertyValue2" } - }) - } - }, - - ParameterCount = 3, - ParameterTypes = new[] { typeof(int), typeof(int), typeof(int) }, - Hooks = new TestHooks(), - InstanceFactory = args => new SampleTestClass((string)args[0]), - TestInvoker = async (instance, args) => - { - var method = instance.GetType().GetMethod("TestWithData"); - await Task.Run(() => method!.Invoke(instance, args)); - } - }; - - // Create a simple metadata source - var metadataSource = new SourceGeneratedTestMetadataSource(() => new[] { metadata }); - - // Create the pipeline - var pipeline = UnifiedTestBuilderPipelineFactory.CreateAotPipeline( - metadataSource, - new DefaultTestInvoker(), - new DefaultHookInvoker()); - - // Build tests - this will expand all data combinations - var tests = await pipeline.BuildTestsAsync(); - - Console.WriteLine($"Expanded to {tests.Count()} test variations:"); - foreach (var test in tests) - { - Console.WriteLine($" - {test.DisplayName}"); - - // The key feature: each test gets fresh data instances - var instance1 = await test.CreateInstance(); - var instance2 = await test.CreateInstance(); - - Console.WriteLine($" Instance 1: {instance1.GetHashCode()}"); - Console.WriteLine($" Instance 2: {instance2.GetHashCode()}"); - Console.WriteLine($" Instances are different: {!ReferenceEquals(instance1, instance2)}"); - } - } - - // Sample test metadata for examples - private static IEnumerable GetSampleTestMetadata() - { - return new[] - { - new TestMetadata - { - TestId = "SampleTests.Test1", - TestName = "Test1", - TestClassType = typeof(SampleTestClass), - TestMethodName = "SimpleTest", - Categories = Array.Empty(), - IsSkipped = false, - CanRunInParallel = true, - DependsOn = Array.Empty(), - DataSources = Array.Empty(), - ClassDataSources = Array.Empty(), - PropertyDataSources = Array.Empty(), - ParameterCount = 0, - ParameterTypes = Array.Empty(), - Hooks = new TestHooks() - }, - new TestMetadata - { - TestId = "SampleTests.Test2", - TestName = "Test2", - TestClassType = typeof(SampleTestClass), - TestMethodName = "TestWithTimeout", - Categories = new[] { "Integration" }, - IsSkipped = false, - TimeoutMs = 5000, - RetryCount = 2, - CanRunInParallel = false, - DependsOn = new[] { "SampleTests.Test1" }, - DataSources = Array.Empty(), - ClassDataSources = Array.Empty(), - PropertyDataSources = Array.Empty(), - ParameterCount = 0, - ParameterTypes = Array.Empty(), - Hooks = new TestHooks() - } - }; - } -} - -// Sample test class for examples -public class SampleTestClass -{ - private readonly string _context; - - public SampleTestClass() : this("default") { } - - public SampleTestClass(string context) - { - _context = context; - } - - public string TestProperty { get; set; } = ""; - - [Test] - public void SimpleTest() - { - Console.WriteLine($"Running SimpleTest in context: {_context}"); - } - - [Test] - [Timeout(5000)] - [Retry(2)] - [NotInParallel] - [DependsOn("SimpleTest")] - [Category("Integration")] - public async Task TestWithTimeout() - { - Console.WriteLine($"Running TestWithTimeout in context: {_context}"); - await Task.Delay(100); - } - - [Test] - [Arguments(1, 2, 3)] - [Arguments(4, 5, 9)] - public void TestWithData(int a, int b, int expected) - { - Console.WriteLine($"Testing {a} + {b} = {expected} in context: {_context}, property: {TestProperty}"); - } -} - -// Placeholder implementations for the example -public class DefaultTestInvoker : ITestInvoker -{ - public Task InvokeTestMethod(object instance, MethodInfo method, object?[] arguments) - { - var result = method.Invoke(instance, arguments); - if (result is Task task) - return task; - return Task.CompletedTask; - } -} - -public class DefaultHookInvoker : IHookInvoker -{ - public Task InvokeHookAsync(object? instance, MethodInfo method, HookContext context) - { - var result = method.Invoke(instance, new object[] { context }); - if (result is Task task) - return task; - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/README.md b/README.md index 5525b39b47..41afeb4395 100644 --- a/README.md +++ b/README.md @@ -375,683 +375,145 @@ dotnet add package TUnit --prerelease ### Scenario: Building the test project -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|------------- |-------- |--------:|---------:|---------:|--------:| -| Build_TUnit | 0.66.6 | 1.425 s | 0.0954 s | 0.2722 s | 1.384 s | -| Build_NUnit | 4.4.0 | 1.171 s | 0.0670 s | 0.1934 s | 1.150 s | -| Build_xUnit | 2.9.3 | 1.149 s | 0.0853 s | 0.2448 s | 1.101 s | -| Build_MSTest | 3.11.0 | 1.108 s | 0.0468 s | 0.1365 s | 1.103 s | -| Build_xUnit3 | 3.1.0 | 1.144 s | 0.0763 s | 0.2238 s | 1.093 s | - - - -#### ubuntu-latest - ``` BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 +AMD EPYC 7763 2.73GHz, 1 CPU, 4 logical and 2 physical cores +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` | Method | Version | Mean | Error | StdDev | Median | |------------- |-------- |--------:|---------:|---------:|--------:| -| Build_TUnit | 0.66.6 | 1.645 s | 0.0212 s | 0.0188 s | 1.645 s | -| Build_NUnit | 4.4.0 | 1.500 s | 0.0294 s | 0.0302 s | 1.502 s | -| Build_xUnit | 2.9.3 | 1.513 s | 0.0175 s | 0.0163 s | 1.513 s | -| Build_MSTest | 3.11.0 | 1.534 s | 0.0136 s | 0.0127 s | 1.539 s | -| Build_xUnit3 | 3.1.0 | 1.496 s | 0.0247 s | 0.0219 s | 1.500 s | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|------------- |-------- |--------:|---------:|---------:|--------:| -| Build_TUnit | 0.66.6 | 2.134 s | 0.0440 s | 0.1275 s | 2.143 s | -| Build_NUnit | 4.4.0 | 2.085 s | 0.0360 s | 0.0319 s | 2.085 s | -| Build_xUnit | 2.9.3 | 2.055 s | 0.0406 s | 0.0865 s | 2.057 s | -| Build_MSTest | 3.11.0 | 2.160 s | 0.0431 s | 0.1142 s | 2.152 s | -| Build_xUnit3 | 3.1.0 | 2.136 s | 0.0424 s | 0.0505 s | 2.124 s | - - -### Scenario: Tests focused on assertion performance and validation - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 507.19 ms | 28.541 ms | 83.71 ms | 497.91 ms | -| NUnit | 4.4.0 | NA | NA | NA | NA | -| xUnit | 2.9.3 | 884.34 ms | 54.651 ms | 160.28 ms | 895.71 ms | -| MSTest | 3.11.0 | 768.27 ms | 39.207 ms | 115.60 ms | 746.33 ms | -| xUnit3 | 3.1.0 | 493.87 ms | 16.161 ms | 47.40 ms | 503.28 ms | -| TUnit_AOT | 0.66.6 | 70.85 ms | 7.276 ms | 21.34 ms | 67.87 ms | - -Benchmarks with issues: - RuntimeBenchmarks.NUnit: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest - -``` - -BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.61GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 487.37 ms | 3.093 ms | 2.893 ms | 487.43 ms | -| NUnit | 4.4.0 | 908.34 ms | 17.276 ms | 16.967 ms | 911.94 ms | -| xUnit | 2.9.3 | 984.77 ms | 19.259 ms | 18.015 ms | 979.06 ms | -| MSTest | 3.11.0 | 836.95 ms | 11.507 ms | 10.764 ms | 832.08 ms | -| xUnit3 | 3.1.0 | 458.16 ms | 4.159 ms | 3.890 ms | 457.83 ms | -| TUnit_AOT | 0.66.6 | 25.31 ms | 0.431 ms | 0.382 ms | 25.16 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 533.36 ms | 3.679 ms | 3.441 ms | 532.96 ms | -| NUnit | 4.4.0 | 1,016.18 ms | 20.186 ms | 34.820 ms | 1,015.43 ms | -| xUnit | 2.9.3 | 1,068.97 ms | 20.224 ms | 16.888 ms | 1,073.74 ms | -| MSTest | 3.11.0 | 968.58 ms | 17.772 ms | 31.127 ms | 964.24 ms | -| xUnit3 | 3.1.0 | 516.29 ms | 7.819 ms | 6.931 ms | 515.39 ms | -| TUnit_AOT | 0.66.6 | 65.97 ms | 2.281 ms | 6.724 ms | 65.43 ms | +| Build_TUnit | 0.78.0 | 1.777 s | 0.0332 s | 0.0341 s | 1.765 s | +| Build_NUnit | 4.4.0 | 1.582 s | 0.0152 s | 0.0143 s | 1.577 s | +| Build_MSTest | 4.0.1 | 1.667 s | 0.0137 s | 0.0128 s | 1.668 s | +| Build_xUnit3 | 3.1.0 | 1.570 s | 0.0101 s | 0.0090 s | 1.569 s | ### Scenario: Tests running asynchronous operations and async/await patterns -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |-----------:|---------:|----------:|-----------:| -| TUnit | 0.66.6 | 608.9 ms | 39.85 ms | 117.49 ms | 577.8 ms | -| NUnit | 4.4.0 | 1,260.3 ms | 57.30 ms | 166.24 ms | 1,274.6 ms | -| xUnit | 2.9.3 | NA | NA | NA | NA | -| MSTest | 3.11.0 | 1,050.5 ms | 41.59 ms | 119.99 ms | 1,053.4 ms | -| xUnit3 | 3.1.0 | 559.6 ms | 21.67 ms | 62.18 ms | 567.1 ms | -| TUnit_AOT | 0.66.6 | 144.6 ms | 11.89 ms | 34.88 ms | 145.0 ms | - -Benchmarks with issues: - RuntimeBenchmarks.xUnit: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest - ``` BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` | Method | Version | Mean | Error | StdDev | Median | |---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 447.34 ms | 3.704 ms | 3.465 ms | 447.86 ms | -| NUnit | 4.4.0 | 907.30 ms | 17.922 ms | 18.404 ms | 901.36 ms | -| xUnit | 2.9.3 | 988.70 ms | 19.061 ms | 17.830 ms | 983.11 ms | -| MSTest | 3.11.0 | 842.79 ms | 16.374 ms | 17.520 ms | 842.60 ms | -| xUnit3 | 3.1.0 | 460.86 ms | 2.968 ms | 2.777 ms | 459.81 ms | -| TUnit_AOT | 0.66.6 | 26.67 ms | 0.506 ms | 0.562 ms | 26.78 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 494.36 ms | 7.194 ms | 6.729 ms | 490.64 ms | -| NUnit | 4.4.0 | 1,005.78 ms | 18.596 ms | 17.394 ms | 1,007.02 ms | -| xUnit | 2.9.3 | 1,096.34 ms | 20.797 ms | 22.253 ms | 1,097.98 ms | -| MSTest | 3.11.0 | 962.06 ms | 18.672 ms | 26.175 ms | 957.03 ms | -| xUnit3 | 3.1.0 | 522.65 ms | 9.988 ms | 9.343 ms | 521.69 ms | -| TUnit_AOT | 0.66.6 | 89.31 ms | 2.294 ms | 6.728 ms | 89.53 ms | - - -### Scenario: Simple tests with basic operations and assertions - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|---------:|----------:| -| TUnit | 0.66.6 | 413.11 ms | 29.400 ms | 85.30 ms | 389.28 ms | -| NUnit | 4.4.0 | NA | NA | NA | NA | -| xUnit | 2.9.3 | NA | NA | NA | NA | -| MSTest | 3.11.0 | NA | NA | NA | NA | -| xUnit3 | 3.1.0 | 289.63 ms | 7.455 ms | 21.51 ms | 285.72 ms | -| TUnit_AOT | 0.66.6 | 66.85 ms | 9.402 ms | 27.57 ms | 61.87 ms | - -Benchmarks with issues: - RuntimeBenchmarks.NUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.xUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.MSTest: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest - -``` - -BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 466.81 ms | 5.399 ms | 4.786 ms | 466.44 ms | -| NUnit | 4.4.0 | 919.54 ms | 16.718 ms | 15.638 ms | 919.80 ms | -| xUnit | 2.9.3 | 994.05 ms | 10.533 ms | 9.337 ms | 992.55 ms | -| MSTest | 3.11.0 | 853.21 ms | 16.534 ms | 17.691 ms | 854.80 ms | -| xUnit3 | 3.1.0 | 459.93 ms | 3.301 ms | 2.926 ms | 458.96 ms | -| TUnit_AOT | 0.66.6 | 25.34 ms | 0.444 ms | 0.415 ms | 25.14 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 517.27 ms | 4.416 ms | 4.130 ms | 518.39 ms | -| NUnit | 4.4.0 | 1,018.48 ms | 20.084 ms | 19.725 ms | 1,014.70 ms | -| xUnit | 2.9.3 | 1,079.55 ms | 19.399 ms | 18.145 ms | 1,079.08 ms | -| MSTest | 3.11.0 | 950.05 ms | 18.521 ms | 21.329 ms | 953.91 ms | -| xUnit3 | 3.1.0 | 509.16 ms | 6.805 ms | 6.365 ms | 507.00 ms | -| TUnit_AOT | 0.66.6 | 66.58 ms | 1.505 ms | 4.414 ms | 65.67 ms | +| TUnit | 0.78.0 | 452.17 ms | 3.388 ms | 2.829 ms | 452.69 ms | +| NUnit | 4.4.0 | 565.57 ms | 9.621 ms | 8.528 ms | 567.10 ms | +| MSTest | 4.0.1 | 578.39 ms | 11.254 ms | 12.960 ms | 574.71 ms | +| xUnit3 | 3.1.0 | 522.50 ms | 4.072 ms | 3.610 ms | 522.72 ms | +| TUnit_AOT | 0.78.0 | 24.35 ms | 0.406 ms | 0.380 ms | 24.34 ms | ### Scenario: Parameterized tests with multiple test cases using data attributes -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|---------:|----------:| -| TUnit | 0.66.6 | 408.74 ms | 18.928 ms | 55.21 ms | 396.30 ms | -| NUnit | 4.4.0 | NA | NA | NA | NA | -| xUnit | 2.9.3 | NA | NA | NA | NA | -| MSTest | 3.11.0 | 659.03 ms | 22.634 ms | 66.38 ms | 666.53 ms | -| xUnit3 | 3.1.0 | 377.11 ms | 11.684 ms | 33.90 ms | 379.14 ms | -| TUnit_AOT | 0.66.6 | 44.69 ms | 3.968 ms | 11.39 ms | 41.36 ms | - -Benchmarks with issues: - RuntimeBenchmarks.NUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.xUnit: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest - ``` BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 +AMD EPYC 7763 3.23GHz, 1 CPU, 4 logical and 2 physical cores +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 460.22 ms | 2.117 ms | 1.877 ms | 460.03 ms | -| NUnit | 4.4.0 | 909.38 ms | 16.413 ms | 15.352 ms | 917.73 ms | -| xUnit | 2.9.3 | 1,016.83 ms | 18.472 ms | 17.279 ms | 1,008.66 ms | -| MSTest | 3.11.0 | 866.29 ms | 16.852 ms | 18.031 ms | 865.01 ms | -| xUnit3 | 3.1.0 | 486.65 ms | 3.559 ms | 3.155 ms | 487.03 ms | -| TUnit_AOT | 0.66.6 | 28.22 ms | 0.343 ms | 0.304 ms | 28.31 ms | - +| Method | Version | Mean | Error | StdDev | Median | +|---------- |-------- |----------:|---------:|----------:|----------:| +| TUnit | 0.78.0 | 497.97 ms | 9.414 ms | 10.073 ms | 496.53 ms | +| NUnit | 4.4.0 | 616.29 ms | 8.142 ms | 7.218 ms | 613.56 ms | +| MSTest | 4.0.1 | 631.89 ms | 8.377 ms | 6.995 ms | 630.92 ms | +| xUnit3 | 3.1.0 | 549.54 ms | 5.447 ms | 4.829 ms | 548.19 ms | +| TUnit_AOT | 0.78.0 | 24.02 ms | 0.201 ms | 0.157 ms | 24.04 ms | -#### windows-latest +### Scenario: Tests executing massively parallel workloads with CPU-bound, I/O-bound, and mixed operations ``` -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|-----------:|------------:| -| TUnit | 0.66.6 | 550.13 ms | 10.668 ms | 10.477 ms | 545.52 ms | -| NUnit | 4.4.0 | 1,115.22 ms | 22.111 ms | 23.658 ms | 1,115.33 ms | -| xUnit | 2.9.3 | 1,209.43 ms | 35.495 ms | 100.694 ms | 1,223.99 ms | -| MSTest | 3.11.0 | 1,041.10 ms | 20.681 ms | 23.817 ms | 1,038.52 ms | -| xUnit3 | 3.1.0 | 565.34 ms | 10.258 ms | 9.596 ms | 565.75 ms | -| TUnit_AOT | 0.66.6 | 71.69 ms | 1.423 ms | 3.410 ms | 71.39 ms | - - -### Scenario: Tests utilizing class fixtures and shared test context - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a +BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) +Intel Xeon Platinum 8370C CPU 2.80GHz (Max: 2.62GHz), 1 CPU, 4 logical and 2 physical cores +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v4 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v4 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` | Method | Version | Mean | Error | StdDev | Median | |---------- |-------- |----------:|----------:|---------:|----------:| -| TUnit | 0.66.6 | 286.49 ms | 6.152 ms | 17.75 ms | 285.41 ms | -| NUnit | 4.4.0 | NA | NA | NA | NA | -| xUnit | 2.9.3 | NA | NA | NA | NA | -| MSTest | 3.11.0 | NA | NA | NA | NA | -| xUnit3 | 3.1.0 | 375.36 ms | 22.387 ms | 66.01 ms | 362.13 ms | -| TUnit_AOT | 0.66.6 | 64.68 ms | 6.634 ms | 19.03 ms | 62.08 ms | +| TUnit | 0.78.0 | 439.78 ms | 3.590 ms | 2.998 ms | 440.24 ms | +| NUnit | 4.4.0 | 579.16 ms | 10.529 ms | 9.334 ms | 576.13 ms | +| MSTest | 4.0.1 | 592.15 ms | 11.068 ms | 9.242 ms | 592.37 ms | +| xUnit3 | 3.1.0 | 541.26 ms | 3.818 ms | 3.385 ms | 541.16 ms | +| TUnit_AOT | 0.78.0 | 29.11 ms | 0.289 ms | 0.256 ms | 29.09 ms | -Benchmarks with issues: - RuntimeBenchmarks.NUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.xUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.MSTest: Job-YNJDZW(Runtime=.NET 9.0) - - -#### ubuntu-latest +### Scenario: Tests with complex parameter combinations creating 25-125 test variations ``` BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 +AMD EPYC 7763 2.77GHz, 1 CPU, 4 logical and 2 physical cores +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 452.99 ms | 3.907 ms | 3.263 ms | 453.44 ms | -| NUnit | 4.4.0 | 930.95 ms | 14.776 ms | 13.821 ms | 935.97 ms | -| xUnit | 2.9.3 | 1,006.26 ms | 16.690 ms | 15.611 ms | 1,000.82 ms | -| MSTest | 3.11.0 | 850.14 ms | 16.934 ms | 18.119 ms | 852.12 ms | -| xUnit3 | 3.1.0 | 450.19 ms | 4.025 ms | 3.765 ms | 450.09 ms | -| TUnit_AOT | 0.66.6 | 38.57 ms | 1.098 ms | 3.220 ms | 38.60 ms | - +| Method | Version | Mean | Error | StdDev | Median | +|---------- |-------- |----------:|---------:|---------:|----------:| +| TUnit | 0.78.0 | 477.67 ms | 5.540 ms | 5.182 ms | 477.54 ms | +| NUnit | 4.4.0 | 603.24 ms | 9.112 ms | 7.609 ms | 603.63 ms | +| MSTest | 4.0.1 | 618.86 ms | 9.034 ms | 7.544 ms | 618.20 ms | +| xUnit3 | 3.1.0 | 541.77 ms | 4.720 ms | 4.184 ms | 542.61 ms | +| TUnit_AOT | 0.78.0 | 28.99 ms | 0.374 ms | 0.331 ms | 28.99 ms | -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 495.87 ms | 8.424 ms | 10.653 ms | 492.34 ms | -| NUnit | 4.4.0 | 973.98 ms | 19.011 ms | 18.671 ms | 972.03 ms | -| xUnit | 2.9.3 | 1,049.78 ms | 14.531 ms | 13.593 ms | 1,044.49 ms | -| MSTest | 3.11.0 | 916.98 ms | 16.913 ms | 15.821 ms | 912.23 ms | -| xUnit3 | 3.1.0 | 486.78 ms | 3.897 ms | 3.645 ms | 486.01 ms | -| TUnit_AOT | 0.66.6 | 91.20 ms | 1.800 ms | 3.152 ms | 91.43 ms | - - -### Scenario: Tests executing in parallel to test framework parallelization - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|-----------:|----------:|------------:| -| TUnit | 0.66.6 | 410.22 ms | 23.733 ms | 69.23 ms | 402.84 ms | -| NUnit | 4.4.0 | 1,342.07 ms | 95.053 ms | 274.25 ms | 1,303.84 ms | -| xUnit | 2.9.3 | 1,328.93 ms | 101.864 ms | 300.35 ms | 1,301.91 ms | -| MSTest | 3.11.0 | NA | NA | NA | NA | -| xUnit3 | 3.1.0 | 470.25 ms | 20.347 ms | 58.38 ms | 468.24 ms | -| TUnit_AOT | 0.66.6 | 58.77 ms | 7.644 ms | 21.93 ms | 53.57 ms | - -Benchmarks with issues: - RuntimeBenchmarks.MSTest: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest +### Scenario: Large-scale parameterized tests with 100+ test cases testing framework scalability ``` BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) AMD EPYC 7763 2.45GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 +.NET SDK 10.0.100-rc.2.25502.107 + [Host] : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 + RyuJitX64 : .NET 10.0.0 (10.0.0-rc.2.25502.107, 10.0.25.50307), X64 RyuJIT x86-64-v3 -Runtime=.NET 9.0 +Job=RyuJitX64 Jit=RyuJit Platform=X64 +PowerPlanMode=00000000-0000-0000-0000-000000000000 Runtime=.NET 10.0 Concurrent=True +Server=True ``` | Method | Version | Mean | Error | StdDev | Median | |---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 442.19 ms | 1.731 ms | 1.534 ms | 441.97 ms | -| NUnit | 4.4.0 | 918.06 ms | 17.680 ms | 17.364 ms | 921.88 ms | -| xUnit | 2.9.3 | 983.91 ms | 18.873 ms | 17.654 ms | 979.36 ms | -| MSTest | 3.11.0 | 838.79 ms | 14.777 ms | 13.823 ms | 844.27 ms | -| xUnit3 | 3.1.0 | 449.58 ms | 2.903 ms | 2.573 ms | 449.82 ms | -| TUnit_AOT | 0.66.6 | 24.97 ms | 0.208 ms | 0.184 ms | 24.95 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 510.80 ms | 3.865 ms | 3.616 ms | 511.67 ms | -| NUnit | 4.4.0 | 1,085.21 ms | 21.543 ms | 37.161 ms | 1,079.30 ms | -| xUnit | 2.9.3 | 1,125.35 ms | 22.326 ms | 27.418 ms | 1,124.00 ms | -| MSTest | 3.11.0 | 979.31 ms | 15.894 ms | 14.867 ms | 979.73 ms | -| xUnit3 | 3.1.0 | 526.16 ms | 5.769 ms | 5.396 ms | 526.42 ms | -| TUnit_AOT | 0.66.6 | 65.78 ms | 1.726 ms | 5.063 ms | 65.93 ms | - - -### Scenario: A test that takes 50ms to execute, repeated 100 times - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |----------:|----------:|----------:|----------:| -| TUnit | 0.66.6 | 338.92 ms | 19.812 ms | 58.105 ms | 325.53 ms | -| NUnit | 4.4.0 | 574.90 ms | 9.258 ms | 7.228 ms | 572.83 ms | -| xUnit | 2.9.3 | NA | NA | NA | NA | -| MSTest | 3.11.0 | NA | NA | NA | NA | -| xUnit3 | 3.1.0 | 324.91 ms | 10.115 ms | 29.507 ms | 318.54 ms | -| TUnit_AOT | 0.66.6 | 60.53 ms | 8.531 ms | 24.613 ms | 56.15 ms | - -Benchmarks with issues: - RuntimeBenchmarks.xUnit: Job-YNJDZW(Runtime=.NET 9.0) - RuntimeBenchmarks.MSTest: Job-YNJDZW(Runtime=.NET 9.0) - - - -#### ubuntu-latest - -``` - -BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 2.90GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 486.94 ms | 3.897 ms | 3.645 ms | 487.44 ms | -| NUnit | 4.4.0 | 925.61 ms | 17.307 ms | 16.189 ms | 922.59 ms | -| xUnit | 2.9.3 | 1,085.95 ms | 20.200 ms | 17.906 ms | 1,082.26 ms | -| MSTest | 3.11.0 | 858.03 ms | 16.000 ms | 14.966 ms | 856.06 ms | -| xUnit3 | 3.1.0 | 491.88 ms | 4.490 ms | 3.980 ms | 489.95 ms | -| TUnit_AOT | 0.66.6 | 40.90 ms | 0.680 ms | 0.636 ms | 40.67 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 560.34 ms | 10.543 ms | 9.862 ms | 559.08 ms | -| NUnit | 4.4.0 | 1,072.50 ms | 20.980 ms | 45.608 ms | 1,074.71 ms | -| xUnit | 2.9.3 | 1,232.15 ms | 24.387 ms | 26.094 ms | 1,232.77 ms | -| MSTest | 3.11.0 | 994.43 ms | 19.847 ms | 54.995 ms | 991.14 ms | -| xUnit3 | 3.1.0 | 580.80 ms | 11.371 ms | 15.180 ms | 581.16 ms | -| TUnit_AOT | 0.66.6 | 81.43 ms | 2.104 ms | 6.203 ms | 82.90 ms | - - -### Scenario: Tests with setup and teardown lifecycle methods - -#### macos-latest - -``` - -BenchmarkDotNet v0.15.4, macOS Sequoia 15.6.1 (24G90) [Darwin 24.6.0] -Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), Arm64 RyuJIT armv8.0-a - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 525.73 ms | 37.455 ms | 108.66 ms | 518.72 ms | -| NUnit | 4.4.0 | 1,163.42 ms | 50.082 ms | 143.69 ms | 1,154.49 ms | -| xUnit | 2.9.3 | 1,063.35 ms | 38.811 ms | 113.83 ms | 1,063.37 ms | -| MSTest | 3.11.0 | 864.08 ms | 79.507 ms | 234.43 ms | 768.70 ms | -| xUnit3 | 3.1.0 | 389.16 ms | 18.371 ms | 53.59 ms | 391.37 ms | -| TUnit_AOT | 0.66.6 | 50.16 ms | 6.305 ms | 18.19 ms | 48.60 ms | - - - -#### ubuntu-latest - -``` - -BenchmarkDotNet v0.15.4, Linux Ubuntu 24.04.3 LTS (Noble Numbat) -AMD EPYC 7763 3.14GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 467.37 ms | 2.088 ms | 1.953 ms | 467.00 ms | -| NUnit | 4.4.0 | 937.52 ms | 18.192 ms | 19.465 ms | 935.06 ms | -| xUnit | 2.9.3 | 1,033.10 ms | 18.060 ms | 16.894 ms | 1,028.90 ms | -| MSTest | 3.11.0 | 885.00 ms | 17.336 ms | 17.026 ms | 882.50 ms | -| xUnit3 | 3.1.0 | 465.87 ms | 3.757 ms | 3.331 ms | 465.39 ms | -| TUnit_AOT | 0.66.6 | 26.79 ms | 0.208 ms | 0.174 ms | 26.82 ms | - - - -#### windows-latest - -``` - -BenchmarkDotNet v0.15.4, Windows 11 (10.0.26100.6584/24H2/2024Update/HudsonValley) (Hyper-V) -AMD EPYC 7763 2.44GHz, 1 CPU, 4 logical and 2 physical cores -.NET SDK 9.0.305 - [Host] : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - Job-YNJDZW : .NET 9.0.9 (9.0.9, 9.0.925.41916), X64 RyuJIT x86-64-v3 - -Runtime=.NET 9.0 - -``` -| Method | Version | Mean | Error | StdDev | Median | -|---------- |-------- |------------:|----------:|----------:|------------:| -| TUnit | 0.66.6 | 527.84 ms | 10.425 ms | 24.160 ms | 521.87 ms | -| NUnit | 4.4.0 | 1,069.13 ms | 21.368 ms | 22.864 ms | 1,069.02 ms | -| xUnit | 2.9.3 | 1,152.17 ms | 22.381 ms | 29.102 ms | 1,160.05 ms | -| MSTest | 3.11.0 | 994.82 ms | 19.730 ms | 21.929 ms | 994.32 ms | -| xUnit3 | 3.1.0 | 544.24 ms | 10.540 ms | 14.071 ms | 543.06 ms | -| TUnit_AOT | 0.66.6 | 68.69 ms | 2.349 ms | 6.815 ms | 68.38 ms | +| TUnit | 0.78.0 | 478.45 ms | 5.465 ms | 4.844 ms | 478.34 ms | +| NUnit | 4.4.0 | 585.18 ms | 10.662 ms | 10.471 ms | 583.94 ms | +| MSTest | 4.0.1 | 569.01 ms | 11.041 ms | 15.114 ms | 568.46 ms | +| xUnit3 | 3.1.0 | 508.09 ms | 5.421 ms | 4.806 ms | 508.19 ms | +| TUnit_AOT | 0.78.0 | 46.62 ms | 1.520 ms | 4.481 ms | 47.06 ms | diff --git a/StringMatchesAssertion.patch b/StringMatchesAssertion.patch new file mode 100644 index 0000000000..a5dac85a28 --- /dev/null +++ b/StringMatchesAssertion.patch @@ -0,0 +1,88 @@ +REQUIRED CHANGES TO: TUnit.Assertions/Conditions/StringAssertions.cs + +This patch adds Match caching to StringMatchesAssertion class to enable clean, reflection-free access to regex match results. + +================================================================================ +CHANGE 1: Add _cachedMatch field +================================================================================ +Location: Line 432 (after "private RegexOptions _options = RegexOptions.None;") + +ADD THIS LINE: + private Match? _cachedMatch; + +So it becomes: + private readonly string _pattern; + private readonly Regex? _regex; + private RegexOptions _options = RegexOptions.None; + private Match? _cachedMatch; // <-- ADD THIS LINE + +================================================================================ +CHANGE 2: Add GetMatch() method +================================================================================ +Location: After line 464 (after the WithOptions() method, before CheckAsync()) + +ADD THIS METHOD: + /// + /// Gets the cached regex match result after the assertion has been executed. + /// Returns null if the assertion hasn't been executed yet or if the match failed. + /// + public Match? GetMatch() => _cachedMatch; + +So it becomes: + public StringMatchesAssertion WithOptions(RegexOptions options) + { + _options = options; + Context.ExpressionBuilder.Append($".WithOptions({options})"); + return this; + } + + /// + /// Gets the cached regex match result after the assertion has been executed. + /// Returns null if the assertion hasn't been executed yet or if the match failed. + /// + public Match? GetMatch() => _cachedMatch; // <-- ADD THIS METHOD + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + +================================================================================ +CHANGE 3: Modify CheckAsync() to cache the Match +================================================================================ +Location: Lines 486-492 in CheckAsync() method + +REPLACE THIS: + // Use the validated regex to check the match + bool isMatch = regex.IsMatch(value); + + if (isMatch) + { + return Task.FromResult(AssertionResult.Passed); + } + +WITH THIS: + // Use the validated regex to check the match and cache it + var match = regex.Match(value); + _cachedMatch = match; + + if (match.Success) + { + return Task.FromResult(AssertionResult.Passed); + } + +EXPLANATION: +- Changed from regex.IsMatch(value) to regex.Match(value) to get the Match object +- Store the Match in _cachedMatch field +- Changed from checking isMatch to checking match.Success + +================================================================================ +SUMMARY +================================================================================ +These changes enable StringMatchesAssertionExtensions.GetMatchAsync() to work +without reflection by calling the new GetMatch() method. + +The implementation follows SOLID, KISS, DRY, and SRP principles: +- Single Responsibility: StringMatchesAssertion now caches its match +- Open/Closed: API extended without modifying existing behavior +- No reflection: Clean, AOT-compatible code +- DRY: Match is performed once and cached +- KISS: Simple, straightforward implementation diff --git a/TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs b/TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs index 2a9a31064a..4b545d6757 100644 --- a/TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs +++ b/TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs @@ -494,4 +494,707 @@ public void Test1() """ ); } + + + [Test] + [Arguments("Class")] + [Arguments("Assembly")] + [Arguments("TestSession")] + public async Task Bug3213(string hook) + { + await Verifier + .VerifyAnalyzerAsync( + $$""" + using System; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using TUnit.Core; + + record RegisterPaymentHttp(string BookingId, string RoomId, decimal Amount, DateTimeOffset PaidAt); + record BookingState; + class Result { public class Ok { public HttpStatusCode StatusCode { get; set; } } } + class BookingEvents { public record BookingFullyPaid(DateTimeOffset PaidAt); } + class Booking { public object Payload { get; set; } = null!; } + class RestRequest { + public RestRequest(string path) { } + public RestRequest AddJsonBody(object obj) => this; + } + class ServerFixture { + public HttpClient GetClient() => null!; + public static BookRoom GetBookRoom() => null!; + public Task> ReadStream(string id) => Task.FromResult(Enumerable.Empty()); + } + class BookRoom { + public string BookingId => string.Empty; + public string RoomId => string.Empty; + } + class TestEventListener : IDisposable { + public void Dispose() { } + } + static class HttpClientExtensions { + public static Task PostJsonAsync(this HttpClient client, string path, object body, CancellationToken cancellationToken) => Task.CompletedTask; + public static Task ExecutePostAsync(this HttpClient client, RestRequest request, CancellationToken cancellationToken) => Task.FromResult(default!); + } + static class ObjectExtensions { + public static void ShouldBe(this object obj, object expected) { } + public static void ShouldBeEquivalentTo(this object obj, object expected) { } + } + + [ClassDataSource] + public class ControllerTests { + readonly ServerFixture _fixture = null!; + + public ControllerTests(string value) { + } + + [Test] + public async Task RecordPaymentUsingMappedCommand(CancellationToken cancellationToken) { + using var client = _fixture.GetClient(); + + var bookRoom = ServerFixture.GetBookRoom(); + + await client.PostJsonAsync("/book", bookRoom, cancellationToken: cancellationToken); + + var registerPayment = new RegisterPaymentHttp(bookRoom.BookingId, bookRoom.RoomId, 100, DateTimeOffset.Now); + + var request = new RestRequest("/v2/pay").AddJsonBody(registerPayment); + var response = await client.ExecutePostAsync.Ok>(request, cancellationToken: cancellationToken); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + + var expected = new BookingEvents.BookingFullyPaid(registerPayment.PaidAt); + + var events = await _fixture.ReadStream(bookRoom.BookingId); + var last = events.LastOrDefault(); + last!.Payload.ShouldBeEquivalentTo(expected); + } + + static TestEventListener? listener; + + [After(HookType.{{hook}})] + public static void Dispose() => listener?.Dispose(); + + [Before(HookType.{{hook}})] + public static void BeforeClass() => listener = new(); + } + """ + ); + } + + [Test] + public async Task New_Disposable_In_AsyncInitializer_Flags_Issue() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + using TUnit.Core.Interfaces; + + public class DisposableFieldTests : IAsyncInitializer + { + private HttpClient? {|#0:_httpClient|}; + + public Task InitializeAsync() + { + _httpClient = new HttpClient(); + return Task.CompletedTask; + } + + [Test] + public void Test1() + { + } + } + """, + + Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup) + .WithLocation(0) + .WithArguments("_httpClient") + ); + } + + [Test] + public async Task New_Disposable_In_AsyncInitializer_No_Issue_When_Cleaned_Up() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + using TUnit.Core.Interfaces; + + public class DisposableFieldTests : IAsyncInitializer, IAsyncDisposable + { + private HttpClient? _httpClient; + + public Task InitializeAsync() + { + _httpClient = new HttpClient(); + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() + { + _httpClient?.Dispose(); + return ValueTask.CompletedTask; + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // FIELD INITIALIZATION TESTS + // ======================================== + + [Test] + public async Task FieldInitialization_Flags_Issue() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private HttpClient? {|#0:_httpClient|} = new HttpClient(); + + [Test] + public void Test1() + { + } + } + """, + + Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup) + .WithLocation(0) + .WithArguments("_httpClient") + ); + } + + [Test] + public async Task FieldInitialization_No_Issue_When_Disposed_In_Dispose() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests : IDisposable + { + private HttpClient? _httpClient = new HttpClient(); + + public void Dispose() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task FieldInitialization_No_Issue_When_Disposed_In_DisposeAsync() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + + public class DisposableFieldTests : IAsyncDisposable + { + private HttpClient? _httpClient = new HttpClient(); + + public ValueTask DisposeAsync() + { + _httpClient?.Dispose(); + return ValueTask.CompletedTask; + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task FieldInitialization_No_Issue_When_Disposed_In_After() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private HttpClient? _httpClient = new HttpClient(); + + [After(HookType.Test)] + public void Cleanup() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // CONSTRUCTOR INITIALIZATION TESTS + // ======================================== + + [Test] + public async Task Constructor_Flags_Issue() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private HttpClient? {|#0:_httpClient|}; + + public DisposableFieldTests() + { + _httpClient = new HttpClient(); + } + + [Test] + public void Test1() + { + } + } + """, + + Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup) + .WithLocation(0) + .WithArguments("_httpClient") + ); + } + + [Test] + public async Task Constructor_No_Issue_When_Disposed_In_Dispose() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests : IDisposable + { + private HttpClient? _httpClient; + + public DisposableFieldTests() + { + _httpClient = new HttpClient(); + } + + public void Dispose() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task Constructor_No_Issue_When_Disposed_In_DisposeAsync() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + + public class DisposableFieldTests : IAsyncDisposable + { + private HttpClient? _httpClient; + + public DisposableFieldTests() + { + _httpClient = new HttpClient(); + } + + public ValueTask DisposeAsync() + { + _httpClient?.Dispose(); + return ValueTask.CompletedTask; + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task Constructor_No_Issue_When_Disposed_In_After() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private HttpClient? _httpClient; + + public DisposableFieldTests() + { + _httpClient = new HttpClient(); + } + + [After(HookType.Test)] + public void Cleanup() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // BEFORE(TEST) WITH DISPOSE/DISPOSEASYNC TESTS + // ======================================== + + [Test] + public async Task BeforeTest_No_Issue_When_Disposed_In_Dispose() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests : IDisposable + { + private HttpClient? _httpClient; + + [Before(HookType.Test)] + public void Setup() + { + _httpClient = new HttpClient(); + } + + public void Dispose() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task BeforeTest_No_Issue_When_Disposed_In_DisposeAsync() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + + public class DisposableFieldTests : IAsyncDisposable + { + private HttpClient? _httpClient; + + [Before(HookType.Test)] + public void Setup() + { + _httpClient = new HttpClient(); + } + + public ValueTask DisposeAsync() + { + _httpClient?.Dispose(); + return ValueTask.CompletedTask; + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // IASYNCINITIALIZER ADDITIONAL COMBINATIONS + // ======================================== + + [Test] + public async Task IAsyncInitializer_No_Issue_When_Disposed_In_Dispose() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + using TUnit.Core.Interfaces; + + public class DisposableFieldTests : IAsyncInitializer, IDisposable + { + private HttpClient? _httpClient; + + public Task InitializeAsync() + { + _httpClient = new HttpClient(); + return Task.CompletedTask; + } + + public void Dispose() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + [Test] + public async Task IAsyncInitializer_No_Issue_When_Disposed_In_After() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System; + using System.Net.Http; + using System.Threading.Tasks; + using TUnit.Core; + using TUnit.Core.Interfaces; + + public class DisposableFieldTests : IAsyncInitializer + { + private HttpClient? _httpClient; + + public Task InitializeAsync() + { + _httpClient = new HttpClient(); + return Task.CompletedTask; + } + + [After(HookType.Test)] + public void Cleanup() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // STATIC FIELD WITH BEFORE(ASSEMBLY) TESTS + // ======================================== + + [Test] + public async Task BeforeAssembly_Static_Flags_Issue() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private static HttpClient? {|#0:_httpClient|}; + + [Before(HookType.Assembly)] + public static void Setup() + { + _httpClient = new HttpClient(); + } + + [Test] + public void Test1() + { + } + } + """, + + Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup) + .WithLocation(0) + .WithArguments("_httpClient") + ); + } + + [Test] + public async Task BeforeAssembly_Static_No_Issue_When_Disposed_In_AfterAssembly() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private static HttpClient? _httpClient; + + [Before(HookType.Assembly)] + public static void Setup() + { + _httpClient = new HttpClient(); + } + + [After(HookType.Assembly)] + public static void Cleanup() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } + + // ======================================== + // STATIC FIELD WITH BEFORE(TESTSESSION) TESTS + // ======================================== + + [Test] + public async Task BeforeTestSession_Static_Flags_Issue() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private static HttpClient? {|#0:_httpClient|}; + + [Before(HookType.TestSession)] + public static void Setup() + { + _httpClient = new HttpClient(); + } + + [Test] + public void Test1() + { + } + } + """, + + Verifier.Diagnostic(Rules.Dispose_Member_In_Cleanup) + .WithLocation(0) + .WithArguments("_httpClient") + ); + } + + [Test] + public async Task BeforeTestSession_Static_No_Issue_When_Disposed_In_AfterTestSession() + { + await Verifier + .VerifyAnalyzerAsync( + """ + using System.Net.Http; + using TUnit.Core; + + public class DisposableFieldTests + { + private static HttpClient? _httpClient; + + [Before(HookType.TestSession)] + public static void Setup() + { + _httpClient = new HttpClient(); + } + + [After(HookType.TestSession)] + public static void Cleanup() + { + _httpClient?.Dispose(); + } + + [Test] + public void Test1() + { + } + } + """ + ); + } } diff --git a/TUnit.Analyzers.Tests/TUnit.Analyzers.Tests.csproj b/TUnit.Analyzers.Tests/TUnit.Analyzers.Tests.csproj index 4118449776..dabf679d09 100644 --- a/TUnit.Analyzers.Tests/TUnit.Analyzers.Tests.csproj +++ b/TUnit.Analyzers.Tests/TUnit.Analyzers.Tests.csproj @@ -22,20 +22,20 @@ - - + + - - + + - - + + diff --git a/TUnit.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier.cs b/TUnit.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier.cs index b1268538d6..296fc46c1c 100644 --- a/TUnit.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier.cs +++ b/TUnit.Analyzers.Tests/Verifiers/CSharpAnalyzerVerifier.cs @@ -1,3 +1,4 @@ +using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; @@ -42,7 +43,11 @@ public Test() } compilationOptions = compilationOptions - .WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings)); + .WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions + .SetItems(CSharpVerifierHelper.NullableWarnings) + // Suppress analyzer release tracking warnings - we're testing TUnit analyzers, not release tracking + .SetItem("RS2007", ReportDiagnostic.Suppress) + .SetItem("RS2008", ReportDiagnostic.Suppress)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions) .WithProjectParseOptions(projectId, parseOptions diff --git a/TUnit.Analyzers.Tests/Verifiers/CSharpCodeFixVerifier.cs b/TUnit.Analyzers.Tests/Verifiers/CSharpCodeFixVerifier.cs index 79656d8ff4..3683793e41 100644 --- a/TUnit.Analyzers.Tests/Verifiers/CSharpCodeFixVerifier.cs +++ b/TUnit.Analyzers.Tests/Verifiers/CSharpCodeFixVerifier.cs @@ -1,3 +1,5 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; @@ -35,7 +37,12 @@ public Test() return solution; } - compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings)); + compilationOptions = compilationOptions + .WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions + .SetItems(CSharpVerifierHelper.NullableWarnings) + // Suppress analyzer release tracking warnings - we're testing TUnit analyzers, not release tracking + .SetItem("RS2007", ReportDiagnostic.Suppress) + .SetItem("RS2008", ReportDiagnostic.Suppress)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions) .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)); diff --git a/TUnit.Analyzers.Tests/Verifiers/CSharpCodeRefactoringVerifier.cs b/TUnit.Analyzers.Tests/Verifiers/CSharpCodeRefactoringVerifier.cs index 017501bcdf..18db324888 100644 --- a/TUnit.Analyzers.Tests/Verifiers/CSharpCodeRefactoringVerifier.cs +++ b/TUnit.Analyzers.Tests/Verifiers/CSharpCodeRefactoringVerifier.cs @@ -1,3 +1,4 @@ +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Testing; @@ -33,7 +34,12 @@ public Test() return solution; } - compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings)); + compilationOptions = compilationOptions + .WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions + .SetItems(CSharpVerifierHelper.NullableWarnings) + // Suppress analyzer release tracking warnings - we're testing TUnit analyzers, not release tracking + .SetItem("RS2007", ReportDiagnostic.Suppress) + .SetItem("RS2008", ReportDiagnostic.Suppress)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions) .WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.Preview)); diff --git a/TUnit.Analyzers/AbstractTestClassWithDataSourcesAnalyzer.cs b/TUnit.Analyzers/AbstractTestClassWithDataSourcesAnalyzer.cs index 66727629db..6e8c53893f 100644 --- a/TUnit.Analyzers/AbstractTestClassWithDataSourcesAnalyzer.cs +++ b/TUnit.Analyzers/AbstractTestClassWithDataSourcesAnalyzer.cs @@ -99,8 +99,8 @@ private void AnalyzeSymbol(SymbolAnalysisContext context) private static bool HasConcreteInheritingClassesWithInheritsTests(SymbolAnalysisContext context, INamedTypeSymbol abstractClass) { - // Get all named types in the compilation - var allTypes = GetAllNamedTypes(context.Compilation.Assembly.GlobalNamespace); + // Get all named types in the compilation (including referenced assemblies) + var allTypes = GetAllNamedTypes(context.Compilation.GlobalNamespace); // Check if any concrete class inherits from the abstract class and has [InheritsTests] foreach (var type in allTypes) diff --git a/TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs b/TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs index 77900e6c58..151d20de8c 100644 --- a/TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs +++ b/TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs @@ -46,6 +46,16 @@ private static void CheckMethods(SyntaxNodeAnalysisContext context, IMethodSymbo var methodSymbols = methods.Where(x => x.IsStatic == isStaticMethod).ToArray(); + // Check field initializers first + if (context.Node is ClassDeclarationSyntax classDeclarationSyntax) + { + var namedTypeSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax); + if (namedTypeSymbol != null) + { + CheckFieldInitializers(context, namedTypeSymbol, isStaticMethod, createdObjects); + } + } + foreach (var methodSymbol in methodSymbols) { CheckSetUps(context, methodSymbol, createdObjects); @@ -65,6 +75,87 @@ private static void CheckMethods(SyntaxNodeAnalysisContext context, IMethodSymbo } } + private static void CheckFieldInitializers(SyntaxNodeAnalysisContext context, INamedTypeSymbol namedTypeSymbol, bool isStatic, ConcurrentDictionary createdObjects) + { + // Directly traverse the class syntax to find field declarations + if (context.Node is not ClassDeclarationSyntax classDeclaration) + { + return; + } + + var members = classDeclaration.Members; + + foreach (var member in members) + { + // Handle field declarations: private HttpClient _client = new HttpClient(); + if (member is FieldDeclarationSyntax fieldDeclaration) + { + if (fieldDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)) != isStatic) + { + continue; + } + + foreach (var variable in fieldDeclaration.Declaration.Variables) + { + if (variable.Initializer == null) + { + continue; + } + + // Check if the initializer contains an object creation expression + var objectCreations = variable.Initializer.Value.DescendantNodesAndSelf() + .OfType(); + + foreach (var objectCreation in objectCreations) + { + var typeInfo = context.SemanticModel.GetTypeInfo(objectCreation); + if (typeInfo.Type?.IsDisposable() is true || typeInfo.Type?.IsAsyncDisposable() is true) + { + var fieldSymbol = context.SemanticModel.GetDeclaredSymbol(variable) as IFieldSymbol; + if (fieldSymbol != null) + { + createdObjects.TryAdd(fieldSymbol, HookLevel.Test); + break; // Only need to add once + } + } + } + } + } + + // Handle property declarations: public HttpClient Client { get; set; } = new HttpClient(); + if (member is PropertyDeclarationSyntax propertyDeclaration) + { + if (propertyDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)) != isStatic) + { + continue; + } + + if (propertyDeclaration.Initializer == null) + { + continue; + } + + // Check if the initializer contains an object creation expression + var objectCreations = propertyDeclaration.Initializer.Value.DescendantNodesAndSelf() + .OfType(); + + foreach (var objectCreation in objectCreations) + { + var typeInfo = context.SemanticModel.GetTypeInfo(objectCreation); + if (typeInfo.Type?.IsDisposable() is true || typeInfo.Type?.IsAsyncDisposable() is true) + { + var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration) as IPropertySymbol; + if (propertySymbol != null) + { + createdObjects.TryAdd(propertySymbol, HookLevel.Test); + break; // Only need to add once + } + } + } + } + } + } + private static void CheckSetUps(SyntaxNodeAnalysisContext context, IMethodSymbol methodSymbol, ConcurrentDictionary createdObjects) { var syntaxNodes = methodSymbol.DeclaringSyntaxReferences @@ -72,7 +163,20 @@ private static void CheckSetUps(SyntaxNodeAnalysisContext context, IMethodSymbol var isHookMethod = methodSymbol.IsHookMethod(context.Compilation, out _, out var level, out _); - if (!isHookMethod && methodSymbol.MethodKind != MethodKind.Constructor) + // Check for IAsyncInitializer.InitializeAsync() + var isInitializeAsyncMethod = false; + if (methodSymbol is { Name: "InitializeAsync", Parameters.IsDefaultOrEmpty: true }) + { + var asyncInitializer = context.Compilation.GetTypeByMetadataName("TUnit.Core.Interfaces.IAsyncInitializer"); + if (asyncInitializer != null && methodSymbol.ContainingType.Interfaces.Any(x => + SymbolEqualityComparer.Default.Equals(x, asyncInitializer))) + { + isInitializeAsyncMethod = true; + level = HookLevel.Test; + } + } + + if (!isHookMethod && methodSymbol.MethodKind != MethodKind.Constructor && !isInitializeAsyncMethod) { return; } diff --git a/TUnit.Assertions.Analyzers.Tests/AnalyzerTestHelpers.cs b/TUnit.Assertions.Analyzers.Tests/AnalyzerTestHelpers.cs new file mode 100644 index 0000000000..58efd18d48 --- /dev/null +++ b/TUnit.Assertions.Analyzers.Tests/AnalyzerTestHelpers.cs @@ -0,0 +1,186 @@ +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Testing; + +namespace TUnit.Assertions.Analyzers.Tests; + +public static class AnalyzerTestHelpers +{ + public static CSharpAnalyzerTest CreateAnalyzerTest( + [StringSyntax("c#-test")] string inputSource + ) + where TAnalyzer : DiagnosticAnalyzer, new() + { + var csTest = new CSharpAnalyzerTest + { + TestState = + { + Sources = { inputSource }, + ReferenceAssemblies = new ReferenceAssemblies( + "net8.0", + new PackageIdentity( + "Microsoft.NETCore.App.Ref", + "8.0.0"), + Path.Combine("ref", "net8.0")), + }, + }; + + csTest.TestState.AdditionalReferences + .AddRange( + [ + MetadataReference.CreateFromFile(typeof(TUnitAttribute).Assembly.Location), + MetadataReference.CreateFromFile(typeof(Assert).Assembly.Location), + ] + ); + + return csTest; + } + + public sealed class CSharpSuppressorTest : CSharpAnalyzerTest + where TSuppressor : DiagnosticSuppressor, new() + where TVerifier : IVerifier, new() + { + private readonly List _analyzers = []; + + protected override IEnumerable GetDiagnosticAnalyzers() + { + return base.GetDiagnosticAnalyzers().Concat(_analyzers); + } + + public CSharpSuppressorTest WithAnalyzer(bool enableDiagnostics = false) + where TAnalyzer : DiagnosticAnalyzer, new() + { + var analyzer = new TAnalyzer(); + _analyzers.Add(analyzer); + + if (enableDiagnostics) + { + var diagnosticOptions = analyzer.SupportedDiagnostics + .ToImmutableDictionary( + descriptor => descriptor.Id, + descriptor => descriptor.DefaultSeverity.ToReportDiagnostic() + ); + + SolutionTransforms.Clear(); + SolutionTransforms.Add(EnableDiagnostics(diagnosticOptions)); + } + + return this; + } + + public CSharpSuppressorTest WithSpecificDiagnostics( + params DiagnosticResult[] diagnostics + ) + { + var diagnosticOptions = diagnostics + .ToImmutableDictionary( + descriptor => descriptor.Id, + descriptor => descriptor.Severity.ToReportDiagnostic() + ); + + SolutionTransforms.Clear(); + SolutionTransforms.Add(EnableDiagnostics(diagnosticOptions)); + return this; + } + + private static Func EnableDiagnostics( + ImmutableDictionary diagnostics + ) => + (solution, id) => + { + var options = solution.GetProject(id)?.CompilationOptions + ?? throw new InvalidOperationException("Compilation options missing."); + + return solution + .WithProjectCompilationOptions( + id, + options + .WithSpecificDiagnosticOptions(diagnostics) + ); + }; + + public CSharpSuppressorTest WithExpectedDiagnosticsResults( + params DiagnosticResult[] diagnostics + ) + { + ExpectedDiagnostics.AddRange(diagnostics); + return this; + } + + public CSharpSuppressorTest WithCompilerDiagnostics( + CompilerDiagnostics diagnostics + ) + { + CompilerDiagnostics = diagnostics; + return this; + } + + public CSharpSuppressorTest IgnoringDiagnostics(params string[] diagnostics) + { + DisabledDiagnostics.AddRange(diagnostics); + return this; + } + } + + public static CSharpSuppressorTest CreateSuppressorTest( + [StringSyntax("c#-test")] string inputSource + ) + where TSuppressor : DiagnosticSuppressor, new() + { + var test = new CSharpSuppressorTest + { + TestCode = inputSource, + ReferenceAssemblies = GetReferenceAssemblies() + }; + + test.TestState.AdditionalReferences + .AddRange([ + MetadataReference.CreateFromFile(typeof(TUnitAttribute).Assembly.Location), + MetadataReference.CreateFromFile(typeof(Assert).Assembly.Location), + ]); + + return test; + } + + private static ReferenceAssemblies GetReferenceAssemblies() + { +#if NET472 + return ReferenceAssemblies.NetFramework.Net472.Default; +#elif NET8_0 + return ReferenceAssemblies.Net.Net80; +#elif NET9_0 + return ReferenceAssemblies.Net.Net90; +#elif NET10_0_OR_GREATER + return ReferenceAssemblies.Net.Net90; +#else + return ReferenceAssemblies.Net.Net80; // Default fallback +#endif + } + + public static CSharpSuppressorTest CreateSuppressorTest( + [StringSyntax("c#-test")] string inputSource + ) + where TSuppressor : DiagnosticSuppressor, new() + where TAnalyzer : DiagnosticAnalyzer, new() + { + return CreateSuppressorTest(inputSource) + .WithAnalyzer(enableDiagnostics: true); + } +} + +static file class DiagnosticSeverityExtensions +{ + public static ReportDiagnostic ToReportDiagnostic(this DiagnosticSeverity severity) + => severity switch + { + DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden, + DiagnosticSeverity.Info => ReportDiagnostic.Info, + DiagnosticSeverity.Warning => ReportDiagnostic.Warn, + DiagnosticSeverity.Error => ReportDiagnostic.Error, + _ => throw new InvalidEnumArgumentException(nameof(severity), (int) severity, typeof(DiagnosticSeverity)), + }; +} diff --git a/TUnit.Assertions.Analyzers.Tests/IsNotNullAssertionSuppressorTests.cs b/TUnit.Assertions.Analyzers.Tests/IsNotNullAssertionSuppressorTests.cs new file mode 100644 index 0000000000..28e196efff --- /dev/null +++ b/TUnit.Assertions.Analyzers.Tests/IsNotNullAssertionSuppressorTests.cs @@ -0,0 +1,425 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using TUnit.Core; + +namespace TUnit.Assertions.Analyzers.Tests; + +/// +/// Tests for the IsNotNullAssertionSuppressor which suppresses nullability warnings +/// (CS8600, CS8602, CS8604, CS8618) for variables after Assert.That(x).IsNotNull(). +/// +/// Note: These tests verify that the suppressor correctly identifies and suppresses +/// nullability warnings. The suppressor does not change null-state flow analysis, +/// only suppresses the resulting warnings. +/// +public class IsNotNullAssertionSuppressorTests +{ + private static readonly DiagnosticResult CS8602 = new("CS8602", DiagnosticSeverity.Warning); + private static readonly DiagnosticResult CS8604 = new("CS8604", DiagnosticSeverity.Warning); + + [Test] + public async Task Suppresses_CS8602_After_IsNotNull_Assertion() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + await Assert.That(nullableString).IsNotNull(); + + // This would normally produce CS8602: Dereference of a possibly null reference + // But the suppressor should suppress it after IsNotNull assertion + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_CS8604_After_IsNotNull_Assertion() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + await Assert.That(nullableString).IsNotNull(); + + // This would normally produce CS8604: Possible null reference argument + // But the suppressor should suppress it after IsNotNull assertion + AcceptsNonNull({|#0:nullableString|}); + } + + private void AcceptsNonNull(string nonNull) { } + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8604) + .WithExpectedDiagnosticsResults(CS8604.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Does_Not_Suppress_Without_IsNotNull_Assertion() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public void TestMethod() + { + string? nullableString = GetNullableString(); + + // No IsNotNull assertion here + + // This should still produce CS8602 warning + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(false)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_Multiple_Uses_After_IsNotNull() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + await Assert.That(nullableString).IsNotNull(); + + // Multiple uses should all be suppressed + var length = {|#0:nullableString|}.Length; + var upper = {|#1:nullableString|}.ToUpper(); + AcceptsNonNull({|#2:nullableString|}); + } + + private void AcceptsNonNull(string nonNull) { } + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults( + // Only the first usage generates a warning; subsequent uses benefit from flow analysis + CS8602.WithLocation(0).WithIsSuppressed(true) + ) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_Only_Asserted_Variable() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString1 = GetNullableString(); + string? nullableString2 = GetNullableString(); + + await Assert.That(nullableString1).IsNotNull(); + + // nullableString1 should be suppressed + var length1 = {|#0:nullableString1|}.Length; + + // nullableString2 should NOT be suppressed (not asserted) + var length2 = {|#1:nullableString2|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults( + CS8602.WithLocation(0).WithIsSuppressed(true), + CS8602.WithLocation(1).WithIsSuppressed(false) + ) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_Property_Access_Chain() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyClass + { + public string? Property { get; set; } + } + + public class MyTests + { + public async Task TestMethod() + { + MyClass? obj = GetNullableObject(); + + await Assert.That(obj).IsNotNull(); + + // This should be suppressed + var prop = {|#0:obj|}.Property; + } + + private MyClass? GetNullableObject() => new MyClass(); + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_After_IsNotNull_At_Start_Of_Assertion_Chain() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + // IsNotNull at the START of the chain + await Assert.That(nullableString).IsNotNull().And.Contains("test"); + + // After the assertion chain, should be suppressed + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_After_IsNotNull_At_End_Of_Assertion_Chain() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + // IsNotNull at the END of the chain + await Assert.That(nullableString).Contains("test").And.IsNotNull(); + + // After the assertion chain, should be suppressed + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_After_IsNotNull_In_Middle_Of_Assertion_Chain() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + // IsNotNull in the MIDDLE of the chain + await Assert.That(nullableString).Contains("t").And.IsNotNull().And.Contains("test"); + + // After the assertion chain, should be suppressed + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_After_IsNotNull_With_Or_Chain() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? nullableString = GetNullableString(); + + // IsNotNull with Or chain + await Assert.That(nullableString).IsNotNull().Or.IsEqualTo("fallback"); + + // After the assertion, should be suppressed + var length = {|#0:nullableString|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults(CS8602.WithLocation(0).WithIsSuppressed(true)) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } + + [Test] + public async Task Suppresses_Multiple_Variables_With_Chained_Assertions() + { + const string code = """ + #nullable enable + using System.Threading.Tasks; + using TUnit.Assertions; + using TUnit.Assertions.Extensions; + + public class MyTests + { + public async Task TestMethod() + { + string? str1 = GetNullableString(); + string? str2 = GetNullableString(); + + // Both variables asserted + await Assert.That(str1).IsNotNull().And.Contains("test"); + await Assert.That(str2).IsNotNull(); + + // Both should be suppressed + var length1 = {|#0:str1|}.Length; + var length2 = {|#1:str2|}.Length; + } + + private string? GetNullableString() => "test"; + } + """; + + await AnalyzerTestHelpers + .CreateSuppressorTest(code) + .IgnoringDiagnostics("CS1591") + .WithSpecificDiagnostics(CS8602) + .WithExpectedDiagnosticsResults( + CS8602.WithLocation(0).WithIsSuppressed(true), + CS8602.WithLocation(1).WithIsSuppressed(true) + ) + .WithCompilerDiagnostics(CompilerDiagnostics.Warnings) + .RunAsync(); + } +} diff --git a/TUnit.Assertions.Analyzers/IsNotNullAssertionSuppressor.cs b/TUnit.Assertions.Analyzers/IsNotNullAssertionSuppressor.cs new file mode 100644 index 0000000000..495afe2af2 --- /dev/null +++ b/TUnit.Assertions.Analyzers/IsNotNullAssertionSuppressor.cs @@ -0,0 +1,242 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace TUnit.Assertions.Analyzers; + +/// +/// Suppresses nullability warnings (CS8600, CS8602, CS8604, CS8618) for variables +/// after they have been asserted as non-null using Assert.That(x).IsNotNull(). +/// +/// Note: This suppressor only hides the warnings; it does not change the compiler's +/// null-state flow analysis. Variables will still appear as nullable in IntelliSense. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public class IsNotNullAssertionSuppressor : DiagnosticSuppressor +{ + public override void ReportSuppressions(SuppressionAnalysisContext context) + { + foreach (var diagnostic in context.ReportedDiagnostics) + { + // Only process nullability warnings + if (!IsNullabilityWarning(diagnostic.Id)) + { + continue; + } + + // Get the syntax tree and semantic model + if (diagnostic.Location.SourceTree is not { } sourceTree) + { + continue; + } + + var root = sourceTree.GetRoot(); + var diagnosticSpan = diagnostic.Location.SourceSpan; + var node = root.FindNode(diagnosticSpan); + + if (node is null) + { + continue; + } + + var semanticModel = context.GetSemanticModel(sourceTree); + + // Find the variable being referenced that caused the warning + var identifierName = GetIdentifierFromNode(node); + if (identifierName is null) + { + continue; + } + + // Check if this variable was previously asserted as non-null + if (WasAssertedNotNull(identifierName, semanticModel, context.CancellationToken)) + { + Suppress(context, diagnostic); + } + } + } + + private bool IsNullabilityWarning(string diagnosticId) + { + return diagnosticId is "CS8600" // Converting null literal or possible null value to non-nullable type + or "CS8602" // Dereference of a possibly null reference + or "CS8604" // Possible null reference argument + or "CS8618"; // Non-nullable field/property uninitialized + } + + private IdentifierNameSyntax? GetIdentifierFromNode(SyntaxNode node) + { + // The warning might be on the identifier itself or a parent node + return node switch + { + IdentifierNameSyntax identifier => identifier, + MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax identifier } => identifier, + ArgumentSyntax { Expression: IdentifierNameSyntax identifier } => identifier, + _ => node.DescendantNodesAndSelf().OfType().FirstOrDefault() + }; + } + + private bool WasAssertedNotNull( + IdentifierNameSyntax identifierName, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + var symbol = semanticModel.GetSymbolInfo(identifierName, cancellationToken).Symbol; + if (symbol is null) + { + return false; + } + + // Find the containing method/block + var containingMethod = identifierName.FirstAncestorOrSelf(); + if (containingMethod is null) + { + return false; + } + + // Look for Assert.That(variable).IsNotNull() patterns before this usage + var allStatements = containingMethod.DescendantNodes().OfType().ToList(); + var identifierStatement = identifierName.FirstAncestorOrSelf(); + + if (identifierStatement is null) + { + return false; + } + + var identifierStatementIndex = allStatements.IndexOf(identifierStatement); + if (identifierStatementIndex < 0) + { + return false; + } + + // Check all statements before the current one + for (int i = 0; i < identifierStatementIndex; i++) + { + var statement = allStatements[i]; + + // Look for await Assert.That(x).IsNotNull() pattern + if (IsNotNullAssertion(statement, symbol, semanticModel, cancellationToken)) + { + return true; + } + } + + return false; + } + + private bool IsNotNullAssertion( + StatementSyntax statement, + ISymbol targetSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + // Pattern: await Assert.That(variable).IsNotNull() + // or: await Assert.That(variable).Contains("test").And.IsNotNull() + // or: Assert.That(variable).IsNotNull().GetAwaiter().GetResult() + + var invocations = statement.DescendantNodes().OfType(); + + foreach (var invocation in invocations) + { + // Check if this is a call to IsNotNull() + if (invocation.Expression is not MemberAccessExpressionSyntax { Name.Identifier.Text: "IsNotNull" }) + { + continue; + } + + // Walk up the expression chain to find Assert.That() call + var assertThatCall = FindAssertThatInChain(invocation); + if (assertThatCall is null) + { + continue; + } + + // Get the argument to Assert.That() + if (assertThatCall.ArgumentList.Arguments.Count != 1) + { + continue; + } + + var argument = assertThatCall.ArgumentList.Arguments[0].Expression; + + // Get the symbol of the argument + var argumentSymbol = semanticModel.GetSymbolInfo(argument, cancellationToken).Symbol; + + // Check if it's the same symbol we're looking for + if (SymbolEqualityComparer.Default.Equals(argumentSymbol, targetSymbol)) + { + return true; + } + } + + return false; + } + + private InvocationExpressionSyntax? FindAssertThatInChain(InvocationExpressionSyntax invocation) + { + // Walk up the expression chain looking for Assert.That() + var current = invocation.Expression; + + while (current is not null) + { + if (current is InvocationExpressionSyntax invocationExpr) + { + // Check if this is Assert.That() + if (invocationExpr.Expression is MemberAccessExpressionSyntax + { + Name.Identifier.Text: "That", + Expression: IdentifierNameSyntax { Identifier.Text: "Assert" } + }) + { + return invocationExpr; + } + + // Continue walking up from this invocation + current = invocationExpr.Expression; + } + else if (current is MemberAccessExpressionSyntax memberAccess) + { + // Move to the expression being accessed + current = memberAccess.Expression; + } + else + { + break; + } + } + + return null; + } + + private void Suppress(SuppressionAnalysisContext context, Diagnostic diagnostic) + { + var suppression = SupportedSuppressions.FirstOrDefault(s => s.SuppressedDiagnosticId == diagnostic.Id); + + if (suppression is not null) + { + context.ReportSuppression( + Suppression.Create( + suppression, + diagnostic + ) + ); + } + } + + public override ImmutableArray SupportedSuppressions { get; } = + ImmutableArray.Create( + CreateDescriptor("CS8600"), + CreateDescriptor("CS8602"), + CreateDescriptor("CS8604"), + CreateDescriptor("CS8618") + ); + + private static SuppressionDescriptor CreateDescriptor(string id) + => new( + id: $"{id}Suppression", + suppressedDiagnosticId: id, + justification: $"Suppress {id} for variables asserted as non-null via Assert.That(x).IsNotNull()." + ); +} diff --git a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet10_0.verified.txt b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet10_0.verified.txt index 7433164a90..9049945a09 100644 --- a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet10_0.verified.txt +++ b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet10_0.verified.txt @@ -73,6 +73,80 @@ public sealed class Bool_IsFalse_Assertion : Assertion } } +/// +/// Generated assertion for IsTrue +/// +public sealed class NullableBool_IsTrue_Assertion : Assertion +{ + public NullableBool_IsTrue_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsTrue(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be true"; + } +} + +/// +/// Generated assertion for IsFalse +/// +public sealed class NullableBool_IsFalse_Assertion : Assertion +{ + public NullableBool_IsFalse_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsFalse(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be false"; + } +} + public static partial class BooleanAssertionExtensions { /// @@ -93,6 +167,24 @@ public static partial class BooleanAssertionExtensions return new Bool_IsFalse_Assertion(source.Context); } + /// + /// Generated extension method for IsTrue + /// + public static NullableBool_IsTrue_Assertion IsTrue(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsTrue()"); + return new NullableBool_IsTrue_Assertion(source.Context); + } + + /// + /// Generated extension method for IsFalse + /// + public static NullableBool_IsFalse_Assertion IsFalse(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsFalse()"); + return new NullableBool_IsFalse_Assertion(source.Context); + } + } ] \ No newline at end of file diff --git a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet8_0.verified.txt b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet8_0.verified.txt index 7433164a90..9049945a09 100644 --- a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet8_0.verified.txt +++ b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet8_0.verified.txt @@ -73,6 +73,80 @@ public sealed class Bool_IsFalse_Assertion : Assertion } } +/// +/// Generated assertion for IsTrue +/// +public sealed class NullableBool_IsTrue_Assertion : Assertion +{ + public NullableBool_IsTrue_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsTrue(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be true"; + } +} + +/// +/// Generated assertion for IsFalse +/// +public sealed class NullableBool_IsFalse_Assertion : Assertion +{ + public NullableBool_IsFalse_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsFalse(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be false"; + } +} + public static partial class BooleanAssertionExtensions { /// @@ -93,6 +167,24 @@ public static partial class BooleanAssertionExtensions return new Bool_IsFalse_Assertion(source.Context); } + /// + /// Generated extension method for IsTrue + /// + public static NullableBool_IsTrue_Assertion IsTrue(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsTrue()"); + return new NullableBool_IsTrue_Assertion(source.Context); + } + + /// + /// Generated extension method for IsFalse + /// + public static NullableBool_IsFalse_Assertion IsFalse(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsFalse()"); + return new NullableBool_IsFalse_Assertion(source.Context); + } + } ] \ No newline at end of file diff --git a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet9_0.verified.txt b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet9_0.verified.txt index 7433164a90..9049945a09 100644 --- a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet9_0.verified.txt +++ b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.DotNet9_0.verified.txt @@ -73,6 +73,80 @@ public sealed class Bool_IsFalse_Assertion : Assertion } } +/// +/// Generated assertion for IsTrue +/// +public sealed class NullableBool_IsTrue_Assertion : Assertion +{ + public NullableBool_IsTrue_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsTrue(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be true"; + } +} + +/// +/// Generated assertion for IsFalse +/// +public sealed class NullableBool_IsFalse_Assertion : Assertion +{ + public NullableBool_IsFalse_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsFalse(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be false"; + } +} + public static partial class BooleanAssertionExtensions { /// @@ -93,6 +167,24 @@ public static partial class BooleanAssertionExtensions return new Bool_IsFalse_Assertion(source.Context); } + /// + /// Generated extension method for IsTrue + /// + public static NullableBool_IsTrue_Assertion IsTrue(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsTrue()"); + return new NullableBool_IsTrue_Assertion(source.Context); + } + + /// + /// Generated extension method for IsFalse + /// + public static NullableBool_IsFalse_Assertion IsFalse(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsFalse()"); + return new NullableBool_IsFalse_Assertion(source.Context); + } + } ] \ No newline at end of file diff --git a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.Net4_7.verified.txt b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.Net4_7.verified.txt index 7433164a90..9049945a09 100644 --- a/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.Net4_7.verified.txt +++ b/TUnit.Assertions.SourceGenerator.Tests/BooleanAssertionGeneratorTests.GeneratesBooleanAssertions.Net4_7.verified.txt @@ -73,6 +73,80 @@ public sealed class Bool_IsFalse_Assertion : Assertion } } +/// +/// Generated assertion for IsTrue +/// +public sealed class NullableBool_IsTrue_Assertion : Assertion +{ + public NullableBool_IsTrue_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsTrue(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be true"; + } +} + +/// +/// Generated assertion for IsFalse +/// +public sealed class NullableBool_IsFalse_Assertion : Assertion +{ + public NullableBool_IsFalse_Assertion(AssertionContext context) + : base(context) + { + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().FullName}")); + } + + if (value is null) + { + return Task.FromResult(AssertionResult.Failed("Actual value is null")); + } + + var result = value.IsFalse(); + return Task.FromResult(result + ? AssertionResult.Passed + : AssertionResult.Failed($"found {value}")); + } + + protected override string GetExpectation() + { + return "to be false"; + } +} + public static partial class BooleanAssertionExtensions { /// @@ -93,6 +167,24 @@ public static partial class BooleanAssertionExtensions return new Bool_IsFalse_Assertion(source.Context); } + /// + /// Generated extension method for IsTrue + /// + public static NullableBool_IsTrue_Assertion IsTrue(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsTrue()"); + return new NullableBool_IsTrue_Assertion(source.Context); + } + + /// + /// Generated extension method for IsFalse + /// + public static NullableBool_IsFalse_Assertion IsFalse(this IAssertionSource source) + { + source.Context.ExpressionBuilder.Append(".IsFalse()"); + return new NullableBool_IsFalse_Assertion(source.Context); + } + } ] \ No newline at end of file diff --git a/TUnit.Assertions.SourceGenerator/Generators/AssertionMethodGenerator.cs b/TUnit.Assertions.SourceGenerator/Generators/AssertionMethodGenerator.cs index 1120d2c753..116e99f278 100644 --- a/TUnit.Assertions.SourceGenerator/Generators/AssertionMethodGenerator.cs +++ b/TUnit.Assertions.SourceGenerator/Generators/AssertionMethodGenerator.cs @@ -12,15 +12,7 @@ public sealed class AssertionMethodGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { - // Handle non-generic CreateAssertionAttribute (deprecated) - var nonGenericCreateAttributeData = context.SyntaxProvider - .ForAttributeWithMetadataName( - "TUnit.Assertions.Attributes.CreateAssertionAttribute", - predicate: (node, _) => true, - transform: (ctx, _) => GetCreateAssertionAttributeData(ctx)) - .Where(x => x != null); - - // Handle non-generic AssertionFromAttribute (new) + // Handle non-generic AssertionFromAttribute var nonGenericAssertionFromData = context.SyntaxProvider .ForAttributeWithMetadataName( "TUnit.Assertions.Attributes.AssertionFromAttribute", @@ -28,15 +20,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) transform: (ctx, _) => GetCreateAssertionAttributeData(ctx)) .Where(x => x != null); - // Handle generic CreateAssertionAttribute (deprecated) - var genericCreateAttributeData = context.SyntaxProvider - .CreateSyntaxProvider( - predicate: (node, _) => node is ClassDeclarationSyntax, - transform: (ctx, _) => GetGenericCreateAssertionAttributeData(ctx, "CreateAssertionAttribute")) - .Where(x => x != null) - .SelectMany((x, _) => x!.ToImmutableArray()); - - // Handle generic AssertionFromAttribute (new) + // Handle generic AssertionFromAttribute var genericAssertionFromData = context.SyntaxProvider .CreateSyntaxProvider( predicate: (node, _) => node is ClassDeclarationSyntax, @@ -45,16 +29,12 @@ public void Initialize(IncrementalGeneratorInitializationContext context) .SelectMany((x, _) => x!.ToImmutableArray()); // Combine all sources - var allAttributeData = nonGenericCreateAttributeData.Collect() - .Combine(nonGenericAssertionFromData.Collect()) - .Combine(genericCreateAttributeData.Collect()) + var allAttributeData = nonGenericAssertionFromData.Collect() .Combine(genericAssertionFromData.Collect()) .Select((data, _) => { var result = new List(); - result.AddRange(data.Left.Left.Left.Where(x => x != null).SelectMany(x => x!)); - result.AddRange(data.Left.Left.Right.Where(x => x != null).SelectMany(x => x!)); - result.AddRange(data.Left.Right); + result.AddRange(data.Left.Where(x => x != null).SelectMany(x => x!)); result.AddRange(data.Right); return result.AsEnumerable(); }); @@ -95,6 +75,10 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { continue; } + + // Track if this is an unbound generic type for special handling + var isUnboundGeneric = containingType.IsUnboundGenericType; + string? customName = null; if (attributeData.NamedArguments.Any(na => na.Key == "CustomName")) { @@ -143,7 +127,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) negateLogic, requiresGenericTypeParameter, treatAsInstance, - expectationMessage + expectationMessage, + isUnboundGeneric ); attributeDataList.Add(new AttributeWithClassData(classSymbol, createAssertionAttributeData)); @@ -219,6 +204,9 @@ public void Initialize(IncrementalGeneratorInitializationContext context) continue; } + // Track if this is an unbound generic type for special handling + var isUnboundGeneric = containingType.IsUnboundGenericType; + string? customName = null; bool negateLogic = false; bool requiresGenericTypeParameter = false; @@ -255,7 +243,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) negateLogic, requiresGenericTypeParameter, treatAsInstance, - expectationMessage + expectationMessage, + isUnboundGeneric ); attributeDataList.Add(new AttributeWithClassData(classSymbol, createAssertionAttributeData)); @@ -380,8 +369,33 @@ private static void GenerateAssertionsForSpecificClass(SourceProductionContext c { var attributeData = attributeWithClassData.AttributeData; + // For unbound generic types, we need to temporarily construct them for member lookup + var typeForMemberLookup = attributeData.ContainingType; + if (attributeData.IsUnboundGeneric && typeForMemberLookup.IsUnboundGenericType) + { + // Get System.Object by searching through the type's containing assembly references + INamedTypeSymbol? objectType = null; + + // Look through the referenced assemblies to find System.Object + foreach (var refAssembly in typeForMemberLookup.ContainingAssembly.Modules.FirstOrDefault()?.ReferencedAssemblySymbols ?? Enumerable.Empty()) + { + var systemNs = refAssembly.GlobalNamespace.GetNamespaceMembers().FirstOrDefault(ns => ns.Name == "System"); + if (systemNs != null) + { + objectType = systemNs.GetTypeMembers("Object").FirstOrDefault(); + if (objectType != null) break; + } + } + + if (objectType != null) + { + var typeArgs = Enumerable.Repeat(objectType, typeForMemberLookup.TypeParameters.Length).ToArray(); + typeForMemberLookup = typeForMemberLookup.Construct(typeArgs); + } + } + // First try to find methods - var methodMembers = attributeData.ContainingType.GetMembers(attributeData.MethodName) + var methodMembers = typeForMemberLookup.GetMembers(attributeData.MethodName) .OfType() .Where(m => IsValidReturnType(m.ReturnType, out _) && (attributeData.TreatAsInstance ? @@ -405,10 +419,10 @@ private static void GenerateAssertionsForSpecificClass(SourceProductionContext c var propertyMembers = new List(); if (!methodMembers.Any()) { - propertyMembers = attributeData.ContainingType.GetMembers(attributeData.MethodName) + propertyMembers = typeForMemberLookup.GetMembers(attributeData.MethodName) .OfType() .Where(p => p.Type.SpecialType == SpecialType.System_Boolean && - p is { GetMethod: not null, IsStatic: false } && SymbolEqualityComparer.Default.Equals(p.ContainingType, attributeData.TargetType)) + p is { GetMethod: not null, IsStatic: false }) .ToList(); } @@ -425,15 +439,20 @@ private static void GenerateAssertionsForSpecificClass(SourceProductionContext c if (!matchingMethods.Any()) { - context.ReportDiagnostic(Diagnostic.Create( - new DiagnosticDescriptor( - "TU0001", - "Method not found", - $"No boolean method '{attributeData.MethodName}' found on type '{attributeData.ContainingType.ToDisplayString()}'", - "TUnit.Assertions", - DiagnosticSeverity.Error, - true), - Location.None)); + // For unbound generic types, we'll generate generic methods even if we can't find the property now + // The property will exist on the constructed type at runtime + if (!attributeData.IsUnboundGeneric) + { + context.ReportDiagnostic(Diagnostic.Create( + new DiagnosticDescriptor( + "TU0001", + "Method not found", + $"No boolean method '{attributeData.MethodName}' found on type '{attributeData.ContainingType.ToDisplayString()}'", + "TUnit.Assertions", + DiagnosticSeverity.Error, + true), + Location.None)); + } continue; } @@ -577,6 +596,21 @@ private static void GenerateAssertConditionClassForMethod(SourceProductionContex sourceBuilder.AppendLine($"public class {className} : Assertion"); sourceBuilder.AppendLine($" where TTask : {targetTypeName}"); } + else if (attributeData.IsUnboundGeneric) + { + // For unbound generic types like Memory, generate generic assertion class + // Generate type parameter names: T, T1, T2, etc. + var typeParamCount = attributeData.TargetType.TypeParameters.Length; + var typeParamNames = typeParamCount == 1 ? new[] { "T" } : + Enumerable.Range(1, typeParamCount).Select(i => $"T{i}").ToArray(); + var typeParamsList = string.Join(", ", typeParamNames); + + // Generate assertion class with generic parameters + // Example: public class MemoryIsEmptyAssertion : Assertion> + var unboundTypeName = attributeData.TargetType.Name; // e.g., "Memory" + var constructedTargetType = $"{unboundTypeName}<{typeParamsList}>"; // e.g., "Memory" + sourceBuilder.AppendLine($"public class {className}<{typeParamsList}> : Assertion<{constructedTargetType}>"); + } else if (hasMethodTypeParameters) { // Generate generic assertion class with the method's type parameters @@ -1082,6 +1116,19 @@ private static void GenerateMethod(StringBuilder sourceBuilder, string targetTyp // For Task, generate a generic method that works with Task and Task sourceBuilder.Append($" public static {assertConditionClassName} {generatedMethodName}(this IAssertionSource source"); } + else if (attributeData.IsUnboundGeneric) + { + // For unbound generic types like Memory, generate generic extension method + var typeParamCount = attributeData.TargetType.TypeParameters.Length; + var typeParamNames = typeParamCount == 1 ? new[] { "T" } : + Enumerable.Range(1, typeParamCount).Select(i => $"T{i}").ToArray(); + var typeParamsList = string.Join(", ", typeParamNames); + + var unboundTypeName = attributeData.TargetType.Name; + var constructedTargetType = $"{unboundTypeName}<{typeParamsList}>"; + // Example: public static MemoryIsEmptyAssertion IsEmpty(this IAssertionSource> source + sourceBuilder.Append($" public static {assertConditionClassName}<{typeParamsList}> {generatedMethodName}<{typeParamsList}>(this IAssertionSource<{constructedTargetType}> source"); + } else if (hasMethodTypeParameters) { // Method has generic type parameters - include them in the extension method @@ -1181,6 +1228,7 @@ private record CreateAssertionAttributeData( bool NegateLogic, bool RequiresGenericTypeParameter, bool TreatAsInstance, - string? ExpectationMessage + string? ExpectationMessage, + bool IsUnboundGeneric ); } diff --git a/TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs b/TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs index d32840697b..47796a2da8 100644 --- a/TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs +++ b/TUnit.Assertions.SourceGenerator/Generators/MethodAssertionGenerator.cs @@ -18,53 +18,105 @@ namespace TUnit.Assertions.SourceGenerator.Generators; [Generator] public sealed class MethodAssertionGenerator : IIncrementalGenerator { + private static readonly DiagnosticDescriptor MethodMustBeStaticRule = new DiagnosticDescriptor( + id: "TUNITGEN001", + title: "Method must be static", + messageFormat: "Method '{0}' decorated with [GenerateAssertion] must be static", + category: "TUnit.Assertions.SourceGenerator", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods decorated with [GenerateAssertion] must be static to be used in generated assertions."); + + private static readonly DiagnosticDescriptor MethodMustHaveParametersRule = new DiagnosticDescriptor( + id: "TUNITGEN002", + title: "Method must have at least one parameter", + messageFormat: "Method '{0}' decorated with [GenerateAssertion] must have at least one parameter (the value to assert)", + category: "TUnit.Assertions.SourceGenerator", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods decorated with [GenerateAssertion] must have at least one parameter representing the value being asserted."); + + private static readonly DiagnosticDescriptor UnsupportedReturnTypeRule = new DiagnosticDescriptor( + id: "TUNITGEN003", + title: "Unsupported return type", + messageFormat: "Method '{0}' decorated with [GenerateAssertion] has unsupported return type '{1}'. Supported types are: bool, AssertionResult, Task, Task", + category: "TUnit.Assertions.SourceGenerator", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods decorated with [GenerateAssertion] must return bool, AssertionResult, Task, or Task."); + public void Initialize(IncrementalGeneratorInitializationContext context) { // Find all methods decorated with [GenerateAssertion] - var assertionMethods = context.SyntaxProvider + var assertionMethodsOrDiagnostics = context.SyntaxProvider .ForAttributeWithMetadataName( "TUnit.Assertions.Attributes.GenerateAssertionAttribute", predicate: static (node, _) => node is MethodDeclarationSyntax, - transform: static (ctx, ct) => GetAssertionMethodData(ctx, ct)) - .Where(static x => x != null) - .Select(static (x, _) => x!); + transform: (ctx, ct) => GetAssertionMethodData(ctx, ct)); + + // Split into methods and diagnostics + var methods = assertionMethodsOrDiagnostics + .Where(x => x.Data != null) + .Select((x, _) => x.Data!); + + var diagnostics = assertionMethodsOrDiagnostics + .Where(x => x.Diagnostic != null) + .Select((x, _) => x.Diagnostic!); + + // Report diagnostics + context.RegisterSourceOutput(diagnostics, static (context, diagnostic) => + { + context.ReportDiagnostic(diagnostic); + }); // Generate assertion classes and extension methods - context.RegisterSourceOutput(assertionMethods.Collect(), static (context, methods) => + context.RegisterSourceOutput(methods.Collect(), static (context, methods) => { GenerateAssertions(context, methods); }); } - private static AssertionMethodData? GetAssertionMethodData( + private static (AssertionMethodData? Data, Diagnostic? Diagnostic) GetAssertionMethodData( GeneratorAttributeSyntaxContext context, CancellationToken cancellationToken) { if (context.TargetSymbol is not IMethodSymbol methodSymbol) { - return null; + return (null, null); } + var location = context.TargetNode.GetLocation(); + // Validate method is static if (!methodSymbol.IsStatic) { - // TODO: Report diagnostic - method must be static - return null; + var diagnostic = Diagnostic.Create( + MethodMustBeStaticRule, + location, + methodSymbol.Name); + return (null, diagnostic); } // Validate method has at least one parameter if (methodSymbol.Parameters.Length == 0) { - // TODO: Report diagnostic - method must have at least one parameter - return null; + var diagnostic = Diagnostic.Create( + MethodMustHaveParametersRule, + location, + methodSymbol.Name); + return (null, diagnostic); } // Get return type info var returnTypeInfo = AnalyzeReturnType(methodSymbol.ReturnType); if (returnTypeInfo == null) { - // TODO: Report diagnostic - unsupported return type - return null; + var diagnostic = Diagnostic.Create( + UnsupportedReturnTypeRule, + location, + methodSymbol.Name, + methodSymbol.ReturnType.ToDisplayString()); + return (null, diagnostic); } // First parameter is the target type (what becomes IAssertionSource) @@ -90,7 +142,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) } } - return new AssertionMethodData( + var data = new AssertionMethodData( methodSymbol, targetType, additionalParameters, @@ -98,6 +150,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) isExtensionMethod, customExpectation ); + + return (data, null); } private static ReturnTypeInfo? AnalyzeReturnType(ITypeSymbol returnType) @@ -405,9 +459,10 @@ private static string BuildMethodCallExpression(AssertionMethodData data) if (data.IsExtensionMethod) { - // Extension method syntax: value.MethodName(params) + // Extension method syntax: value!.MethodName(params) + // Use null-forgiving operator since we've already checked for null above var paramList = string.Join(", ", data.AdditionalParameters.Select(p => $"_{p.Name}")); - return $"value.{methodName}{typeArguments}({paramList})"; + return $"value!.{methodName}{typeArguments}({paramList})"; } else { @@ -448,14 +503,18 @@ private static void GenerateExtensionMethod(StringBuilder sb, AssertionMethodDat // Additional parameters foreach (var param in data.AdditionalParameters) { - sb.Append($", {param.Type.ToDisplayString()} {param.Name}"); + var paramsModifier = param.IsParams ? "params " : ""; + sb.Append($", {paramsModifier}{param.Type.ToDisplayString()} {param.Name}"); } - // CallerArgumentExpression parameters + // CallerArgumentExpression parameters (skip for params since params must be last) for (int i = 0; i < data.AdditionalParameters.Length; i++) { var param = data.AdditionalParameters[i]; - sb.Append($", [CallerArgumentExpression(nameof({param.Name}))] string? {param.Name}Expression = null"); + if (!param.IsParams) + { + sb.Append($", [CallerArgumentExpression(nameof({param.Name}))] string? {param.Name}Expression = null"); + } } sb.AppendLine(")"); @@ -474,7 +533,9 @@ private static void GenerateExtensionMethod(StringBuilder sb, AssertionMethodDat // Build expression string if (data.AdditionalParameters.Length > 0) { - var exprList = string.Join(", ", data.AdditionalParameters.Select(p => $"{{{p.Name}Expression}}")); + // For params parameters, use parameter name directly (no Expression suffix since we didn't generate it) + var exprList = string.Join(", ", data.AdditionalParameters.Select(p => + p.IsParams ? $"{{{p.Name}}}" : $"{{{p.Name}Expression}}")); sb.AppendLine($" source.Context.ExpressionBuilder.Append($\".{methodName}({exprList})\");"); } else diff --git a/TUnit.Assertions.Tests/AssertNotNullTests.cs b/TUnit.Assertions.Tests/AssertNotNullTests.cs new file mode 100644 index 0000000000..537ab1f2aa --- /dev/null +++ b/TUnit.Assertions.Tests/AssertNotNullTests.cs @@ -0,0 +1,149 @@ +#nullable enable +using TUnit.Assertions.Exceptions; +using TUnit.Core; + +namespace TUnit.Assertions.Tests; + +/// +/// Tests for Assert.NotNull() and Assert.Null() methods. +/// These methods properly update null-state flow analysis via [NotNull] attribute. +/// +public class AssertNotNullTests +{ + [Test] + public async Task NotNull_WithNonNullReferenceType_DoesNotThrow() + { + string? value = "test"; + + Assert.NotNull(value); + + // After NotNull, the compiler should know value is non-null + // This should compile without warnings + var length = value.Length; + + await Assert.That(length).IsEqualTo(4); + } + + [Test] + public async Task NotNull_WithNullReferenceType_Throws() + { + string? value = null; + + var exception = Assert.Throws(() => Assert.NotNull(value)); + + await Assert.That(exception.Message).Contains("to not be null"); + } + + [Test] + public async Task NotNull_WithNonNullableValueType_DoesNotThrow() + { + int? value = 42; + + Assert.NotNull(value); + + // After NotNull, the compiler should know value has a value + var intValue = value.Value; + + await Assert.That(intValue).IsEqualTo(42); + } + + [Test] + public async Task NotNull_WithNullableValueType_Throws() + { + int? value = null; + + var exception = Assert.Throws(() => Assert.NotNull(value)); + + await Assert.That(exception.Message).Contains("to not be null"); + } + + [Test] + public void Null_WithNullReferenceType_DoesNotThrow() + { + string? value = null; + + Assert.Null(value); + + // Test passes if no exception thrown + } + + [Test] + public async Task Null_WithNonNullReferenceType_Throws() + { + string? value = "test"; + + var exception = Assert.Throws(() => Assert.Null(value)); + + await Assert.That(exception.Message).Contains("to be null"); + } + + [Test] + public void Null_WithNullValueType_DoesNotThrow() + { + int? value = null; + + Assert.Null(value); + + // Test passes if no exception thrown + } + + [Test] + public async Task Null_WithNonNullValueType_Throws() + { + int? value = 42; + + var exception = Assert.Throws(() => Assert.Null(value)); + + await Assert.That(exception.Message).Contains("to be null"); + } + + [Test] + public async Task NotNull_CapturesExpressionInMessage() + { + string? myVariable = null; + + var exception = Assert.Throws(() => Assert.NotNull(myVariable)); + + await Assert.That(exception.Message).Contains("myVariable"); + } + + [Test] + public async Task Null_CapturesExpressionInMessage() + { + string myVariable = "not null"; + + var exception = Assert.Throws(() => Assert.Null(myVariable)); + + await Assert.That(exception.Message).Contains("myVariable"); + } + + [Test] + public async Task NotNull_AllowsChainingWithOtherAssertions() + { + string? value = "test"; + + Assert.NotNull(value); + + // Can use the value directly without null-forgiving operator + await Assert.That(value.ToUpper()).IsEqualTo("TEST"); + await Assert.That(value.Length).IsEqualTo(4); + } + + [Test] + public async Task NotNull_WithComplexObject_UpdatesNullState() + { + var obj = new TestClass { Name = "test" }; + TestClass? nullableObj = obj; + + Assert.NotNull(nullableObj); + + // Should be able to access properties without warnings + var name = nullableObj.Name; + await Assert.That(name).IsEqualTo("test"); + } + + private class TestClass + { + public string? Name { get; set; } + } +} diff --git a/TUnit.Assertions.Tests/Bugs/Issue3580Tests.cs b/TUnit.Assertions.Tests/Bugs/Issue3580Tests.cs new file mode 100644 index 0000000000..69238daf1b --- /dev/null +++ b/TUnit.Assertions.Tests/Bugs/Issue3580Tests.cs @@ -0,0 +1,122 @@ +namespace TUnit.Assertions.Tests.Bugs; + +/// +/// Tests for issue #3580: More warnings CS8620 and CS8619 after update to >= 0.72 +/// https://github.com/thomhurst/TUnit/issues/3580 +/// +public class Issue3580Tests +{ + [Test] + public async Task Task_FromResult_With_NonNullable_Value_And_Nullable_Expected_Should_Not_Cause_Warnings() + { + // Scenario 1: Both parameters nullable (from issue) + object? value = "test"; + object? expected = "test"; + + // This should not produce CS8620 or CS8619 warnings + await Assert.That(Task.FromResult(value)).IsEqualTo(expected); + } + + [Test] + public async Task Task_FromResult_With_NonNullable_Value_And_NonNullable_Expected_Should_Not_Cause_Warnings() + { + // Scenario 2: Non-nullable value with nullable expectation (from issue) + object value = "test"; + object? expected = "test"; + + // This should not produce CS8620 or CS8619 warnings + await Assert.That(Task.FromResult(value)).IsEqualTo(expected); + } + + [Test] + public async Task Task_FromResult_With_Both_NonNullable_Should_Not_Cause_Warnings() + { + // Scenario 3: Both non-nullable (from issue) + object value = "test"; + object expected = "test"; + + // This should not produce CS8619 warnings + await Assert.That(Task.FromResult(value)).IsEqualTo(expected); + } + + [Test] + public async Task Task_FromResult_With_String_Should_Not_Cause_Warnings() + { + // Test with string type (reference type) + var value = "hello"; + var expected = "hello"; + + await Assert.That(Task.FromResult(value)).IsEqualTo(expected); + } + + [Test] + public async Task Task_FromResult_With_ValueType_Should_Not_Cause_Warnings() + { + // Test with value type (int) + var value = 42; + var expected = 42; + + await Assert.That(Task.FromResult(value)).IsEqualTo(expected); + } + + [Test] + public async Task Task_FromResult_With_Null_Value_Should_Work() + { + // Test with null value + object? value = null; + + var result = await Task.FromResult(value); + await Assert.That(result).IsNull(); + } + + [Test] + public async Task Task_FromResult_With_Custom_Type_Should_Not_Cause_Warnings() + { + // Test with custom type + var value = new TestData { Value = "test" }; + var expected = value; + + var result = await Task.FromResult(value); + await Assert.That(result).IsSameReferenceAs(expected); + } + + [Test] + public async Task Async_Method_Returning_NonNullable_Task_Should_Not_Cause_Warnings() + { + // Test with async method that returns non-nullable task + // Just verify we can await it and get a non-null result + var result = await GetNonNullableValueAsync(); + + await Assert.That(result).IsNotNull(); + } + + [Test] + public async Task Task_FromResult_With_IsNotNull_Should_Not_Cause_Warnings() + { + // Test IsNotNull assertion + object value = "test"; + + var result = await Task.FromResult(value); + await Assert.That(result).IsNotNull(); + } + + [Test] + public async Task Task_FromResult_With_IsGreaterThan_Should_Not_Cause_Warnings() + { + // Test numeric comparison + var value = 10; + + await Assert.That(Task.FromResult(value)).IsGreaterThan(5); + } + + private static async Task GetNonNullableValueAsync() + { + await Task.Yield(); + return new object(); + } + + private class TestData + { + public string Value { get; set; } = string.Empty; + } +} diff --git a/TUnit.Assertions.Tests/Old/EqualsAssertionTests.cs b/TUnit.Assertions.Tests/Old/EqualsAssertionTests.cs index 01cb5f75cc..0a9c64d653 100644 --- a/TUnit.Assertions.Tests/Old/EqualsAssertionTests.cs +++ b/TUnit.Assertions.Tests/Old/EqualsAssertionTests.cs @@ -11,7 +11,7 @@ await TUnitAssert.That(async () => await TUnitAssert.That(one).IsEqualTo("2", StringComparison.Ordinal).And.IsNotEqualTo("1").And.IsOfType(typeof(string)) ).ThrowsException() .And - .HasMessageContaining("Assert.That(one).IsEqualTo(\"2\", Ordinal)"); + .HasMessageContaining("Assert.That(one).IsEqualTo(\"2\", StringComparison.Ordinal)"); } [Test] diff --git a/TUnit.Assertions.Tests/RegexAPITests.cs b/TUnit.Assertions.Tests/RegexAPITests.cs new file mode 100644 index 0000000000..a213cc0db2 --- /dev/null +++ b/TUnit.Assertions.Tests/RegexAPITests.cs @@ -0,0 +1,72 @@ +using TUnit.Core; + +namespace TUnit.Assertions.Tests; + +public class RegexAPITests +{ + [Test] + public async Task Test_Matches_WithGroup_DirectCall() + { + var email = "john.doe@example.com"; + var pattern = @"(?[\w.]+)@(?[\w.]+)"; + + // Test the new API - requires .And before .Group() for readability + await Assert.That(email) + .Matches(pattern) + .And.Group("username", user => user.IsEqualTo("john.doe")) + .And.Group("domain", domain => domain.IsEqualTo("example.com")); + } + + [Test] + public async Task Test_Matches_WithAnd_ThenGroup() + { + var email = "john.doe@example.com"; + var pattern = @"(?[\w.]+)@(?[\w.]+)"; + + // Test with .And before first .Group() + await Assert.That(email) + .Matches(pattern) + .And.Group("username", user => user.IsEqualTo("john.doe")) + .And.Group("domain", domain => domain.IsEqualTo("example.com")); + } + + [Test] + public async Task Test_Matches_WithMatchAt() + { + var text = "test123 hello456"; + var pattern = @"\w+\d+"; + + // Test accessing multiple matches - requires .And before .Match() + await Assert.That(text) + .Matches(pattern) + .And.Match(0) + .And.Group(0, match => match.IsEqualTo("test123")); + } + + [Test] + public async Task Test_Matches_IndexedGroups() + { + var date = "2025-10-28"; + var pattern = @"(\d{4})-(\d{2})-(\d{2})"; + + // Test indexed groups - all require .And for consistency + await Assert.That(date) + .Matches(pattern) + .And.Group(0, full => full.IsEqualTo("2025-10-28")) + .And.Group(1, year => year.IsEqualTo("2025")) + .And.Group(2, month => month.IsEqualTo("10")) + .And.Group(3, day => day.IsEqualTo("28")); + } + + [Test] + public async Task Test_Match_WithLambda() + { + var text = "test123 hello456"; + var pattern = @"\w+\d+"; + + // Test lambda pattern for match assertions + await Assert.That(text) + .Matches(pattern) + .And.Match(0, match => match.Group(0, g => g.IsEqualTo("test123"))); + } +} diff --git a/TUnit.Assertions.Tests/WaitsForAssertionTests.cs b/TUnit.Assertions.Tests/WaitsForAssertionTests.cs new file mode 100644 index 0000000000..2e37d8c04b --- /dev/null +++ b/TUnit.Assertions.Tests/WaitsForAssertionTests.cs @@ -0,0 +1,265 @@ +using System.Diagnostics; + +namespace TUnit.Assertions.Tests; + +[NotInParallel] +public class WaitsForAssertionTests +{ + [Test] + public async Task WaitsFor_Passes_Immediately_When_Assertion_Succeeds() + { + var stopwatch = Stopwatch.StartNew(); + + var value = 42; + await Assert.That(value).WaitsFor( + assert => assert.IsEqualTo(42), + timeout: TimeSpan.FromSeconds(5)); + + stopwatch.Stop(); + + // Should complete very quickly since assertion passes immediately + await Assert.That(stopwatch.Elapsed).IsLessThan(TimeSpan.FromMilliseconds(100)); + } + + [Test] + public async Task WaitsFor_Passes_After_Multiple_Retries() + { + var counter = 0; + var stopwatch = Stopwatch.StartNew(); + + // Use a func that returns different values based on call count + Func getValue = () => Interlocked.Increment(ref counter); + + await Assert.That(getValue).WaitsFor( + assert => assert.IsGreaterThan(3), + timeout: TimeSpan.FromSeconds(5), + pollingInterval: TimeSpan.FromMilliseconds(10)); + + stopwatch.Stop(); + + // Should have retried at least 3 times + await Assert.That(counter).IsGreaterThanOrEqualTo(4); + } + + [Test] + public async Task WaitsFor_Fails_When_Timeout_Expires() + { + var stopwatch = Stopwatch.StartNew(); + var value = 1; + + var exception = await Assert.That( + async () => await Assert.That(value).WaitsFor( + assert => assert.IsEqualTo(999), + timeout: TimeSpan.FromMilliseconds(100), + pollingInterval: TimeSpan.FromMilliseconds(10)) + ).Throws(); + + stopwatch.Stop(); + + // Verify timeout was respected (should be close to 100ms, not significantly longer) + await Assert.That(stopwatch.Elapsed).IsLessThan(TimeSpan.FromMilliseconds(200)); + + // Verify error message contains useful information + await Assert.That(exception.Message).Contains("assertion did not pass within 100ms"); + await Assert.That(exception.Message).Contains("Last error:"); + } + + [Test] + public async Task WaitsFor_Supports_And_Chaining() + { + var value = 42; + + // WaitsFor should support chaining with And + await Assert.That(value) + .WaitsFor(assert => assert.IsGreaterThan(40), timeout: TimeSpan.FromSeconds(1)) + .And.IsLessThan(50); + } + + [Test] + public async Task WaitsFor_Supports_Or_Chaining() + { + var value = 42; + + // WaitsFor should support chaining with Or + await Assert.That(value) + .WaitsFor(assert => assert.IsEqualTo(42), timeout: TimeSpan.FromSeconds(1)) + .Or.IsEqualTo(43); + } + + [Test] + public async Task WaitsFor_With_Custom_Polling_Interval() + { + var counter = 0; + Func getValue = () => Interlocked.Increment(ref counter); + + var stopwatch = Stopwatch.StartNew(); + + await Assert.That(getValue).WaitsFor( + assert => assert.IsGreaterThan(2), + timeout: TimeSpan.FromSeconds(1), + pollingInterval: TimeSpan.FromMilliseconds(50)); + + stopwatch.Stop(); + + // With 50ms interval and needing >2 (3rd increment), should take at least one polling interval + // The timing may vary slightly due to execution overhead, so we check for at least 40ms + await Assert.That(stopwatch.Elapsed).IsGreaterThan(TimeSpan.FromMilliseconds(40)); + + // Verify counter was actually incremented multiple times + await Assert.That(counter).IsGreaterThanOrEqualTo(3); + } + + [Test] + public async Task WaitsFor_With_Eventually_Changing_Value() + { + var value = 0; + + // Start a task that changes the value after 100ms + _ = Task.Run(async () => + { + await Task.Delay(100); + Interlocked.Exchange(ref value, 42); + }); + + // WaitsFor should poll and eventually see the new value + await Assert.That(() => value).WaitsFor( + assert => assert.IsEqualTo(42), + timeout: TimeSpan.FromSeconds(5), + pollingInterval: TimeSpan.FromMilliseconds(10)); + } + + [Test] + public async Task WaitsFor_Works_With_Complex_Assertions() + { + var list = new List { 1, 2, 3 }; + + // Start a task that adds to the list after 50ms + _ = Task.Run(async () => + { + await Task.Delay(50); + lock (list) + { + list.Add(4); + list.Add(5); + } + }); + + // Wait for list to have 5 items + await Assert.That(() => + { + lock (list) + { + return list.Count; + } + }).WaitsFor( + assert => assert.IsEqualTo(5), + timeout: TimeSpan.FromSeconds(5), + pollingInterval: TimeSpan.FromMilliseconds(10)); + } + + [Test] + public async Task WaitsFor_Throws_ArgumentException_For_Zero_Timeout() + { + var value = 42; + +#pragma warning disable TUnitAssertions0002 // Testing constructor exception, not awaiting + var exception = Assert.Throws(() => + Assert.That(value).WaitsFor( + assert => assert.IsEqualTo(42), + timeout: TimeSpan.Zero)); +#pragma warning restore TUnitAssertions0002 + + await Assert.That(exception.Message).Contains("Timeout must be positive"); + } + + [Test] + public async Task WaitsFor_Throws_ArgumentException_For_Negative_Timeout() + { + var value = 42; + +#pragma warning disable TUnitAssertions0002 // Testing constructor exception, not awaiting + var exception = Assert.Throws(() => + Assert.That(value).WaitsFor( + assert => assert.IsEqualTo(42), + timeout: TimeSpan.FromSeconds(-1))); +#pragma warning restore TUnitAssertions0002 + + await Assert.That(exception.Message).Contains("Timeout must be positive"); + } + + [Test] + public async Task WaitsFor_Throws_ArgumentException_For_Zero_PollingInterval() + { + var value = 42; + +#pragma warning disable TUnitAssertions0002 // Testing constructor exception, not awaiting + var exception = Assert.Throws(() => + Assert.That(value).WaitsFor( + assert => assert.IsEqualTo(42), + timeout: TimeSpan.FromSeconds(1), + pollingInterval: TimeSpan.Zero)); +#pragma warning restore TUnitAssertions0002 + + await Assert.That(exception.Message).Contains("Polling interval must be positive"); + } + + [Test] + public async Task WaitsFor_Throws_ArgumentNullException_For_Null_AssertionBuilder() + { + var value = 42; + +#pragma warning disable TUnitAssertions0002 // Testing constructor exception, not awaiting + var exception = Assert.Throws(() => + Assert.That(value).WaitsFor( + assertionBuilder: null!, + timeout: TimeSpan.FromSeconds(1))); +#pragma warning restore TUnitAssertions0002 + + await Assert.That(exception.ParamName).IsEqualTo("assertionBuilder"); + } + + [Test] + public async Task WaitsFor_Real_World_Scenario_GPIO_Event() + { + // Simulate the real-world scenario from the GitHub issue: + // Testing GPIO events that take time to propagate + + var pinValue = false; + + // Simulate an async GPIO event that changes state after 75ms + _ = Task.Run(async () => + { + await Task.Delay(75); + pinValue = true; + }); + + // Wait for the pin to become true + await Assert.That(() => pinValue).WaitsFor( + assert => assert.IsEqualTo(true), + timeout: TimeSpan.FromSeconds(2), + pollingInterval: TimeSpan.FromMilliseconds(10)); + } + + [Test] + public async Task WaitsFor_Performance_Many_Quick_Polls() + { + var counter = 0; + var stopwatch = Stopwatch.StartNew(); + + // This will take many polls before succeeding + Func getValue = () => Interlocked.Increment(ref counter); + + await Assert.That(getValue).WaitsFor( + assert => assert.IsGreaterThan(100), + timeout: TimeSpan.FromSeconds(5), + pollingInterval: TimeSpan.FromMilliseconds(1)); + + stopwatch.Stop(); + + // Should have made at least 100 attempts + await Assert.That(counter).IsGreaterThanOrEqualTo(101); + + // Should complete in a reasonable time (well under 5 seconds) + await Assert.That(stopwatch.Elapsed).IsLessThan(TimeSpan.FromSeconds(2)); + } +} diff --git a/TUnit.Assertions/Assertions/GenericAssertions.cs b/TUnit.Assertions/Assertions/GenericAssertions.cs new file mode 100644 index 0000000000..61dc2282da --- /dev/null +++ b/TUnit.Assertions/Assertions/GenericAssertions.cs @@ -0,0 +1,42 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Assertions; + +internal static class GenericAssertions +{ + [GenerateAssertion] + public static bool IsIn(this T value, IEnumerable collection) + { + return collection.Contains(value); + } + + [GenerateAssertion] + public static bool IsIn(this T value, IEnumerable collection, IEqualityComparer equalityComparer) + { + return collection.Contains(value, equalityComparer); + } + + [GenerateAssertion] + public static bool IsIn(this T value, params T[] collection) + { + return collection.Contains(value); + } + + [GenerateAssertion] + public static bool IsNotIn(this T value, IEnumerable collection) + { + return !collection.Contains(value); + } + + [GenerateAssertion] + public static bool IsNotIn(this T value, IEnumerable collection, IEqualityComparer equalityComparer) + { + return !collection.Contains(value, equalityComparer); + } + + [GenerateAssertion] + public static bool IsNotIn(this T value, params T[] collection) + { + return !collection.Contains(value); + } +} diff --git a/TUnit.Assertions/Assertions/PropertyAssertion.cs b/TUnit.Assertions/Assertions/PropertyAssertion.cs index e7b92dccec..8112b3db53 100644 --- a/TUnit.Assertions/Assertions/PropertyAssertion.cs +++ b/TUnit.Assertions/Assertions/PropertyAssertion.cs @@ -35,7 +35,6 @@ public PropertyAssertionResult IsEqualTo(TProperty expected) { _parentContext.ExpressionBuilder.Append($".IsEqualTo({expected})"); - // Create assertion on the property and wrap it with type erasure var assertion = new Conditions.EqualsAssertion(_propertyContext, expected); var erasedAssertion = new Conditions.TypeErasedAssertion(assertion); @@ -132,10 +131,8 @@ public TypeOfAssertion IsTypeOf() private async Task ExecuteAsync() { - // Execute the property assertion await _propertyAssertion.AssertAsync(); - // Return the parent object value var (parentValue, _) = await Context.GetAsync(); return parentValue; } diff --git a/TUnit.Assertions/Assertions/Regex/GroupAssertion.cs b/TUnit.Assertions/Assertions/Regex/GroupAssertion.cs new file mode 100644 index 0000000000..b2b998ea6e --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/GroupAssertion.cs @@ -0,0 +1,156 @@ +using TUnit.Assertions.Core; +using TUnit.Assertions.Sources; + +namespace TUnit.Assertions.Assertions.Regex; + +/// +/// Assertion for a regex capture group on a match collection (operates on first match). +/// +public class GroupAssertion : Assertion +{ + private readonly Func, Assertion?> _groupAssertion; + private readonly string? _groupName; + private readonly int? _groupIndex; + + internal GroupAssertion( + AssertionContext context, + string groupName, + Func, Assertion?> assertion, + bool _) + : base(context) + { + _groupName = groupName; + _groupAssertion = assertion; + } + + internal GroupAssertion( + AssertionContext context, + int groupIndex, + Func, Assertion?> assertion, + bool _) + : base(context) + { + _groupIndex = groupIndex; + _groupAssertion = assertion; + } + + protected override async Task CheckAsync(EvaluationMetadata metadata) + { + var collection = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return AssertionResult.Failed($"threw {exception.GetType().Name}: {exception.Message}"); + } + + if (collection == null || collection.Count == 0) + { + return AssertionResult.Failed("No match results available"); + } + + string groupValue; + try + { + groupValue = _groupName != null + ? collection.First.GetGroup(_groupName) + : collection.First.GetGroup(_groupIndex!.Value); + } + catch (Exception ex) + { + return AssertionResult.Failed(ex.Message); + } + + var groupAssertion = new ValueAssertion(groupValue, _groupName ?? $"group {_groupIndex}"); + var resultingAssertion = _groupAssertion(groupAssertion); + if (resultingAssertion != null) + { + await resultingAssertion.AssertAsync(); + } + return AssertionResult.Passed; + } + + protected override string GetExpectation() + { + if (_groupName != null) + { + return $"group '{_groupName}' to satisfy assertion"; + } + return $"group {_groupIndex} to satisfy assertion"; + } +} + +/// +/// Assertion for a regex capture group on a specific match. +/// +public class MatchGroupAssertion : Assertion +{ + private readonly Func, Assertion?> _groupAssertion; + private readonly string? _groupName; + private readonly int? _groupIndex; + + internal MatchGroupAssertion( + AssertionContext context, + string groupName, + Func, Assertion?> assertion) + : base(context) + { + _groupName = groupName; + _groupAssertion = assertion; + } + + internal MatchGroupAssertion( + AssertionContext context, + int groupIndex, + Func, Assertion?> assertion) + : base(context) + { + _groupIndex = groupIndex; + _groupAssertion = assertion; + } + + protected override async Task CheckAsync(EvaluationMetadata metadata) + { + var match = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return AssertionResult.Failed($"threw {exception.GetType().Name}: {exception.Message}"); + } + + if (match == null) + { + return AssertionResult.Failed("No match available"); + } + + string groupValue; + try + { + groupValue = _groupName != null + ? match.GetGroup(_groupName) + : match.GetGroup(_groupIndex!.Value); + } + catch (Exception ex) + { + return AssertionResult.Failed(ex.Message); + } + + var groupAssertion = new ValueAssertion(groupValue, _groupName ?? $"group {_groupIndex}"); + var resultingAssertion = _groupAssertion(groupAssertion); + if (resultingAssertion != null) + { + await resultingAssertion.AssertAsync(); + } + return AssertionResult.Passed; + } + + protected override string GetExpectation() + { + if (_groupName != null) + { + return $"group '{_groupName}' to satisfy assertion"; + } + return $"group {_groupIndex} to satisfy assertion"; + } +} diff --git a/TUnit.Assertions/Assertions/Regex/MatchAssertion.cs b/TUnit.Assertions/Assertions/Regex/MatchAssertion.cs new file mode 100644 index 0000000000..41aef69833 --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/MatchAssertion.cs @@ -0,0 +1,68 @@ +using TUnit.Assertions.Core; +using TUnit.Assertions.Sources; + +namespace TUnit.Assertions.Assertions.Regex; + +/// +/// Assertion for a specific regex match with lambda support. +/// +public class MatchAssertion : Assertion +{ + private readonly int _index; + private readonly Func, Assertion?> _matchAssertion; + + internal MatchAssertion( + AssertionContext context, + int index, + Func, Assertion?> assertion) + : base(context) + { + _index = index; + _matchAssertion = assertion; + } + + protected override async Task CheckAsync(EvaluationMetadata metadata) + { + var collection = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + return AssertionResult.Failed($"threw {exception.GetType().Name}: {exception.Message}"); + } + + if (collection == null) + { + return AssertionResult.Failed("No match collection available"); + } + + if (_index < 0 || _index >= collection.Count) + { + return AssertionResult.Failed( + $"Match index {_index} is out of range. Collection has {collection.Count} matches."); + } + + RegexMatch match; + try + { + match = collection[_index]; + } + catch (Exception ex) + { + return AssertionResult.Failed($"Failed to get match at index {_index}: {ex.Message}"); + } + + var matchAssertion = new ValueAssertion(match, $"match at index {_index}"); + var resultingAssertion = _matchAssertion(matchAssertion); + if (resultingAssertion != null) + { + await resultingAssertion.AssertAsync(); + } + return AssertionResult.Passed; + } + + protected override string GetExpectation() + { + return $"match at index {_index} to satisfy assertion"; + } +} diff --git a/TUnit.Assertions/Assertions/Regex/MatchIndexAssertion.cs b/TUnit.Assertions/Assertions/Regex/MatchIndexAssertion.cs new file mode 100644 index 0000000000..65a19913d5 --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/MatchIndexAssertion.cs @@ -0,0 +1,59 @@ +using TUnit.Assertions.Core; + +namespace TUnit.Assertions.Assertions.Regex; + +/// +/// Assertion that maps from RegexMatchCollection to a specific RegexMatch at an index. +/// Mirrors .NET's MatchCollection[index] indexer. +/// +public class MatchIndexAssertion : Assertion +{ + private readonly int _index; + + internal MatchIndexAssertion( + AssertionContext context, + int index) + : base(context.Map(collection => + { + if (collection == null) + { + throw new InvalidOperationException("No match collection available"); + } + + if (index < 0) + { + throw new ArgumentOutOfRangeException(nameof(index), "Match index must be >= 0"); + } + + if (index >= collection.Count) + { + throw new ArgumentOutOfRangeException(nameof(index), + $"Match index {index} is out of range. Collection has {collection.Count} matches."); + } + + return collection[index]; + })) + { + _index = index; + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var match = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) + { + if (exception is ArgumentOutOfRangeException || exception is InvalidOperationException) + { + return Task.FromResult(AssertionResult.Failed(exception.Message)); + } + return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().Name}")); + } + + // If we have a match, the assertion passed + return Task.FromResult(AssertionResult.Passed); + } + + protected override string GetExpectation() => $"match at index {_index} to exist"; +} diff --git a/TUnit.Assertions/Assertions/Regex/RegexMatch.cs b/TUnit.Assertions/Assertions/Regex/RegexMatch.cs new file mode 100644 index 0000000000..df55ff34ba --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/RegexMatch.cs @@ -0,0 +1,77 @@ +using System.Text.RegularExpressions; + +namespace TUnit.Assertions.Assertions.Regex; + +/// +/// Represents a single regex match with access to capture groups, match position, and length. +/// Mirrors the .NET System.Text.RegularExpressions.Match type. +/// +public class RegexMatch +{ + internal Match InternalMatch { get; } + + internal RegexMatch(Match match) + { + InternalMatch = match ?? throw new ArgumentNullException(nameof(match)); + + if (!match.Success) + { + throw new InvalidOperationException("Cannot create RegexMatch from an unsuccessful match"); + } + } + + /// + /// Gets the captured string for a named group. + /// + /// Thrown when the group name is null, empty, or does not exist in the match. + public string GetGroup(string groupName) + { + if (string.IsNullOrEmpty(groupName)) + { + throw new ArgumentException("Group name cannot be null or empty", nameof(groupName)); + } + + var group = InternalMatch.Groups[groupName]; + if (!group.Success) + { + throw new ArgumentException( + $"Group '{groupName}' does not exist in the match", + nameof(groupName)); + } + + return group.Value; + } + + /// + /// Gets the captured string for an indexed group (0 is full match, 1+ are capture groups). + /// + public string GetGroup(int groupIndex) + { + if (groupIndex < 0) + { + throw new ArgumentOutOfRangeException(nameof(groupIndex), "Group index must be >= 0"); + } + + if (groupIndex >= InternalMatch.Groups.Count) + { + throw new ArgumentOutOfRangeException(nameof(groupIndex), $"Group index {groupIndex} is out of range. Match has {InternalMatch.Groups.Count} groups."); + } + + return InternalMatch.Groups[groupIndex].Value; + } + + /// + /// Gets the index where the match starts in the input string. + /// + public int Index => InternalMatch.Index; + + /// + /// Gets the length of the matched string. + /// + public int Length => InternalMatch.Length; + + /// + /// Gets the matched string value. + /// + public string Value => InternalMatch.Value; +} diff --git a/TUnit.Assertions/Assertions/Regex/RegexMatchCollection.cs b/TUnit.Assertions/Assertions/Regex/RegexMatchCollection.cs new file mode 100644 index 0000000000..30fe4eb824 --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/RegexMatchCollection.cs @@ -0,0 +1,57 @@ +using System.Collections; +using System.Text.RegularExpressions; + +namespace TUnit.Assertions.Assertions.Regex; + +/// +/// Collection of all regex matches from a string. +/// Mirrors the .NET System.Text.RegularExpressions.MatchCollection type. +/// +public class RegexMatchCollection : IReadOnlyList +{ + private readonly List _matches; + + internal RegexMatchCollection(MatchCollection matches) + { + if (matches == null) + { + throw new ArgumentNullException(nameof(matches)); + } + + _matches = []; + foreach (Match match in matches) + { + if (match.Success) + { + _matches.Add(new RegexMatch(match)); + } + } + + if (_matches.Count == 0) + { + throw new InvalidOperationException("No successful matches found"); + } + } + + /// + /// Gets the first match in the collection. + /// + public RegexMatch First => _matches[0]; + + /// + /// Gets the match at the specified index. + /// + public RegexMatch this[int index] => _matches[index]; + + /// + /// Gets the number of matches in the collection. + /// + public int Count => _matches.Count; + + /// + /// Returns an enumerator that iterates through the matches. + /// + public IEnumerator GetEnumerator() => _matches.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/TUnit.Assertions/Assertions/Regex/StringMatchesAssertionExtensions.cs b/TUnit.Assertions/Assertions/Regex/StringMatchesAssertionExtensions.cs new file mode 100644 index 0000000000..7f58e32445 --- /dev/null +++ b/TUnit.Assertions/Assertions/Regex/StringMatchesAssertionExtensions.cs @@ -0,0 +1,153 @@ +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using TUnit.Assertions.Assertions.Regex; +using TUnit.Assertions.Conditions; +using TUnit.Assertions.Core; +using TUnit.Assertions.Sources; + +namespace TUnit.Assertions.Extensions; + +/// +/// Extension methods for regex match assertions to access capture groups and individual matches. +/// +public static class RegexAssertionExtensions +{ + // =============================================================== + // .Matches() - Maps string → RegexMatchCollection + // =============================================================== + + /// + /// Asserts that a string matches a regular expression pattern. + /// Returns a collection of all matches for further assertions. + /// + public static StringMatchesAssertion Matches( + this IAssertionSource source, + string pattern, + [CallerArgumentExpression(nameof(pattern))] string? patternExpression = null) + { + source.Context.ExpressionBuilder.Append(".Matches(" + (patternExpression ?? "?") + ")"); + return new StringMatchesAssertion(source.Context, pattern); + } + + /// + /// Asserts that a string matches a regular expression. + /// Returns a collection of all matches for further assertions. + /// + public static StringMatchesAssertion Matches( + this IAssertionSource source, + System.Text.RegularExpressions.Regex regex, + [CallerArgumentExpression(nameof(regex))] string? regexExpression = null) + { + source.Context.ExpressionBuilder.Append(".Matches(" + (regexExpression ?? "regex") + ")"); + return new StringMatchesAssertion(source.Context, regex); + } + + // =============================================================== + // .Match(index) - Maps RegexMatchCollection → RegexMatch + // =============================================================== + + /// + /// Gets a specific match by index from the match collection. + /// Requires .And before .Match() for better readability. + /// Mirrors .NET's MatchCollection[index] indexer. + /// + public static MatchIndexAssertion Match( + this AndContinuation continuation, + int index) + { + return new MatchIndexAssertion(continuation.Context, index); + } + + /// + /// Asserts on a specific match by index from the match collection using a lambda. + /// Requires .And before .Match() for better readability. + /// + public static MatchAssertion Match( + this AndContinuation continuation, + int index, + Func, Assertion?> assertion) + { + return new MatchAssertion(continuation.Context, index, assertion); + } + + // =============================================================== + // .Group() - Operates on first match in collection + // =============================================================== + + /// + /// Asserts on a named capture group from the first regex match. + /// Requires .And before .Group() for better readability. + /// + public static GroupAssertion Group( + this AndContinuation continuation, + string groupName, + Func, Assertion?> assertion) + { + return new GroupAssertion(continuation.Context, groupName, assertion, true); + } + + /// + /// Asserts on an indexed capture group from the first regex match. + /// Requires .And before .Group() for better readability. + /// + public static GroupAssertion Group( + this AndContinuation continuation, + int groupIndex, + Func, Assertion?> assertion) + { + return new GroupAssertion(continuation.Context, groupIndex, assertion, true); + } + + // =============================================================== + // .Group() - Operates on specific match (after .Match(index)) + // =============================================================== + + /// + /// Asserts on a named capture group from a specific regex match. + /// Can be used inside lambda expressions or after .And for chaining. + /// + public static MatchGroupAssertion Group( + this ValueAssertion source, + string groupName, + Func, Assertion?> assertion) + { + return new MatchGroupAssertion(source.Context, groupName, assertion); + } + + /// + /// Asserts on an indexed capture group from a specific regex match. + /// Can be used inside lambda expressions or after .And for chaining. + /// + public static MatchGroupAssertion Group( + this ValueAssertion source, + int groupIndex, + Func, Assertion?> assertion) + { + return new MatchGroupAssertion(source.Context, groupIndex, assertion); + } + + /// + /// Asserts on a named capture group from a specific regex match. + /// Requires .And before .Group() for better readability. + /// + public static MatchGroupAssertion Group( + this AndContinuation continuation, + string groupName, + Func, Assertion?> assertion) + { + return new MatchGroupAssertion(continuation.Context, groupName, assertion); + } + + /// + /// Asserts on an indexed capture group from a specific regex match. + /// Requires .And before .Group() for better readability. + /// + public static MatchGroupAssertion Group( + this AndContinuation continuation, + int groupIndex, + Func, Assertion?> assertion) + { + return new MatchGroupAssertion(continuation.Context, groupIndex, assertion); + } +} + diff --git a/TUnit.Assertions/Attributes/AssertionFromAttribute.cs b/TUnit.Assertions/Attributes/AssertionFromAttribute.cs index dcddf31073..3c749ababb 100644 --- a/TUnit.Assertions/Attributes/AssertionFromAttribute.cs +++ b/TUnit.Assertions/Attributes/AssertionFromAttribute.cs @@ -129,4 +129,16 @@ public AssertionFromAttribute(Type targetType, Type containingType, string metho /// When false (default), the generator automatically determines the pattern. /// public bool TreatAsInstance { get; set; } + + /// + /// Optional custom expectation message shown in assertion failures. + /// If not specified, a default message based on the method name will be used. + /// + /// + /// + /// [AssertionFrom(typeof(double), "IsNaN", ExpectationMessage = "be NaN")] + /// // Generates failure message: "Expected value to be NaN" + /// + /// + public string? ExpectationMessage { get; set; } } diff --git a/TUnit.Assertions/Attributes/CreateAssertionAttribute.cs b/TUnit.Assertions/Attributes/CreateAssertionAttribute.cs deleted file mode 100644 index 01fd9c22eb..0000000000 --- a/TUnit.Assertions/Attributes/CreateAssertionAttribute.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; - -namespace TUnit.Assertions.Attributes; - -/// -/// DEPRECATED: Use instead. -/// This attribute has been renamed for better clarity. -/// -[Obsolete("Use AssertionFromAttribute instead. This attribute will be removed in a future version.")] -[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] -public class CreateAssertionAttribute : Attribute -{ - public CreateAssertionAttribute(Type targetType, string methodName) - { - TargetType = targetType; - MethodName = methodName; - } - - /// - /// Constructor for methods on a different type than the target type. - /// - /// The type of the first parameter (what becomes IValueSource<T>) - /// The type that contains the static method - /// The name of the static method - /// The types of assertions to generate - public CreateAssertionAttribute(Type targetType, Type containingType, string methodName) - { - TargetType = targetType; - ContainingType = containingType; - MethodName = methodName; - } - - public Type TargetType { get; } - public Type? ContainingType { get; } - public string MethodName { get; } - - - /// - /// Optional custom name for the generated assertion method. If not specified, the name will be derived from the target method name. - /// - public string? CustomName { get; set; } - - /// - /// When true, inverts the logic of the assertion. This is used for creating negative assertions (e.g., DoesNotContain from Contains). - /// The generated assertion will negate the result of the target method. - /// - public bool NegateLogic { get; set; } - - /// - /// Indicates if this method requires generic type parameter handling (e.g., Enum.IsDefined(Type, object) where Type becomes typeof(T)). - /// - public bool RequiresGenericTypeParameter { get; set; } - - /// - /// When true, treats the method as an instance method even if it's static (useful for extension methods). - /// When false (default), the generator will automatically determine based on the method's actual signature. - /// - public bool TreatAsInstance { get; set; } -} diff --git a/TUnit.Assertions/Attributes/CreateAssertionAttribute`1.cs b/TUnit.Assertions/Attributes/CreateAssertionAttribute`1.cs deleted file mode 100644 index 62d2f1cf07..0000000000 --- a/TUnit.Assertions/Attributes/CreateAssertionAttribute`1.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; - -namespace TUnit.Assertions.Attributes; - -/// -/// DEPRECATED: Use instead. -/// This attribute has been renamed for better clarity. -/// -/// The target type for the assertion -[Obsolete("Use AssertionFromAttribute instead. This attribute will be removed in a future version.")] -[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] -public class CreateAssertionAttribute : Attribute -{ - public CreateAssertionAttribute(string methodName) - { - TargetType = typeof(TTarget); - MethodName = methodName; - } - - /// - /// Constructor for methods on a different type than the target type. - /// - /// The type that contains the static method - /// The name of the static method - public CreateAssertionAttribute(Type containingType, string methodName) - { - TargetType = typeof(TTarget); - ContainingType = containingType; - MethodName = methodName; - } - - public Type TargetType { get; } - public Type? ContainingType { get; } - public string MethodName { get; } - - /// - /// Optional custom name for the generated assertion method. If not specified, the name will be derived from the target method name. - /// - public string? CustomName { get; set; } - - /// - /// When true, inverts the logic of the assertion. This is used for creating negative assertions (e.g., DoesNotContain from Contains). - /// The generated assertion will negate the result of the target method. - /// - public bool NegateLogic { get; set; } - - /// - /// Indicates if this method requires generic type parameter handling (e.g., Enum.IsDefined(Type, object) where Type becomes typeof(T)). - /// - public bool RequiresGenericTypeParameter { get; set; } - - /// - /// When true, treats the method as an instance method even if it's static (useful for extension methods). - /// When false (default), the generator will automatically determine based on the method's actual signature. - /// - public bool TreatAsInstance { get; set; } -} \ No newline at end of file diff --git a/TUnit.Assertions/Chaining/OrAssertion.cs b/TUnit.Assertions/Chaining/OrAssertion.cs index a462ca989e..47aa2e87c2 100644 --- a/TUnit.Assertions/Chaining/OrAssertion.cs +++ b/TUnit.Assertions/Chaining/OrAssertion.cs @@ -75,7 +75,6 @@ public OrAssertion( // Both failed - build combined message var secondException = currentScope.GetLastException(); - // Remove both individual exceptions and add combined one currentScope.RemoveLastExceptions(2); var combinedExpectation = BuildCombinedExpectation(); diff --git a/TUnit.Assertions/Conditions/BigIntegerAssertionExtensions.cs b/TUnit.Assertions/Conditions/BigIntegerAssertionExtensions.cs new file mode 100644 index 0000000000..1d975e5ac6 --- /dev/null +++ b/TUnit.Assertions/Conditions/BigIntegerAssertionExtensions.cs @@ -0,0 +1,27 @@ +using System.Numerics; +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for BigInteger type using [AssertionFrom<BigInteger>] attributes. +/// Each assertion wraps a property from the BigInteger structure for numeric checks. +/// +[AssertionFrom(nameof(BigInteger.IsZero), ExpectationMessage = "be zero")] +[AssertionFrom(nameof(BigInteger.IsZero), CustomName = "IsNotZero", NegateLogic = true, ExpectationMessage = "be zero")] + +#if NET6_0_OR_GREATER +[AssertionFrom(nameof(BigInteger.IsOne), ExpectationMessage = "be one")] +[AssertionFrom(nameof(BigInteger.IsOne), CustomName = "IsNotOne", NegateLogic = true, ExpectationMessage = "be one")] +#endif + +[AssertionFrom(nameof(BigInteger.IsEven), ExpectationMessage = "be even")] +[AssertionFrom(nameof(BigInteger.IsEven), CustomName = "IsNotEven", NegateLogic = true, ExpectationMessage = "be even")] + +#if NET6_0_OR_GREATER +[AssertionFrom(nameof(BigInteger.IsPowerOfTwo), ExpectationMessage = "be a power of two")] +[AssertionFrom(nameof(BigInteger.IsPowerOfTwo), CustomName = "IsNotPowerOfTwo", NegateLogic = true, ExpectationMessage = "be a power of two")] +#endif +public static partial class BigIntegerAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/CookieAssertionExtensions.cs b/TUnit.Assertions/Conditions/CookieAssertionExtensions.cs new file mode 100644 index 0000000000..31c7b064a5 --- /dev/null +++ b/TUnit.Assertions/Conditions/CookieAssertionExtensions.cs @@ -0,0 +1,20 @@ +using System.Net; +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for Cookie type using [AssertionFrom<Cookie>] attributes. +/// Each assertion wraps a property from the Cookie class for web and authentication testing. +/// +[AssertionFrom(nameof(Cookie.HttpOnly), ExpectationMessage = "be HTTP-only")] +[AssertionFrom(nameof(Cookie.HttpOnly), CustomName = "IsNotHttpOnly", NegateLogic = true, ExpectationMessage = "be HTTP-only")] + +[AssertionFrom(nameof(Cookie.Secure), ExpectationMessage = "be secure")] +[AssertionFrom(nameof(Cookie.Secure), CustomName = "IsNotSecure", NegateLogic = true, ExpectationMessage = "be secure")] + +[AssertionFrom(nameof(Cookie.Expired), ExpectationMessage = "be expired")] +[AssertionFrom(nameof(Cookie.Expired), CustomName = "IsNotExpired", NegateLogic = true, ExpectationMessage = "be expired")] +public static partial class CookieAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/DoubleAssertionExtensions.cs b/TUnit.Assertions/Conditions/DoubleAssertionExtensions.cs new file mode 100644 index 0000000000..27b7c9073f --- /dev/null +++ b/TUnit.Assertions/Conditions/DoubleAssertionExtensions.cs @@ -0,0 +1,33 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for double type using [AssertionFrom<double>] attributes. +/// Each assertion wraps a static method from the double class for special numeric value checks. +/// +[AssertionFrom(nameof(double.IsNaN), ExpectationMessage = "be NaN")] +[AssertionFrom(nameof(double.IsNaN), CustomName = "IsNotNaN", NegateLogic = true, ExpectationMessage = "be NaN")] + +[AssertionFrom(nameof(double.IsInfinity), ExpectationMessage = "be infinity")] +[AssertionFrom(nameof(double.IsInfinity), CustomName = "IsNotInfinity", NegateLogic = true, ExpectationMessage = "be infinity")] + +[AssertionFrom(nameof(double.IsPositiveInfinity), ExpectationMessage = "be positive infinity")] +[AssertionFrom(nameof(double.IsPositiveInfinity), CustomName = "IsNotPositiveInfinity", NegateLogic = true, ExpectationMessage = "be positive infinity")] + +[AssertionFrom(nameof(double.IsNegativeInfinity), ExpectationMessage = "be negative infinity")] +[AssertionFrom(nameof(double.IsNegativeInfinity), CustomName = "IsNotNegativeInfinity", NegateLogic = true, ExpectationMessage = "be negative infinity")] + +#if NET5_0_OR_GREATER +[AssertionFrom(nameof(double.IsFinite), ExpectationMessage = "be finite")] +[AssertionFrom(nameof(double.IsFinite), CustomName = "IsNotFinite", NegateLogic = true, ExpectationMessage = "be finite")] + +[AssertionFrom(nameof(double.IsNormal), ExpectationMessage = "be normal")] +[AssertionFrom(nameof(double.IsNormal), CustomName = "IsNotNormal", NegateLogic = true, ExpectationMessage = "be normal")] + +[AssertionFrom(nameof(double.IsSubnormal), ExpectationMessage = "be subnormal")] +[AssertionFrom(nameof(double.IsSubnormal), CustomName = "IsNotSubnormal", NegateLogic = true, ExpectationMessage = "be subnormal")] +#endif +public static partial class DoubleAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/HasDistinctItemsAssertion.cs b/TUnit.Assertions/Conditions/HasDistinctItemsAssertion.cs index d78a86b509..a61b3a5efe 100644 --- a/TUnit.Assertions/Conditions/HasDistinctItemsAssertion.cs +++ b/TUnit.Assertions/Conditions/HasDistinctItemsAssertion.cs @@ -31,21 +31,26 @@ protected override Task CheckAsync(EvaluationMetadata(); + var duplicates = new List(); + var totalCount = 0; - if (list.Count == distinctList.Count) + foreach (var item in value) { - return Task.FromResult(AssertionResult.Passed); + totalCount++; + if (!seen.Add(item) && !duplicates.Contains(item)) + { + duplicates.Add(item); + } } - var duplicates = list.GroupBy(x => x) - .Where(g => g.Count() > 1) - .Select(g => g.Key) - .ToList(); + if (duplicates.Count == 0) + { + return Task.FromResult(AssertionResult.Passed); + } return Task.FromResult(AssertionResult.Failed( - $"found {list.Count - distinctList.Count} duplicate(s): {string.Join(", ", duplicates)}")); + $"found {totalCount - seen.Count} duplicate(s): {string.Join(", ", duplicates)}")); } protected override string GetExpectation() => "to have distinct items"; diff --git a/TUnit.Assertions/Conditions/Helpers/CollectionEquivalencyChecker.cs b/TUnit.Assertions/Conditions/Helpers/CollectionEquivalencyChecker.cs index a5447ed9e6..0d7ae09386 100644 --- a/TUnit.Assertions/Conditions/Helpers/CollectionEquivalencyChecker.cs +++ b/TUnit.Assertions/Conditions/Helpers/CollectionEquivalencyChecker.cs @@ -34,8 +34,9 @@ public static CheckResult AreEquivalent( return CheckResult.Failure("collection was null"); } - var actualList = actual.ToList(); - var expectedList = expected.ToList(); + // Optimize for collections that are already lists to avoid re-enumeration + var actualList = actual is List actualListCasted ? actualListCasted : actual.ToList(); + var expectedList = expected is List expectedListCasted ? expectedListCasted : expected.ToList(); // Check counts first if (actualList.Count != expectedList.Count) diff --git a/TUnit.Assertions/Conditions/HttpResponseMessageAssertionExtensions.cs b/TUnit.Assertions/Conditions/HttpResponseMessageAssertionExtensions.cs new file mode 100644 index 0000000000..e999d11c70 --- /dev/null +++ b/TUnit.Assertions/Conditions/HttpResponseMessageAssertionExtensions.cs @@ -0,0 +1,14 @@ +using System.Net.Http; +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for HttpResponseMessage type using [AssertionFrom<HttpResponseMessage>] attributes. +/// These wrap HTTP response validation checks as extension methods. +/// +[AssertionFrom(nameof(HttpResponseMessage.IsSuccessStatusCode), ExpectationMessage = "have a success status code")] +[AssertionFrom(nameof(HttpResponseMessage.IsSuccessStatusCode), CustomName = "IsNotSuccessStatusCode", NegateLogic = true, ExpectationMessage = "have a success status code")] +public static partial class HttpResponseMessageAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/MemberAssertion.cs b/TUnit.Assertions/Conditions/MemberAssertion.cs index ce51314c54..991c6147b5 100644 --- a/TUnit.Assertions/Conditions/MemberAssertion.cs +++ b/TUnit.Assertions/Conditions/MemberAssertion.cs @@ -64,10 +64,8 @@ public static implicit operator Assertion(MemberAssertionResult ExecuteAsync() { - // Execute the member assertion await _memberAssertion.AssertAsync(); - // Return the parent object value var (parentValue, _) = await _parentContext.GetAsync(); return parentValue; } @@ -89,17 +87,14 @@ public MemberExecutionWrapper(AssertionContext parentContext, Assertion public override async Task AssertAsync() { - // Execute the member assertion await _memberAssertion.AssertAsync(); - // Return the parent object value for further chaining var (parentValue, _) = await Context.GetAsync(); return parentValue; } protected override async Task CheckAsync(EvaluationMetadata metadata) { - // Execute the member assertion await _memberAssertion.AssertAsync(); return AssertionResult.Passed; } diff --git a/TUnit.Assertions/Conditions/MembershipAssertions.cs b/TUnit.Assertions/Conditions/MembershipAssertions.cs deleted file mode 100644 index 3dbdb19fce..0000000000 --- a/TUnit.Assertions/Conditions/MembershipAssertions.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Text; -using TUnit.Assertions.Attributes; -using TUnit.Assertions.Core; - -namespace TUnit.Assertions.Conditions; - -/// -/// Asserts that a value is in a collection. -/// -[AssertionExtension("IsIn")] -public class IsInAssertion : ComparerBasedAssertion -{ - private readonly IEnumerable _collection; - - public IsInAssertion( - AssertionContext context, - IEnumerable collection) - : base(context) - { - _collection = collection; - } - - public IsInAssertion Using(IEqualityComparer comparer) - { - SetComparer(comparer); - return this; - } - - protected override Task CheckAsync(EvaluationMetadata metadata) - { - var value = metadata.Value; - var exception = metadata.Exception; - - if (exception != null) - { - return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().Name}")); - } - - var comparer = GetComparer(); - - foreach (var item in _collection) - { - if (comparer.Equals(value!, item)) - { - return Task.FromResult(AssertionResult.Passed); - } - } - - return Task.FromResult(AssertionResult.Failed($"value {value} was not found in collection")); - } - - protected override string GetExpectation() => "to be in collection"; -} - -/// -/// Asserts that a value is NOT in a collection. -/// -[AssertionExtension("IsNotIn")] -public class IsNotInAssertion : ComparerBasedAssertion -{ - private readonly IEnumerable _collection; - - public IsNotInAssertion( - AssertionContext context, - IEnumerable collection) - : base(context) - { - _collection = collection; - } - - public IsNotInAssertion Using(IEqualityComparer comparer) - { - SetComparer(comparer); - return this; - } - - protected override Task CheckAsync(EvaluationMetadata metadata) - { - var value = metadata.Value; - var exception = metadata.Exception; - - if (exception != null) - { - return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().Name}")); - } - - var comparer = GetComparer(); - - foreach (var item in _collection) - { - if (comparer.Equals(value!, item)) - { - return Task.FromResult(AssertionResult.Failed($"value {value} was found in collection")); - } - } - - return Task.FromResult(AssertionResult.Passed); - } - - protected override string GetExpectation() => "to not be in collection"; -} diff --git a/TUnit.Assertions/Conditions/NullableAssertionExtensions.cs b/TUnit.Assertions/Conditions/NullableAssertionExtensions.cs new file mode 100644 index 0000000000..bf987c1865 --- /dev/null +++ b/TUnit.Assertions/Conditions/NullableAssertionExtensions.cs @@ -0,0 +1,13 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for Nullable<T> type using [AssertionFrom<Nullable<T>>] attributes. +/// These wrap nullable value checks as extension methods. +/// +[AssertionFrom(typeof(int?), nameof(Nullable.HasValue), ExpectationMessage = "have a value")] +[AssertionFrom(typeof(int?), nameof(Nullable.HasValue), CustomName = "DoesNotHaveValue", NegateLogic = true, ExpectationMessage = "have a value")] +public static partial class NullableAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/RuneAssertionExtensions.cs b/TUnit.Assertions/Conditions/RuneAssertionExtensions.cs new file mode 100644 index 0000000000..1522033b4f --- /dev/null +++ b/TUnit.Assertions/Conditions/RuneAssertionExtensions.cs @@ -0,0 +1,55 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +#if NET5_0_OR_GREATER +using System.Text; + +/// +/// Source-generated assertions for Rune type using [AssertionFrom<Rune>] attributes. +/// Each assertion wraps a static method or property from the Rune structure for Unicode scalar checks. +/// Rune is the modern, correct type for handling Unicode scalar values. +/// Available in .NET 5.0+ +/// +[AssertionFrom(nameof(Rune.IsAscii), ExpectationMessage = "be ASCII")] +[AssertionFrom(nameof(Rune.IsAscii), CustomName = "IsNotAscii", NegateLogic = true, ExpectationMessage = "be ASCII")] + +[AssertionFrom(nameof(Rune.IsBmp), ExpectationMessage = "be in the Basic Multilingual Plane")] +[AssertionFrom(nameof(Rune.IsBmp), CustomName = "IsNotBmp", NegateLogic = true, ExpectationMessage = "be in the Basic Multilingual Plane")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsLetter), ExpectationMessage = "be a letter")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsLetter), CustomName = "IsNotLetter", NegateLogic = true, ExpectationMessage = "be a letter")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsDigit), ExpectationMessage = "be a digit")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsDigit), CustomName = "IsNotDigit", NegateLogic = true, ExpectationMessage = "be a digit")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsWhiteSpace), ExpectationMessage = "be whitespace")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsWhiteSpace), CustomName = "IsNotWhiteSpace", NegateLogic = true, ExpectationMessage = "be whitespace")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsUpper), ExpectationMessage = "be uppercase")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsUpper), CustomName = "IsNotUpper", NegateLogic = true, ExpectationMessage = "be uppercase")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsLower), ExpectationMessage = "be lowercase")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsLower), CustomName = "IsNotLower", NegateLogic = true, ExpectationMessage = "be lowercase")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsControl), ExpectationMessage = "be a control character")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsControl), CustomName = "IsNotControl", NegateLogic = true, ExpectationMessage = "be a control character")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsPunctuation), ExpectationMessage = "be punctuation")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsPunctuation), CustomName = "IsNotPunctuation", NegateLogic = true, ExpectationMessage = "be punctuation")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsSymbol), ExpectationMessage = "be a symbol")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsSymbol), CustomName = "IsNotSymbol", NegateLogic = true, ExpectationMessage = "be a symbol")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsNumber), ExpectationMessage = "be a number")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsNumber), CustomName = "IsNotNumber", NegateLogic = true, ExpectationMessage = "be a number")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsSeparator), ExpectationMessage = "be a separator")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsSeparator), CustomName = "IsNotSeparator", NegateLogic = true, ExpectationMessage = "be a separator")] + +[AssertionFrom(typeof(Rune), nameof(Rune.IsLetterOrDigit), ExpectationMessage = "be a letter or digit")] +[AssertionFrom(typeof(Rune), nameof(Rune.IsLetterOrDigit), CustomName = "IsNotLetterOrDigit", NegateLogic = true, ExpectationMessage = "be a letter or digit")] +public static partial class RuneAssertionExtensions +{ +} +#endif diff --git a/TUnit.Assertions/Conditions/SingleAssertionExtensions.cs b/TUnit.Assertions/Conditions/SingleAssertionExtensions.cs new file mode 100644 index 0000000000..424794b25a --- /dev/null +++ b/TUnit.Assertions/Conditions/SingleAssertionExtensions.cs @@ -0,0 +1,33 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for float (Single) type using [AssertionFrom<float>] attributes. +/// Each assertion wraps a static method from the float class for special numeric value checks. +/// +[AssertionFrom(nameof(float.IsNaN), ExpectationMessage = "be NaN")] +[AssertionFrom(nameof(float.IsNaN), CustomName = "IsNotNaN", NegateLogic = true, ExpectationMessage = "be NaN")] + +[AssertionFrom(nameof(float.IsInfinity), ExpectationMessage = "be infinity")] +[AssertionFrom(nameof(float.IsInfinity), CustomName = "IsNotInfinity", NegateLogic = true, ExpectationMessage = "be infinity")] + +[AssertionFrom(nameof(float.IsPositiveInfinity), ExpectationMessage = "be positive infinity")] +[AssertionFrom(nameof(float.IsPositiveInfinity), CustomName = "IsNotPositiveInfinity", NegateLogic = true, ExpectationMessage = "be positive infinity")] + +[AssertionFrom(nameof(float.IsNegativeInfinity), ExpectationMessage = "be negative infinity")] +[AssertionFrom(nameof(float.IsNegativeInfinity), CustomName = "IsNotNegativeInfinity", NegateLogic = true, ExpectationMessage = "be negative infinity")] + +#if NET5_0_OR_GREATER +[AssertionFrom(nameof(float.IsFinite), ExpectationMessage = "be finite")] +[AssertionFrom(nameof(float.IsFinite), CustomName = "IsNotFinite", NegateLogic = true, ExpectationMessage = "be finite")] + +[AssertionFrom(nameof(float.IsNormal), ExpectationMessage = "be normal")] +[AssertionFrom(nameof(float.IsNormal), CustomName = "IsNotNormal", NegateLogic = true, ExpectationMessage = "be normal")] + +[AssertionFrom(nameof(float.IsSubnormal), ExpectationMessage = "be subnormal")] +[AssertionFrom(nameof(float.IsSubnormal), CustomName = "IsNotSubnormal", NegateLogic = true, ExpectationMessage = "be subnormal")] +#endif +public static partial class SingleAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/SpanAssertionExtensions.cs b/TUnit.Assertions/Conditions/SpanAssertionExtensions.cs new file mode 100644 index 0000000000..f87d05bd0f --- /dev/null +++ b/TUnit.Assertions/Conditions/SpanAssertionExtensions.cs @@ -0,0 +1,24 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +#if NET5_0_OR_GREATER +using System; + +/// +/// Source-generated assertions for Memory<T> and ReadOnlyMemory<T> types using [AssertionFrom] attributes. +/// Note: Span types cannot be used due to ref struct constraints in the assertion framework. +/// Available in .NET 5.0+ +/// + +// Memory assertions +[AssertionFrom(typeof(Memory<>), nameof(Memory.IsEmpty), ExpectationMessage = "be empty")] +[AssertionFrom(typeof(Memory<>), nameof(Memory.IsEmpty), CustomName = "IsNotEmpty", NegateLogic = true, ExpectationMessage = "be empty")] + +// ReadOnlyMemory assertions +[AssertionFrom(typeof(ReadOnlyMemory<>), nameof(ReadOnlyMemory.IsEmpty), ExpectationMessage = "be empty")] +[AssertionFrom(typeof(ReadOnlyMemory<>), nameof(ReadOnlyMemory.IsEmpty), CustomName = "IsNotEmpty", NegateLogic = true, ExpectationMessage = "be empty")] +public static partial class SpanAssertionExtensions +{ +} +#endif diff --git a/TUnit.Assertions/Conditions/StringAssertions.cs b/TUnit.Assertions/Conditions/StringAssertions.cs index 8d49f69e17..95e20d0ed1 100644 --- a/TUnit.Assertions/Conditions/StringAssertions.cs +++ b/TUnit.Assertions/Conditions/StringAssertions.cs @@ -1,5 +1,6 @@ using System.Text; using System.Text.RegularExpressions; +using TUnit.Assertions.Assertions.Regex; using TUnit.Assertions.Attributes; using TUnit.Assertions.Core; @@ -88,8 +89,8 @@ protected override Task CheckAsync(EvaluationMetadata m if (_ignoringWhitespace) { - actualValue = string.Concat(actualValue.Where(c => !char.IsWhiteSpace(c))); - expectedValue = string.Concat(expectedValue.Where(c => !char.IsWhiteSpace(c))); + actualValue = RemoveWhitespace(actualValue); + expectedValue = RemoveWhitespace(expectedValue); } if (actualValue.Contains(expectedValue, _comparison)) @@ -100,6 +101,24 @@ protected override Task CheckAsync(EvaluationMetadata m return Task.FromResult(AssertionResult.Failed($"found \"{value}\"")); } + private static string RemoveWhitespace(string input) + { + if (string.IsNullOrEmpty(input)) + { + return input; + } + + var sb = new StringBuilder(input.Length); + foreach (var c in input) + { + if (!char.IsWhiteSpace(c)) + { + sb.Append(c); + } + } + return sb.ToString(); + } + protected override string GetExpectation() => $"to contain \"{_expected}\""; } @@ -422,10 +441,9 @@ protected override Task CheckAsync(EvaluationMetadata m } /// -/// Asserts that a string matches a regular expression pattern. +/// Asserts that a string matches a regular expression pattern and returns a collection of all matches. /// -[AssertionExtension("Matches")] -public class StringMatchesAssertion : Assertion +public class StringMatchesAssertion : Assertion { private readonly string _pattern; private readonly Regex? _regex; @@ -434,7 +452,7 @@ public class StringMatchesAssertion : Assertion public StringMatchesAssertion( AssertionContext context, string pattern) - : base(context) + : base(CreateMappedContext(context, pattern, null, RegexOptions.None)) { _pattern = pattern; _regex = null; @@ -443,55 +461,87 @@ public StringMatchesAssertion( public StringMatchesAssertion( AssertionContext context, Regex regex) - : base(context) + : base(CreateMappedContext(context, regex.ToString(), regex, RegexOptions.None)) { _pattern = regex.ToString(); _regex = regex; } + // Private constructor for chaining methods like IgnoringCase + private StringMatchesAssertion( + AssertionContext mappedContext, + string pattern, + Regex? regex, + RegexOptions options) + : base(mappedContext) + { + _pattern = pattern; + _regex = regex; + _options = options; + } + public StringMatchesAssertion IgnoringCase() { - _options |= RegexOptions.IgnoreCase; + var newOptions = _options | RegexOptions.IgnoreCase; Context.ExpressionBuilder.Append(".IgnoringCase()"); - return this; + return new StringMatchesAssertion(Context, _pattern, _regex, newOptions); } public StringMatchesAssertion WithOptions(RegexOptions options) { - _options = options; Context.ExpressionBuilder.Append($".WithOptions({options})"); - return this; + return new StringMatchesAssertion(Context, _pattern, _regex, options); } - protected override Task CheckAsync(EvaluationMetadata metadata) + private static AssertionContext CreateMappedContext( + AssertionContext context, + string pattern, + Regex? regex, + RegexOptions options) { - var value = metadata.Value; - var exception = metadata.Exception; - - if (exception != null) + return context.Map(stringValue => { - return Task.FromResult(AssertionResult.Failed($"threw {exception.GetType().Name}")); - } + // Validate the regex pattern first (by creating a Regex object if we don't have one) + // This ensures RegexParseException is thrown before ArgumentNullException for invalid patterns + var regexObj = regex ?? new Regex(pattern, options); - // Validate the regex pattern first (by creating a Regex object if we don't have one) - // This ensures RegexParseException is thrown before ArgumentNullException for invalid patterns - var regex = _regex ?? new Regex(_pattern, _options); + // Now check if value is null and throw ArgumentNullException + if (stringValue == null) + { + throw new ArgumentNullException(nameof(stringValue), "value was null"); + } - // Now check if value is null and throw ArgumentNullException - if (value == null) - { - throw new ArgumentNullException(nameof(value), "value was null"); - } + // Perform the matches + var matches = regexObj.Matches(stringValue); - // Use the validated regex to check the match - bool isMatch = regex.IsMatch(value); + if (matches.Count == 0) + { + throw new InvalidOperationException($"The regex \"{pattern}\" does not match with \"{stringValue}\""); + } - if (isMatch) + return new RegexMatchCollection(matches); + }); + } + + protected override Task CheckAsync(EvaluationMetadata metadata) + { + var value = metadata.Value; + var exception = metadata.Exception; + + if (exception != null) { - return Task.FromResult(AssertionResult.Passed); + // Check what type of exception it is + if (exception is InvalidOperationException) + { + return Task.FromResult(AssertionResult.Failed(exception.Message)); + } + // Rethrow native exceptions (ArgumentNullException, RegexParseException, RegexMatchTimeoutException) + // so they can be tested with .Throws() + throw exception; } - return Task.FromResult(AssertionResult.Failed($"The regex \"{_pattern}\" does not match with \"{value}\"")); + // If we have a RegexMatchCollection, at least one match succeeded + return Task.FromResult(AssertionResult.Passed); } protected override string GetExpectation() diff --git a/TUnit.Assertions/Conditions/StringEqualsAssertion.cs b/TUnit.Assertions/Conditions/StringEqualsAssertion.cs index 973e69f6a6..0c29255d19 100644 --- a/TUnit.Assertions/Conditions/StringEqualsAssertion.cs +++ b/TUnit.Assertions/Conditions/StringEqualsAssertion.cs @@ -13,9 +13,9 @@ public class StringEqualsAssertion : Assertion { private readonly string? _expected; private StringComparison _comparison = StringComparison.Ordinal; - private bool _trimming = false; - private bool _nullAndEmptyEquality = false; - private bool _ignoringWhitespace = false; + private bool _trimming; + private bool _nullAndEmptyEquality; + private bool _ignoringWhitespace; public StringEqualsAssertion( AssertionContext context, @@ -25,6 +25,16 @@ public StringEqualsAssertion( _expected = expected; } + public StringEqualsAssertion( + AssertionContext context, + string? expected, + StringComparison comparison) + : base(context) + { + _expected = expected; + _comparison = comparison; + } + /// /// Makes the comparison case-insensitive. /// diff --git a/TUnit.Assertions/Conditions/ValueTaskAssertionExtensions.cs b/TUnit.Assertions/Conditions/ValueTaskAssertionExtensions.cs new file mode 100644 index 0000000000..dee08ce995 --- /dev/null +++ b/TUnit.Assertions/Conditions/ValueTaskAssertionExtensions.cs @@ -0,0 +1,22 @@ +using TUnit.Assertions.Attributes; + +namespace TUnit.Assertions.Conditions; + +/// +/// Source-generated assertions for ValueTask type using [AssertionFrom<ValueTask>] attributes. +/// Each assertion wraps a property from the ValueTask structure. +/// +[AssertionFrom(nameof(ValueTask.IsCompleted), ExpectationMessage = "be completed")] +[AssertionFrom(nameof(ValueTask.IsCompleted), CustomName = "IsNotCompleted", NegateLogic = true, ExpectationMessage = "be completed")] + +[AssertionFrom(nameof(ValueTask.IsCanceled), ExpectationMessage = "be canceled")] +[AssertionFrom(nameof(ValueTask.IsCanceled), CustomName = "IsNotCanceled", NegateLogic = true, ExpectationMessage = "be canceled")] + +[AssertionFrom(nameof(ValueTask.IsFaulted), ExpectationMessage = "be faulted")] +[AssertionFrom(nameof(ValueTask.IsFaulted), CustomName = "IsNotFaulted", NegateLogic = true, ExpectationMessage = "be faulted")] + +[AssertionFrom(nameof(ValueTask.IsCompletedSuccessfully), ExpectationMessage = "be completed successfully")] +[AssertionFrom(nameof(ValueTask.IsCompletedSuccessfully), CustomName = "IsNotCompletedSuccessfully", NegateLogic = true, ExpectationMessage = "be completed successfully")] +public static partial class ValueTaskAssertionExtensions +{ +} diff --git a/TUnit.Assertions/Conditions/WaitsForAssertion.cs b/TUnit.Assertions/Conditions/WaitsForAssertion.cs new file mode 100644 index 0000000000..3629d2a297 --- /dev/null +++ b/TUnit.Assertions/Conditions/WaitsForAssertion.cs @@ -0,0 +1,113 @@ +using System.Diagnostics; +using TUnit.Assertions.Core; +using TUnit.Assertions.Exceptions; +using TUnit.Assertions.Sources; + +namespace TUnit.Assertions.Conditions; + +/// +/// Asserts that an assertion passes within a specified timeout by polling repeatedly. +/// Useful for testing asynchronous or event-driven code where state changes take time to propagate. +/// +/// The type of value being asserted +public class WaitsForAssertion : Assertion +{ + private readonly Func, Assertion> _assertionBuilder; + private readonly TimeSpan _timeout; + private readonly TimeSpan _pollingInterval; + + public WaitsForAssertion( + AssertionContext context, + Func, Assertion> assertionBuilder, + TimeSpan timeout, + TimeSpan? pollingInterval = null) + : base(context) + { + _assertionBuilder = assertionBuilder ?? throw new ArgumentNullException(nameof(assertionBuilder)); + _timeout = timeout; + _pollingInterval = pollingInterval ?? TimeSpan.FromMilliseconds(10); + + if (_timeout <= TimeSpan.Zero) + { + throw new ArgumentException("Timeout must be positive", nameof(timeout)); + } + + if (_pollingInterval <= TimeSpan.Zero) + { + throw new ArgumentException("Polling interval must be positive", nameof(pollingInterval)); + } + } + + protected override async Task CheckAsync(EvaluationMetadata metadata) + { + var stopwatch = Stopwatch.StartNew(); + Exception? lastException = null; + var attemptCount = 0; + + using var cts = new CancellationTokenSource(_timeout); + + while (stopwatch.Elapsed < _timeout) + { + attemptCount++; + + try + { + var (currentValue, currentException) = await Context.Evaluation.ReevaluateAsync(); + var assertionSource = new ValueAssertion(currentValue, "polled value"); + var assertion = _assertionBuilder(assertionSource); + await assertion.AssertAsync(); + + return AssertionResult.Passed; + } + catch (AssertionException ex) + { + lastException = ex; + + // Check if we've exceeded timeout before waiting + if (stopwatch.Elapsed + _pollingInterval >= _timeout) + { + break; + } + + try + { + await Task.Delay(_pollingInterval, cts.Token); + } + catch (OperationCanceledException) + { + break; + } + } + } + + stopwatch.Stop(); + + var lastErrorMessage = lastException != null + ? $"Last error: {ExtractAssertionMessage(lastException)}" + : "No attempts were made"; + + return AssertionResult.Failed( + $"assertion did not pass within {_timeout.TotalMilliseconds:F0}ms after {attemptCount} attempts. {lastErrorMessage}"); + } + + protected override string GetExpectation() => + $"assertion to pass within {_timeout.TotalMilliseconds:F0} milliseconds " + + $"(polling every {_pollingInterval.TotalMilliseconds:F0}ms)"; + + /// + /// Extracts the core assertion message from an exception, + /// removing the stack trace and location info for cleaner output. + /// + private static string ExtractAssertionMessage(Exception exception) + { + var message = exception.Message; + var atIndex = message.IndexOf("\nat Assert.That", StringComparison.Ordinal); + + if (atIndex > 0) + { + message = message.Substring(0, atIndex).Trim(); + } + + return message; + } +} diff --git a/TUnit.Assertions/Core/Assertion.cs b/TUnit.Assertions/Core/Assertion.cs index 7efd8f0019..a79e213396 100644 --- a/TUnit.Assertions/Core/Assertion.cs +++ b/TUnit.Assertions/Core/Assertion.cs @@ -52,7 +52,6 @@ protected Assertion(AssertionContext context) var (previous, combiner) = context.ConsumePendingLink(); if (previous != null) { - // Create wrapper based on combiner type _wrappedExecution = combiner == CombinerType.And ? new Chaining.AndAssertion(previous, this) : new Chaining.OrAssertion(previous, this); diff --git a/TUnit.Assertions/Core/EvaluationContext.cs b/TUnit.Assertions/Core/EvaluationContext.cs index 93beef0113..94c9432fff 100644 --- a/TUnit.Assertions/Core/EvaluationContext.cs +++ b/TUnit.Assertions/Core/EvaluationContext.cs @@ -49,6 +49,32 @@ public EvaluationContext(TValue? value) return (_value, _exception); } + /// + /// Re-evaluates the source by bypassing the cache and invoking the evaluator again. + /// Used by polling assertions like WaitsFor that need to observe changing values. + /// For immediate values (created without an evaluator), returns the cached value. + /// + /// The freshly evaluated value and any exception that occurred + public async Task<(TValue? Value, Exception? Exception)> ReevaluateAsync() + { + if (_evaluator == null) + { + return (_value, _exception); + } + + var startTime = DateTimeOffset.Now; + var (value, exception) = await _evaluator(); + var endTime = DateTimeOffset.Now; + + _value = value; + _exception = exception; + _startTime = startTime; + _endTime = endTime; + _evaluated = true; + + return (value, exception); + } + /// /// Creates a derived context by mapping the value to a different type. /// Used for type transformations like IsTypeOf<T>(). diff --git a/TUnit.Assertions/Extensions/Assert.cs b/TUnit.Assertions/Extensions/Assert.cs index 6b9d5119fb..2e4a731f2e 100644 --- a/TUnit.Assertions/Extensions/Assert.cs +++ b/TUnit.Assertions/Extensions/Assert.cs @@ -111,14 +111,23 @@ public static AsyncFuncAssertion That( /// /// Creates an assertion for a Task that returns a value. /// Supports both result assertions (e.g., IsEqualTo) and task state assertions (e.g., IsCompleted). + /// This method accepts both nullable and non-nullable Task results seamlessly. /// Example: await Assert.That(GetValueAsync()).IsEqualTo(expected); + /// Example: await Assert.That(Task.FromResult(value)).IsEqualTo(expected); /// Example: await Assert.That(GetValueAsync()).IsCompleted(); /// public static TaskAssertion That( - Task task, + Task task, [CallerArgumentExpression(nameof(task))] string? expression = null) { - return new TaskAssertion(task, expression); + var nullableTask = ConvertToNullableTask(task); + return new TaskAssertion(nullableTask, expression); + + static async Task ConvertToNullableTask(Task sourceTask) + { + var result = await sourceTask.ConfigureAwait(false); + return result; + } } /// @@ -192,7 +201,7 @@ public static TException Throws(Action action) action(); throw new AssertionException($"Expected {typeof(TException).Name} but no exception was thrown"); } - catch (TException ex) when (ex is not AssertionException) + catch (TException ex) when (typeof(AssertionException).IsAssignableFrom(typeof(TException)) || ex is not AssertionException) { return ex; } @@ -219,7 +228,7 @@ public static Exception Throws(Type exceptionType, Action action) action(); throw new AssertionException($"Expected {exceptionType.Name} but no exception was thrown"); } - catch (Exception ex) when (exceptionType.IsInstanceOfType(ex) && ex is not AssertionException) + catch (Exception ex) when (exceptionType.IsInstanceOfType(ex) && (typeof(AssertionException).IsAssignableFrom(exceptionType) || ex is not AssertionException)) { return ex; } @@ -358,4 +367,79 @@ public static ExceptionParameterNameAssertion ThrowsExactlyAsync(parameterName); } + + /// + /// Asserts that a value is not null (for reference types). + /// This method properly updates null-state flow analysis, allowing the compiler to treat the value as non-null after this assertion. + /// Unlike Assert.That(x).IsNotNull() (fluent API), this method changes the compiler's null-state tracking. + /// Example: Assert.NotNull(myString); // After this, myString is treated as non-null + /// + /// The value to check for null + /// The expression being asserted (captured automatically) + /// Thrown if the value is null + public static void NotNull( + [NotNull] T? value, + [CallerArgumentExpression(nameof(value))] string? expression = null) + where T : class + { + if (value is null) + { + throw new AssertionException($"Expected {expression ?? "value"} to not be null, but it was null"); + } + } + + /// + /// Asserts that a nullable value type is not null. + /// This method properly updates null-state flow analysis, allowing the compiler to treat the value as non-null after this assertion. + /// Example: Assert.NotNull(myNullableInt); // After this, myNullableInt is treated as having a value + /// + /// The nullable value to check + /// The expression being asserted (captured automatically) + /// Thrown if the value is null + public static void NotNull( + [NotNull] T? value, + [CallerArgumentExpression(nameof(value))] string? expression = null) + where T : struct + { + if (!value.HasValue) + { + throw new AssertionException($"Expected {expression ?? "value"} to not be null, but it was null"); + } + } + + /// + /// Asserts that a value is null (for reference types). + /// Example: Assert.Null(myString); + /// + /// The value to check for null + /// The expression being asserted (captured automatically) + /// Thrown if the value is not null + public static void Null( + T? value, + [CallerArgumentExpression(nameof(value))] string? expression = null) + where T : class + { + if (value is not null) + { + throw new AssertionException($"Expected {expression ?? "value"} to be null, but it was {value}"); + } + } + + /// + /// Asserts that a nullable value type is null. + /// Example: Assert.Null(myNullableInt); + /// + /// The nullable value to check + /// The expression being asserted (captured automatically) + /// Thrown if the value is not null + public static void Null( + T? value, + [CallerArgumentExpression(nameof(value))] string? expression = null) + where T : struct + { + if (value.HasValue) + { + throw new AssertionException($"Expected {expression ?? "value"} to be null, but it was {value.Value}"); + } + } } diff --git a/TUnit.Assertions/Extensions/AssertionExtensions.cs b/TUnit.Assertions/Extensions/AssertionExtensions.cs index 487243a262..a902bdc7aa 100644 --- a/TUnit.Assertions/Extensions/AssertionExtensions.cs +++ b/TUnit.Assertions/Extensions/AssertionExtensions.cs @@ -75,21 +75,6 @@ public static EqualsAssertion EqualTo( return new EqualsAssertion(source.Context, expected); } - /// - /// Asserts that the string is equal to the expected value using the specified comparison. - /// Uses .WithComparison() since StringEqualsAssertion doesn't have a constructor for this. - /// - public static StringEqualsAssertion IsEqualTo( - this IAssertionSource source, - string? expected, - StringComparison comparison, - [CallerArgumentExpression(nameof(expected))] string? expression = null) - { - source.Context.ExpressionBuilder.Append($".IsEqualTo({expression}, {comparison})"); - var assertion = new StringEqualsAssertion(source.Context, expected); - return assertion.WithComparison(comparison); - } - /// /// Asserts that the numeric value is greater than zero (positive). /// @@ -208,7 +193,6 @@ public static MemberAssertionResult Member combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -261,7 +245,6 @@ public static MemberAssertionResult Member( // If there was a pending link, wrap both assertions together if (pendingAssertion != null && combinerType != null) { - // Create a combined wrapper that executes the pending assertion first (or together for Or) Assertion combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -369,7 +352,6 @@ public static MemberAssertionResult Member combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -422,7 +404,6 @@ public static MemberAssertionResult Member( // If there was a pending link, wrap both assertions together if (pendingAssertion != null && combinerType != null) { - // Create a combined wrapper that executes the pending assertion first (or together for Or) Assertion combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -530,7 +511,6 @@ public static MemberAssertionResult Member combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -582,7 +562,6 @@ public static MemberAssertionResult Member( // If there was a pending link, wrap both assertions together if (pendingAssertion != null && combinerType != null) { - // Create a combined wrapper that executes the pending assertion first (or together for Or) Assertion combinedAssertion = combinerType == CombinerType.And ? new CombinedAndAssertion(parentContext, pendingAssertion, erasedAssertion) : new CombinedOrAssertion(parentContext, pendingAssertion, erasedAssertion); @@ -759,16 +738,22 @@ public static NotStructuralEquivalencyAssertion IsNotEquivalentTo - /// Asserts that the value satisfies the specified predicate. - /// Example: await Assert.That(x).Satisfies(v => v > 0 && v < 100); + /// Asserts that a mapped Task value satisfies custom assertions on the unwrapped result. + /// Maps the source value using a selector that returns a Task, then runs assertions on the awaited result. + /// Example: await Assert.That(model).Satisfies(m => m.AsyncValue, assert => assert.IsEqualTo("Hello")); /// - public static SatisfiesAssertion Satisfies( + public static AsyncMappedSatisfiesAssertion Satisfies( this IAssertionSource source, - Func predicate, - [CallerArgumentExpression(nameof(predicate))] string? expression = null) + Func> selector, + Func, Assertion> assertions, + [CallerArgumentExpression(nameof(selector))] string? selectorExpression = null) { - source.Context.ExpressionBuilder.Append($".Satisfies({expression})"); - return new SatisfiesAssertion(source.Context, predicate, expression ?? "predicate"); + source.Context.ExpressionBuilder.Append($".Satisfies({selectorExpression}, ...)"); + return new AsyncMappedSatisfiesAssertion( + source.Context, + selector!, + assertions, + selectorExpression ?? "selector"); } /// @@ -791,46 +776,16 @@ public static MappedSatisfiesAssertion Satisfies - /// Asserts that an async-mapped value satisfies custom assertions. - /// Maps the source value using an async selector, then runs assertions on the mapped value. - /// Example: await Assert.That(model).Satisfies(m => m.GetNameAsync(), assert => assert.IsEqualTo("John")); - /// - public static AsyncMappedSatisfiesAssertion Satisfies( - this IAssertionSource source, - Func> selector, - Func, Assertion?> assertions, - [CallerArgumentExpression(nameof(selector))] string? selectorExpression = null) - { - source.Context.ExpressionBuilder.Append($".Satisfies({selectorExpression}, ...)"); - return new AsyncMappedSatisfiesAssertion( - source.Context, - selector, - assertions, - selectorExpression ?? "selector"); - } - - /// - /// Asserts that the value is in the specified collection (params array convenience method). - /// Example: await Assert.That(5).IsIn(1, 3, 5, 7, 9); - /// - public static IsInAssertion IsIn( - this IAssertionSource source, - params TValue[] collection) - { - source.Context.ExpressionBuilder.Append($".IsIn({string.Join(", ", collection)})"); - return new IsInAssertion(source.Context, collection); - } - - /// - /// Asserts that the value is NOT in the specified collection (params array convenience method). - /// Example: await Assert.That(4).IsNotIn(1, 3, 5, 7, 9); + /// Asserts that the value satisfies the specified predicate. + /// Example: await Assert.That(x).Satisfies(v => v > 0 && v < 100); /// - public static IsNotInAssertion IsNotIn( + public static SatisfiesAssertion Satisfies( this IAssertionSource source, - params TValue[] collection) + Func predicate, + [CallerArgumentExpression(nameof(predicate))] string? expression = null) { - source.Context.ExpressionBuilder.Append($".IsNotIn({string.Join(", ", collection)})"); - return new IsNotInAssertion(source.Context, collection); + source.Context.ExpressionBuilder.Append($".Satisfies({expression})"); + return new SatisfiesAssertion(source.Context, predicate, expression ?? "predicate"); } /// @@ -1408,6 +1363,33 @@ public static CompletesWithinAsyncAssertion CompletesWithin( return new CompletesWithinAsyncAssertion(asyncAction, timeout); } + /// + /// Asserts that an assertion passes within the specified timeout by polling repeatedly. + /// The assertion builder is invoked on each polling attempt until it passes or the timeout expires. + /// Useful for testing asynchronous or event-driven code where state changes take time to propagate. + /// Example: await Assert.That(value).WaitsFor(assert => assert.IsEqualTo(2), timeout: TimeSpan.FromSeconds(5)); + /// + /// The type of value being asserted + /// The assertion source + /// A function that builds the assertion to be evaluated on each poll + /// The maximum time to wait for the assertion to pass + /// The interval between polling attempts (defaults to 10ms if not specified) + /// Captured expression for the timeout parameter + /// Captured expression for the polling interval parameter + /// An assertion that can be awaited or chained with And/Or + public static WaitsForAssertion WaitsFor( + this IAssertionSource source, + Func, Assertion> assertionBuilder, + TimeSpan timeout, + TimeSpan? pollingInterval = null, + [CallerArgumentExpression(nameof(timeout))] string? timeoutExpression = null, + [CallerArgumentExpression(nameof(pollingInterval))] string? pollingIntervalExpression = null) + { + var intervalExpr = pollingInterval.HasValue ? $", pollingInterval: {pollingIntervalExpression}" : ""; + source.Context.ExpressionBuilder.Append($".WaitsFor(..., timeout: {timeoutExpression}{intervalExpr})"); + return new WaitsForAssertion(source.Context, assertionBuilder, timeout, pollingInterval); + } + private static Action GetActionFromDelegate(DelegateAssertion source) { return source.Action; diff --git a/TUnit.Assertions/Sources/AsyncDelegateAssertion.cs b/TUnit.Assertions/Sources/AsyncDelegateAssertion.cs index 6147ea3e3f..17b03c5b48 100644 --- a/TUnit.Assertions/Sources/AsyncDelegateAssertion.cs +++ b/TUnit.Assertions/Sources/AsyncDelegateAssertion.cs @@ -40,13 +40,11 @@ public AsyncDelegateAssertion(Func action, string? expression) }); Context = new AssertionContext(evaluationContext, expressionBuilder); - // Create a TaskContext for Task-specific assertions // DO NOT await the task here - we want to check its state synchronously var taskExpressionBuilder = new StringBuilder(); taskExpressionBuilder.Append(expressionBuilder.ToString()); var taskEvaluationContext = new EvaluationContext(() => { - // Return the task object itself without awaiting it // This allows IsCompleted, IsCanceled, IsFaulted, etc. to check task properties synchronously var task = action(); return Task.FromResult<(Task?, Exception?)>((task, null)); @@ -177,7 +175,6 @@ public ThrowsExactlyAssertion ThrowsExactly() where TExc Context.ExpressionBuilder.Append($".Throws({exceptionType.Name})"); // Delegate to the generic Throws() and add runtime type checking var assertion = Throws(); - // Return the assertion with runtime type filtering applied return assertion.WithExceptionType(exceptionType); } diff --git a/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete1.verified.txt b/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete1.verified.txt index e460936b0e..c42ddeb5f0 100644 --- a/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete1.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete1.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute() @@ -34,7 +34,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1)), Name = "ConcreteClass1", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,9 +56,16 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass1(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,11 +73,11 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T yield break; } } -internal static class ConcreteClass1_AssertClassName_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new ConcreteClass1_AssertClassName_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete2.verified.txt b/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete2.verified.txt index d707fe70a3..fdd9b1edda 100644 --- a/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete2.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AbstractTests.Concrete2.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "SecondTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -35,7 +35,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SecondTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource()); } } @@ -85,7 +92,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -117,7 +124,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -125,7 +132,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -139,91 +146,16 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class ConcreteClass2_AssertClassName_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_AssertClassName_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "SecondTest", - TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TestMethodName = "SecondTest", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.InheritsTestsAttribute() - ], - DataSources = global::System.Array.Empty(), - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 3, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "SecondTest", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + try { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "ConcreteClass2", - Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -231,12 +163,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource()); } } @@ -248,7 +180,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -258,7 +190,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute() @@ -279,7 +211,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -287,7 +219,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1)), Name = "ConcreteClass1", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -301,9 +233,16 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass1(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -311,11 +250,11 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T yield break; } } -internal static class ConcreteClass1_AssertClassName_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new ConcreteClass1_AssertClassName_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AfterAllTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AfterAllTests.Test.verified.txt index 6bdfb18c72..35dae8961b 100644 --- a/TUnit.Core.SourceGenerator.Tests/AfterAllTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AfterAllTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AfterTests_CleanupTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In TestClassType = typeof(global::TUnit.TestProject.AfterTests.CleanupTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.CleanupTests)), Name = "CleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,9 +55,16 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AfterTests.CleanupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -65,12 +72,12 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In yield break; } } -internal static class CleanupTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_AfterTests_CleanupTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new CleanupTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new TUnit_TestProject_AfterTests_CleanupTests_Test1_TestSource()); } } @@ -82,7 +89,7 @@ internal static class CleanupTests_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AfterTests_CleanupTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -92,7 +99,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In TestClassType = typeof(global::TUnit.TestProject.AfterTests.CleanupTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -112,7 +119,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -120,7 +127,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.CleanupTests)), Name = "CleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -134,9 +141,16 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AfterTests.CleanupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -144,11 +158,11 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In yield break; } } -internal static class CleanupTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_AfterTests_CleanupTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new CleanupTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new TUnit_TestProject_AfterTests_CleanupTests_Test2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AfterTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AfterTests.Test.verified.txt index 6bdfb18c72..35dae8961b 100644 --- a/TUnit.Core.SourceGenerator.Tests/AfterTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AfterTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AfterTests_CleanupTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In TestClassType = typeof(global::TUnit.TestProject.AfterTests.CleanupTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.CleanupTests)), Name = "CleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,9 +55,16 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AfterTests.CleanupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -65,12 +72,12 @@ internal sealed class CleanupTests_Test1_TestSource_GUID : global::TUnit.Core.In yield break; } } -internal static class CleanupTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_AfterTests_CleanupTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new CleanupTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new TUnit_TestProject_AfterTests_CleanupTests_Test1_TestSource()); } } @@ -82,7 +89,7 @@ internal static class CleanupTests_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AfterTests_CleanupTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -92,7 +99,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In TestClassType = typeof(global::TUnit.TestProject.AfterTests.CleanupTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -112,7 +119,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.CleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -120,7 +127,7 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.CleanupTests)), Name = "CleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -134,9 +141,16 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AfterTests.CleanupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -144,11 +158,11 @@ internal sealed class CleanupTests_Test2_TestSource_GUID : global::TUnit.Core.In yield break; } } -internal static class CleanupTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_AfterTests_CleanupTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new CleanupTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AfterTests.CleanupTests), new TUnit_TestProject_AfterTests_CleanupTests_Test2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt b/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt deleted file mode 100644 index 427afed554..0000000000 --- a/TUnit.Core.SourceGenerator.Tests/AotConverterGeneratorTests.GeneratesCode.verified.txt +++ /dev/null @@ -1,1270 +0,0 @@ -// -#pragma warning disable - -#nullable enable -using System; -using TUnit.Core.Converters; -namespace TUnit.Generated; -internal sealed class AotConverter_0 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource1); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource1 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_1 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource2); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource2 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_2 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource3); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTests.DataSource3 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_3 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource1); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource1 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_4 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource2); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource2 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_5 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource3); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.AllDataSourcesCombinedTestsVerification.DataSource3 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_6 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ArgumentsWithClassDataSourceTests.IntDataSource1); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ArgumentsWithClassDataSourceTests.IntDataSource1 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_7 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ArgumentsWithClassDataSourceTests.IntDataSource2); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ArgumentsWithClassDataSourceTests.IntDataSource2 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_8 : IAotConverter -{ - public Type SourceType => typeof(int); - public Type TargetType => typeof(global::TUnit.TestProject.ExplicitInteger); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.ExplicitInteger targetTypedValue) - { - return targetTypedValue; - } - if (value is int sourceTypedValue) - { - return (global::TUnit.TestProject.ExplicitInteger)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_9 : IAotConverter -{ - public Type SourceType => typeof(int); - public Type TargetType => typeof(global::TUnit.TestProject.ImplicitInteger); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.ImplicitInteger targetTypedValue) - { - return targetTypedValue; - } - if (value is int sourceTypedValue) - { - return (global::TUnit.TestProject.ImplicitInteger)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_10 : IAotConverter -{ - public Type SourceType => typeof(byte); - public Type TargetType => typeof(byte?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is byte targetTypedValue) - { - return targetTypedValue; - } - if (value is byte sourceTypedValue) - { - return (byte?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_11 : IAotConverter -{ - public Type SourceType => typeof(byte?); - public Type TargetType => typeof(byte); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is byte targetTypedValue) - { - return targetTypedValue; - } - if (value is byte sourceTypedValue) - { - return (byte)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_12 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ClassDataSourceEnumerableTest.EnumerableDataSource); - public Type TargetType => typeof(string); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is string targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ClassDataSourceEnumerableTest.EnumerableDataSource sourceTypedValue) - { - return (string)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_13 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource1); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource1 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_14 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource2); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource2 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_15 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource3); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ClassDataSourceWithMethodDataSourceTests.DataSource3 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_16 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.ComprehensiveCountTest.ClassData); - public Type TargetType => typeof(string); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is string targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.ComprehensiveCountTest.ClassData sourceTypedValue) - { - return (string)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_17 : IAotConverter -{ - public Type SourceType => typeof(bool); - public Type TargetType => typeof(bool?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is bool targetTypedValue) - { - return targetTypedValue; - } - if (value is bool sourceTypedValue) - { - return (bool?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_18 : IAotConverter -{ - public Type SourceType => typeof(bool?); - public Type TargetType => typeof(bool); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is bool targetTypedValue) - { - return targetTypedValue; - } - if (value is bool sourceTypedValue) - { - return (bool)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_19 : IAotConverter -{ - public Type SourceType => typeof(byte); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is byte sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_20 : IAotConverter -{ - public Type SourceType => typeof(sbyte); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is sbyte sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_21 : IAotConverter -{ - public Type SourceType => typeof(short); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is short sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_22 : IAotConverter -{ - public Type SourceType => typeof(ushort); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is ushort sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_23 : IAotConverter -{ - public Type SourceType => typeof(char); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is char sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_24 : IAotConverter -{ - public Type SourceType => typeof(int); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is int sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_25 : IAotConverter -{ - public Type SourceType => typeof(uint); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is uint sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_26 : IAotConverter -{ - public Type SourceType => typeof(long); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is long sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_27 : IAotConverter -{ - public Type SourceType => typeof(ulong); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is ulong sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_28 : IAotConverter -{ - public Type SourceType => typeof(float); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is float sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_29 : IAotConverter -{ - public Type SourceType => typeof(double); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is double sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_30 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(byte); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is byte targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (byte)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_31 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(sbyte); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is sbyte targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (sbyte)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_32 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(char); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is char targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (char)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_33 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(short); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is short targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (short)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_34 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(ushort); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is ushort targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (ushort)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_35 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_36 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(uint); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is uint targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (uint)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_37 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(long); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is long targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (long)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_38 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(ulong); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is ulong targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (ulong)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_39 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(float); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is float targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (float)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_40 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(double); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is double targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (double)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_41 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.TestEnum); - public Type TargetType => typeof(global::TUnit.TestProject.TestEnum?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.TestEnum targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.TestEnum sourceTypedValue) - { - return (global::TUnit.TestProject.TestEnum?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_42 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.TestEnum?); - public Type TargetType => typeof(global::TUnit.TestProject.TestEnum); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.TestEnum targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.TestEnum sourceTypedValue) - { - return (global::TUnit.TestProject.TestEnum)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_43 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedDataSourceBugTest.ClassData1); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedDataSourceBugTest.ClassData1 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_44 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedDataSourceBugTest.ClassData2); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedDataSourceBugTest.ClassData2 sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_45 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum4); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum4 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion1)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_46 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum4); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum4 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTests.Enum4)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_47 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum5); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum5 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion1)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_48 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum5); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum5 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTests.Enum5)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_49 : IAotConverter -{ - public Type SourceType => typeof(string); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 targetTypedValue) - { - return targetTypedValue; - } - if (value is string sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion1)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_50 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion1); - public Type TargetType => typeof(string); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is string targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion1 sourceTypedValue) - { - return (string)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_51 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum4); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum4 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion2)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_52 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum4); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum4 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTests.Enum4)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_53 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum5); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum5 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion2)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_54 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTests.Enum5); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTests.Enum5 targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTests.Enum5)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_55 : IAotConverter -{ - public Type SourceType => typeof(string); - public Type TargetType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 targetTypedValue) - { - return targetTypedValue; - } - if (value is string sourceTypedValue) - { - return (global::TUnit.TestProject.MixedMatrixTestsUnion2)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_56 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.MixedMatrixTestsUnion2); - public Type TargetType => typeof(string); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is string targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.MixedMatrixTestsUnion2 sourceTypedValue) - { - return (string)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_57 : IAotConverter -{ - public Type SourceType => typeof(decimal); - public Type TargetType => typeof(decimal?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (decimal?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_58 : IAotConverter -{ - public Type SourceType => typeof(decimal?); - public Type TargetType => typeof(decimal); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is decimal targetTypedValue) - { - return targetTypedValue; - } - if (value is decimal sourceTypedValue) - { - return (decimal)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_59 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.TestCountVerificationTests.TestDataSource); - public Type TargetType => typeof(int); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is int targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.TestCountVerificationTests.TestDataSource sourceTypedValue) - { - return (int)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_60 : IAotConverter -{ - public Type SourceType => typeof(int); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._2757.Foo); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._2757.Foo targetTypedValue) - { - return targetTypedValue; - } - if (value is int sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._2757.Foo)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_61 : IAotConverter -{ - public Type SourceType => typeof(global::System.ValueTuple); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._2798.Foo); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._2798.Foo targetTypedValue) - { - return targetTypedValue; - } - if (value is global::System.ValueTuple sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._2798.Foo)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_62 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.Bugs._3185.FlagMock); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._3185.FlagMock?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._3185.FlagMock targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.Bugs._3185.FlagMock sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._3185.FlagMock?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_63 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.Bugs._3185.FlagMock?); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._3185.FlagMock); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._3185.FlagMock targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.Bugs._3185.FlagMock sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._3185.FlagMock)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_64 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.Bugs._3185.RegularEnum); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._3185.RegularEnum?); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._3185.RegularEnum targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.Bugs._3185.RegularEnum sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._3185.RegularEnum?)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal sealed class AotConverter_65 : IAotConverter -{ - public Type SourceType => typeof(global::TUnit.TestProject.Bugs._3185.RegularEnum?); - public Type TargetType => typeof(global::TUnit.TestProject.Bugs._3185.RegularEnum); - public object? Convert(object? value) - { - if (value == null) return null; - if (value is global::TUnit.TestProject.Bugs._3185.RegularEnum targetTypedValue) - { - return targetTypedValue; - } - if (value is global::TUnit.TestProject.Bugs._3185.RegularEnum sourceTypedValue) - { - return (global::TUnit.TestProject.Bugs._3185.RegularEnum)sourceTypedValue; - } - return value; // Return original value if type doesn't match - } -} -internal static class AotConverterRegistration -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA2255:The 'ModuleInitializer' attribute should not be used in libraries", - Justification = "Test framework needs to register AOT converters for conversion operators")] - public static void Initialize() - { - AotConverterRegistry.Register(new AotConverter_0()); - AotConverterRegistry.Register(new AotConverter_1()); - AotConverterRegistry.Register(new AotConverter_2()); - AotConverterRegistry.Register(new AotConverter_3()); - AotConverterRegistry.Register(new AotConverter_4()); - AotConverterRegistry.Register(new AotConverter_5()); - AotConverterRegistry.Register(new AotConverter_6()); - AotConverterRegistry.Register(new AotConverter_7()); - AotConverterRegistry.Register(new AotConverter_8()); - AotConverterRegistry.Register(new AotConverter_9()); - AotConverterRegistry.Register(new AotConverter_10()); - AotConverterRegistry.Register(new AotConverter_11()); - AotConverterRegistry.Register(new AotConverter_12()); - AotConverterRegistry.Register(new AotConverter_13()); - AotConverterRegistry.Register(new AotConverter_14()); - AotConverterRegistry.Register(new AotConverter_15()); - AotConverterRegistry.Register(new AotConverter_16()); - AotConverterRegistry.Register(new AotConverter_17()); - AotConverterRegistry.Register(new AotConverter_18()); - AotConverterRegistry.Register(new AotConverter_19()); - AotConverterRegistry.Register(new AotConverter_20()); - AotConverterRegistry.Register(new AotConverter_21()); - AotConverterRegistry.Register(new AotConverter_22()); - AotConverterRegistry.Register(new AotConverter_23()); - AotConverterRegistry.Register(new AotConverter_24()); - AotConverterRegistry.Register(new AotConverter_25()); - AotConverterRegistry.Register(new AotConverter_26()); - AotConverterRegistry.Register(new AotConverter_27()); - AotConverterRegistry.Register(new AotConverter_28()); - AotConverterRegistry.Register(new AotConverter_29()); - AotConverterRegistry.Register(new AotConverter_30()); - AotConverterRegistry.Register(new AotConverter_31()); - AotConverterRegistry.Register(new AotConverter_32()); - AotConverterRegistry.Register(new AotConverter_33()); - AotConverterRegistry.Register(new AotConverter_34()); - AotConverterRegistry.Register(new AotConverter_35()); - AotConverterRegistry.Register(new AotConverter_36()); - AotConverterRegistry.Register(new AotConverter_37()); - AotConverterRegistry.Register(new AotConverter_38()); - AotConverterRegistry.Register(new AotConverter_39()); - AotConverterRegistry.Register(new AotConverter_40()); - AotConverterRegistry.Register(new AotConverter_41()); - AotConverterRegistry.Register(new AotConverter_42()); - AotConverterRegistry.Register(new AotConverter_43()); - AotConverterRegistry.Register(new AotConverter_44()); - AotConverterRegistry.Register(new AotConverter_45()); - AotConverterRegistry.Register(new AotConverter_46()); - AotConverterRegistry.Register(new AotConverter_47()); - AotConverterRegistry.Register(new AotConverter_48()); - AotConverterRegistry.Register(new AotConverter_49()); - AotConverterRegistry.Register(new AotConverter_50()); - AotConverterRegistry.Register(new AotConverter_51()); - AotConverterRegistry.Register(new AotConverter_52()); - AotConverterRegistry.Register(new AotConverter_53()); - AotConverterRegistry.Register(new AotConverter_54()); - AotConverterRegistry.Register(new AotConverter_55()); - AotConverterRegistry.Register(new AotConverter_56()); - AotConverterRegistry.Register(new AotConverter_57()); - AotConverterRegistry.Register(new AotConverter_58()); - AotConverterRegistry.Register(new AotConverter_59()); - AotConverterRegistry.Register(new AotConverter_60()); - AotConverterRegistry.Register(new AotConverter_61()); - AotConverterRegistry.Register(new AotConverter_62()); - AotConverterRegistry.Register(new AotConverter_63()); - AotConverterRegistry.Register(new AotConverter_64()); - AotConverterRegistry.Register(new AotConverter_65()); - } -} diff --git a/TUnit.Core.SourceGenerator.Tests/ArgsAsArrayTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ArgsAsArrayTests.Test.verified.txt index 2a71df29b3..adcb5e7769 100644 --- a/TUnit.Core.SourceGenerator.Tests/ArgsAsArrayTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ArgsAsArrayTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ArgsAsArrayTests_Params__string___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.ArgsAsArrayTests), TestMethodName = "Params", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -45,7 +45,7 @@ internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Co ReflectionInfo = typeof(global::TUnit.TestProject.ArgsAsArrayTests).GetMethod("Params", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string[]) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -53,7 +53,7 @@ internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ArgsAsArrayTests)), Name = "ArgsAsArrayTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -67,35 +67,41 @@ internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ArgsAsArrayTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 0: - instance.Params(new string[0]); - break; - case 1: - instance.Params((args[0] is null ? null : args[0] is string[] arr ? arr : new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]) })); - break; - case 2: - instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]) }); - break; - case 3: - instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); - break; - case 4: - instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); - break; - case 5: - instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); - break; - case 6: - instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); - break; - default: - throw new global::System.ArgumentException($"Expected between 0 and 1 arguments, but got {args.Length}"); + switch (args.Length) + { + case 0: + instance.Params(new string[0]); + return default(global::System.Threading.Tasks.ValueTask); + case 1: + instance.Params((args[0] is null ? null : args[0] is string[] arr ? arr : new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]) })); + return default(global::System.Threading.Tasks.ValueTask); + case 2: + instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 3: + instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 4: + instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 5: + instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 6: + instance.Params(new string[] { TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected between 0 and 1 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -103,12 +109,12 @@ internal sealed class ArgsAsArrayTests_Params_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class ArgsAsArrayTests_Params_ModuleInitializer_GUID +internal static class TUnit_TestProject_ArgsAsArrayTests_Params__string___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new ArgsAsArrayTests_Params_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new TUnit_TestProject_ArgsAsArrayTests_Params__string___TestSource()); } } @@ -120,7 +126,7 @@ internal static class ArgsAsArrayTests_Params_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ArgsAsArrayTests_ParamsEnumerable__IEnumerable_string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -130,7 +136,7 @@ internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.ArgsAsArrayTests), TestMethodName = "ParamsEnumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -162,7 +168,7 @@ internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global ReflectionInfo = typeof(global::TUnit.TestProject.ArgsAsArrayTests).GetMethod("ParamsEnumerable", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Collections.Generic.IEnumerable) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -170,7 +176,7 @@ internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ArgsAsArrayTests)), Name = "ArgsAsArrayTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -184,35 +190,41 @@ internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ArgsAsArrayTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 0: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 1: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 2: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 3: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 4: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 5: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + case 6: + instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected between 0 and 1 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 0: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 1: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 2: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 3: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 4: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 5: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - case 6: - instance.ParamsEnumerable(TUnit.Core.Helpers.CastHelper.Cast>(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected between 0 and 1 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -220,12 +232,12 @@ internal sealed class ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID : global yield break; } } -internal static class ArgsAsArrayTests_ParamsEnumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_ArgsAsArrayTests_ParamsEnumerable__IEnumerable_string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new ArgsAsArrayTests_ParamsEnumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new TUnit_TestProject_ArgsAsArrayTests_ParamsEnumerable__IEnumerable_string__TestSource()); } } @@ -237,7 +249,7 @@ internal static class ArgsAsArrayTests_ParamsEnumerable_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ArgsAsArrayTests_Following_Non_Params__int_IEnumerable_string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -247,7 +259,7 @@ internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.ArgsAsArrayTests), TestMethodName = "Following_Non_Params", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -286,7 +298,7 @@ internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : gl ReflectionInfo = typeof(global::TUnit.TestProject.ArgsAsArrayTests).GetMethod("Following_Non_Params", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::System.Collections.Generic.IEnumerable) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgsAsArrayTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -294,7 +306,7 @@ internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ArgsAsArrayTests)), Name = "ArgsAsArrayTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -308,35 +320,41 @@ internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ArgsAsArrayTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 2: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 3: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 4: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 5: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 6: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + case 7: + instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 2: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 3: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 4: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 5: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 6: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - case 7: - instance.Following_Non_Params(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast>(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -344,11 +362,11 @@ internal sealed class ArgsAsArrayTests_Following_Non_Params_TestSource_GUID : gl yield break; } } -internal static class ArgsAsArrayTests_Following_Non_Params_ModuleInitializer_GUID +internal static class TUnit_TestProject_ArgsAsArrayTests_Following_Non_Params__int_IEnumerable_string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new ArgsAsArrayTests_Following_Non_Params_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgsAsArrayTests), new TUnit_TestProject_ArgsAsArrayTests_Following_Non_Params__int_IEnumerable_string__TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ArgumentWithImplicitConverterTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ArgumentWithImplicitConverterTests.Test.verified.txt index c8256408ae..e574acda8e 100644 --- a/TUnit.Core.SourceGenerator.Tests/ArgumentWithImplicitConverterTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ArgumentWithImplicitConverterTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ArgumentWithImplicitConverterTests_Explicit__ExplicitInteger_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), TestMethodName = "Explicit", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -48,7 +48,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests).GetMethod("Explicit", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.ExplicitInteger) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgumentWithImplicitConverterTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgumentWithImplicitConverterTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -56,7 +56,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests)), Name = "ArgumentWithImplicitConverterTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -70,17 +70,23 @@ internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ArgumentWithImplicitConverterTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Explicit(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Explicit(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -88,12 +94,12 @@ internal sealed class ArgumentWithImplicitConverterTests_Explicit_TestSource_GUI yield break; } } -internal static class ArgumentWithImplicitConverterTests_Explicit_ModuleInitializer_GUID +internal static class TUnit_TestProject_ArgumentWithImplicitConverterTests_Explicit__ExplicitInteger_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), new ArgumentWithImplicitConverterTests_Explicit_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), new TUnit_TestProject_ArgumentWithImplicitConverterTests_Explicit__ExplicitInteger_TestSource()); } } @@ -105,7 +111,7 @@ internal static class ArgumentWithImplicitConverterTests_Explicit_ModuleInitiali #nullable enable namespace TUnit.Generated; -internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ArgumentWithImplicitConverterTests_Implicit__ImplicitInteger_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -115,7 +121,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), TestMethodName = "Implicit", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -150,7 +156,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests).GetMethod("Implicit", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.ImplicitInteger) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgumentWithImplicitConverterTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ArgumentWithImplicitConverterTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -158,7 +164,7 @@ internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests)), Name = "ArgumentWithImplicitConverterTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -172,17 +178,23 @@ internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ArgumentWithImplicitConverterTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Implicit(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Implicit(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -190,11 +202,11 @@ internal sealed class ArgumentWithImplicitConverterTests_Implicit_TestSource_GUI yield break; } } -internal static class ArgumentWithImplicitConverterTests_Implicit_ModuleInitializer_GUID +internal static class TUnit_TestProject_ArgumentWithImplicitConverterTests_Implicit__ImplicitInteger_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), new ArgumentWithImplicitConverterTests_Implicit_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ArgumentWithImplicitConverterTests), new TUnit_TestProject_ArgumentWithImplicitConverterTests_Implicit__ImplicitInteger_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyAfterTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyAfterTests.Test.verified.txt index a44a02a2f0..a7cdbc32db 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyAfterTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyAfterTests.Test.verified.txt @@ -15,8 +15,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase1_AfterAll1_After_Assembly_GUID; -internal static class AssemblyBase1_AfterAll1_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase1_AfterAll1_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyBase1_AfterAll1_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -35,7 +35,7 @@ internal static class AssemblyBase1_AfterAll1_After_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal static class AssemblyBase1_AfterAll1_After_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase1)), Name = "AssemblyBase1", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -91,8 +91,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase1_AfterEach1_After_Test_GUID; -internal static class AssemblyBase1_AfterEach1_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase1_AfterEach1_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyBase1_AfterEach1_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -111,7 +111,7 @@ internal static class AssemblyBase1_AfterEach1_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -119,7 +119,7 @@ internal static class AssemblyBase1_AfterEach1_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase1)), Name = "AssemblyBase1", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -166,8 +166,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase2_AfterAll2_After_Assembly_GUID; -internal static class AssemblyBase2_AfterAll2_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase2_AfterAll2_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyBase2_AfterAll2_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -186,7 +186,7 @@ internal static class AssemblyBase2_AfterAll2_After_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -194,7 +194,7 @@ internal static class AssemblyBase2_AfterAll2_After_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase2)), Name = "AssemblyBase2", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -242,8 +242,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase2_AfterEach2_After_Test_GUID; -internal static class AssemblyBase2_AfterEach2_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase2_AfterEach2_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyBase2_AfterEach2_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -262,7 +262,7 @@ internal static class AssemblyBase2_AfterEach2_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -270,7 +270,7 @@ internal static class AssemblyBase2_AfterEach2_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase2)), Name = "AssemblyBase2", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -317,8 +317,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase3_AfterAll3_After_Assembly_GUID; -internal static class AssemblyBase3_AfterAll3_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase3_AfterAll3_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyBase3_AfterAll3_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -337,7 +337,7 @@ internal static class AssemblyBase3_AfterAll3_After_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -345,7 +345,7 @@ internal static class AssemblyBase3_AfterAll3_After_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase3)), Name = "AssemblyBase3", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -393,8 +393,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase3_AfterEach3_After_Test_GUID; -internal static class AssemblyBase3_AfterEach3_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyBase3_AfterEach3_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyBase3_AfterEach3_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -413,7 +413,7 @@ internal static class AssemblyBase3_AfterEach3_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -421,7 +421,7 @@ internal static class AssemblyBase3_AfterEach3_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyBase3)), Name = "AssemblyBase3", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -468,8 +468,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_AfterAllCleanUp_After_Assembly_GUID; -internal static class AssemblyCleanupTests_AfterAllCleanUp_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUp_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUp_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -488,7 +488,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUp_After_Assembly_GUIDIn ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -496,7 +496,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUp_After_Assembly_GUIDIn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -544,8 +544,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_AfterAllCleanUpWithContext_After_Assembly_GUID; -internal static class AssemblyCleanupTests_AfterAllCleanUpWithContext_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUpWithContext__AssemblyHookContext_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUpWithContext__AssemblyHookContext_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -573,7 +573,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUpWithContext_After_Asse ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests).GetMethod("AfterAllCleanUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.AssemblyHookContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -581,7 +581,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUpWithContext_After_Asse TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -629,8 +629,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_AfterAllCleanUp2_After_Assembly_GUID; -internal static class AssemblyCleanupTests_AfterAllCleanUp2_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUp2_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUp2_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -649,7 +649,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUp2_After_Assembly_GUIDI ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -657,7 +657,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUp2_After_Assembly_GUIDI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -705,8 +705,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken_After_Assembly_GUID; -internal static class AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken_After_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken__AssemblyHookContext_CancellationToken_After_Assembly; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken__AssemblyHookContext_CancellationToken_After_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -741,7 +741,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken_Af ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests).GetMethod("AfterAllCleanUpWithContextAndToken", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.AssemblyHookContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -749,7 +749,7 @@ internal static class AssemblyCleanupTests_AfterAllCleanUpWithContextAndToken_Af TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -797,8 +797,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_Cleanup_After_Test_GUID; -internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_Cleanup_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_Cleanup_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -817,7 +817,7 @@ internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -825,7 +825,7 @@ internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -872,8 +872,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_Cleanup_After_Test_GUID; -internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_Cleanup__CancellationToken_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_Cleanup__CancellationToken_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -901,7 +901,7 @@ internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests).GetMethod("Cleanup", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -909,7 +909,7 @@ internal static class AssemblyCleanupTests_Cleanup_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -956,8 +956,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_CleanupWithContext_After_Test_GUID; -internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_CleanupWithContext__TestContext_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_CleanupWithContext__TestContext_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -985,7 +985,7 @@ internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDIni ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests).GetMethod("CleanupWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -993,7 +993,7 @@ internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDIni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1040,8 +1040,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyCleanupTests_CleanupWithContext_After_Test_GUID; -internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_AssemblyCleanupTests_CleanupWithContext__TestContext_CancellationToken_After_Test; +internal static class TUnit_TestProject_AfterTests_AssemblyCleanupTests_CleanupWithContext__TestContext_CancellationToken_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1076,7 +1076,7 @@ internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDIni ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests).GetMethod("CleanupWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.AssemblyCleanupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1084,7 +1084,7 @@ internal static class AssemblyCleanupTests_CleanupWithContext_After_Test_GUIDIni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.AssemblyCleanupTests)), Name = "AssemblyCleanupTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyBeforeTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyBeforeTests.Test.verified.txt index fcbdf1b643..4eada6fd58 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyBeforeTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyBeforeTests.Test.verified.txt @@ -15,8 +15,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase1_BeforeAll1_Before_Assembly_GUID; -internal static class AssemblyBase1_BeforeAll1_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase1_BeforeAll1_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase1_BeforeAll1_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -35,7 +35,7 @@ internal static class AssemblyBase1_BeforeAll1_Before_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal static class AssemblyBase1_BeforeAll1_Before_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase1)), Name = "AssemblyBase1", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -91,8 +91,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase1_BeforeEach1_Before_Test_GUID; -internal static class AssemblyBase1_BeforeEach1_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase1_BeforeEach1_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase1_BeforeEach1_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -111,7 +111,7 @@ internal static class AssemblyBase1_BeforeEach1_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -119,7 +119,7 @@ internal static class AssemblyBase1_BeforeEach1_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase1)), Name = "AssemblyBase1", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -166,8 +166,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase2_BeforeAll2_Before_Assembly_GUID; -internal static class AssemblyBase2_BeforeAll2_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase2_BeforeAll2_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase2_BeforeAll2_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -186,7 +186,7 @@ internal static class AssemblyBase2_BeforeAll2_Before_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -194,7 +194,7 @@ internal static class AssemblyBase2_BeforeAll2_Before_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase2)), Name = "AssemblyBase2", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -242,8 +242,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase2_BeforeEach2_Before_Test_GUID; -internal static class AssemblyBase2_BeforeEach2_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase2_BeforeEach2_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase2_BeforeEach2_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -262,7 +262,7 @@ internal static class AssemblyBase2_BeforeEach2_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -270,7 +270,7 @@ internal static class AssemblyBase2_BeforeEach2_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase2)), Name = "AssemblyBase2", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -317,8 +317,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase3_BeforeAll3_Before_Assembly_GUID; -internal static class AssemblyBase3_BeforeAll3_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase3_BeforeAll3_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase3_BeforeAll3_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -337,7 +337,7 @@ internal static class AssemblyBase3_BeforeAll3_Before_Assembly_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -345,7 +345,7 @@ internal static class AssemblyBase3_BeforeAll3_Before_Assembly_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase3)), Name = "AssemblyBase3", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -393,8 +393,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblyBase3_BeforeEach3_Before_Test_GUID; -internal static class AssemblyBase3_BeforeEach3_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblyBase3_BeforeEach3_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblyBase3_BeforeEach3_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -413,7 +413,7 @@ internal static class AssemblyBase3_BeforeEach3_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblyBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -421,7 +421,7 @@ internal static class AssemblyBase3_BeforeEach3_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblyBase3)), Name = "AssemblyBase3", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -468,8 +468,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_BeforeAllSetUp_Before_Assembly_GUID; -internal static class AssemblySetupTests_BeforeAllSetUp_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUp_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUp_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -488,7 +488,7 @@ internal static class AssemblySetupTests_BeforeAllSetUp_Before_Assembly_GUIDInit ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -496,7 +496,7 @@ internal static class AssemblySetupTests_BeforeAllSetUp_Before_Assembly_GUIDInit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -544,8 +544,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assembly_GUID; -internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUpWithContext__AssemblyHookContext_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUpWithContext__AssemblyHookContext_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -573,7 +573,7 @@ internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assemb ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests).GetMethod("BeforeAllSetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.AssemblyHookContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -581,7 +581,7 @@ internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assemb TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -629,8 +629,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_BeforeAllSetUp2_Before_Assembly_GUID; -internal static class AssemblySetupTests_BeforeAllSetUp2_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUp2_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUp2_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -649,7 +649,7 @@ internal static class AssemblySetupTests_BeforeAllSetUp2_Before_Assembly_GUIDIni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -657,7 +657,7 @@ internal static class AssemblySetupTests_BeforeAllSetUp2_Before_Assembly_GUIDIni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -705,8 +705,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assembly_GUID; -internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assembly_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUpWithContext__AssemblyHookContext_CancellationToken_Before_Assembly; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_BeforeAllSetUpWithContext__AssemblyHookContext_CancellationToken_Before_AssemblyInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -741,7 +741,7 @@ internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assemb ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests).GetMethod("BeforeAllSetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.AssemblyHookContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -749,7 +749,7 @@ internal static class AssemblySetupTests_BeforeAllSetUpWithContext_Before_Assemb TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -797,8 +797,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_Setup_Before_Test_GUID; -internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_Setup_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_Setup_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -817,7 +817,7 @@ internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -825,7 +825,7 @@ internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -872,8 +872,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_Setup_Before_Test_GUID; -internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_Setup__CancellationToken_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_Setup__CancellationToken_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -901,7 +901,7 @@ internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests).GetMethod("Setup", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -909,7 +909,7 @@ internal static class AssemblySetupTests_Setup_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -956,8 +956,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_SetupWithContext_Before_Test_GUID; -internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_SetupWithContext__TestContext_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_SetupWithContext__TestContext_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -985,7 +985,7 @@ internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitia ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests).GetMethod("SetupWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -993,7 +993,7 @@ internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitia TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1040,8 +1040,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.AssemblySetupTests_SetupWithContext_Before_Test_GUID; -internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_AssemblySetupTests_SetupWithContext__TestContext_CancellationToken_Before_Test; +internal static class TUnit_TestProject_BeforeTests_AssemblySetupTests_SetupWithContext__TestContext_CancellationToken_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1076,7 +1076,7 @@ internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitia ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests).GetMethod("SetupWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.AssemblySetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1084,7 +1084,7 @@ internal static class AssemblySetupTests_SetupWithContext_Before_Test_GUIDInitia TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.AssemblySetupTests)), Name = "AssemblySetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet10_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet8_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet9_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.Net4_7.verified.txt index a2665445d5..f5b2d3d7d7 100644 --- a/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AssemblyLoaderTests.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AsyncMethodDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AsyncMethodDataSourceDrivenTests.Test.verified.txt index ac39a7b520..a4e5d2b5ae 100644 --- a/TUnit.Core.SourceGenerator.Tests/AsyncMethodDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AsyncMethodDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_SingleValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -67,7 +67,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_SingleValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -75,7 +75,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -89,15 +89,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.AsyncMethodDataSource_SingleValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_SingleValue(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -106,12 +112,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_SingleValue__int_TestSource()); } } @@ -123,7 +129,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Sin #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples__int_string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -133,7 +139,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_Tuples", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -194,7 +200,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_Tuples", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -202,7 +208,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -216,15 +222,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_Tuples(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.AsyncMethodDataSource_Tuples(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -233,12 +245,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples__int_string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tuples__int_string_TestSource()); } } @@ -250,7 +262,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Tup #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -260,7 +272,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_Enumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -314,7 +326,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_Enumerable", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -322,7 +334,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -336,15 +348,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.AsyncMethodDataSource_Enumerable(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_Enumerable(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -353,12 +371,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enumerable__int_TestSource()); } } @@ -370,7 +388,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Enu #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -380,7 +398,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_Func", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -434,7 +452,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_Func", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -442,7 +460,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -456,15 +474,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_Func(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.AsyncMethodDataSource_Func(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -473,12 +497,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Func__int_TestSource()); } } @@ -490,7 +514,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Fun #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -500,7 +524,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_WithArguments", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -554,7 +578,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_WithArguments", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -562,7 +586,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -576,15 +600,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.AsyncMethodDataSource_WithArguments(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_WithArguments(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -593,12 +623,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_WithArguments__int_TestSource()); } } @@ -610,7 +640,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Wit #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -620,7 +650,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "AsyncMethodDataSource_ExternalClass", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -674,7 +704,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("AsyncMethodDataSource_ExternalClass", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -682,7 +712,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -696,15 +726,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.AsyncMethodDataSource_ExternalClass(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.AsyncMethodDataSource_ExternalClass(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -713,12 +749,12 @@ internal sealed class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_ExternalClass__string_TestSource()); } } @@ -730,7 +766,7 @@ internal static class AsyncMethodDataSourceDrivenTests_AsyncMethodDataSource_Ext #nullable enable namespace TUnit.Generated; -internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -740,7 +776,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource TestClassType = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), TestMethodName = "ValueTaskMethodDataSource_SingleValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -794,7 +830,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource ReflectionInfo = typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests).GetMethod("ValueTaskMethodDataSource_SingleValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -802,7 +838,7 @@ internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests)), Name = "AsyncMethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -816,15 +852,21 @@ internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.ValueTaskMethodDataSource_SingleValue(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.ValueTaskMethodDataSource_SingleValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -833,11 +875,11 @@ internal sealed class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource yield break; } } -internal static class AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AsyncMethodDataSourceDrivenTests), new TUnit_TestProject_AsyncMethodDataSourceDrivenTests_ValueTaskMethodDataSource_SingleValue__int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/AttributeTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/AttributeTests.Test.verified.txt index bd74a1f1a5..60f3ea71f7 100644 --- a/TUnit.Core.SourceGenerator.Tests/AttributeTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/AttributeTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AttributeTests_MyTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core TestClassType = typeof(global::TUnit.TestProject.AttributeTests), TestMethodName = "MyTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.AttributeTests.MixedAttribute(), @@ -45,7 +45,7 @@ internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AttributeTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AttributeTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -53,7 +53,7 @@ internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AttributeTests)), Name = "AttributeTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -67,10 +67,17 @@ internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AttributeTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.MyTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.MyTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -78,11 +85,11 @@ internal sealed class AttributeTests_MyTest_TestSource_GUID : global::TUnit.Core yield break; } } -internal static class AttributeTests_MyTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AttributeTests_MyTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AttributeTests), new AttributeTests_MyTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AttributeTests), new TUnit_TestProject_AttributeTests_MyTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet10_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet8_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet9_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.Net4_7.verified.txt index a2665445d5..f5b2d3d7d7 100644 --- a/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BasicTests.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BeforeAllTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/BeforeAllTests.Test.verified.txt index 279c0098c8..264ca836a8 100644 --- a/TUnit.Core.SourceGenerator.Tests/BeforeAllTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BeforeAllTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BeforeTests_SetupTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.BeforeTests.SetupTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.SetupTests)), Name = "SetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,9 +55,16 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BeforeTests.SetupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -65,12 +72,12 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class SetupTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_BeforeTests_SetupTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new SetupTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new TUnit_TestProject_BeforeTests_SetupTests_Test1_TestSource()); } } @@ -82,7 +89,7 @@ internal static class SetupTests_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BeforeTests_SetupTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -92,7 +99,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.BeforeTests.SetupTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -112,7 +119,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -120,7 +127,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.SetupTests)), Name = "SetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -134,9 +141,16 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BeforeTests.SetupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -144,11 +158,11 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class SetupTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_BeforeTests_SetupTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new SetupTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new TUnit_TestProject_BeforeTests_SetupTests_Test2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/BeforeTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/BeforeTests.Test.verified.txt index 279c0098c8..264ca836a8 100644 --- a/TUnit.Core.SourceGenerator.Tests/BeforeTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/BeforeTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BeforeTests_SetupTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.BeforeTests.SetupTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.SetupTests)), Name = "SetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,9 +55,16 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BeforeTests.SetupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -65,12 +72,12 @@ internal sealed class SetupTests_Test1_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class SetupTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_BeforeTests_SetupTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new SetupTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new TUnit_TestProject_BeforeTests_SetupTests_Test1_TestSource()); } } @@ -82,7 +89,7 @@ internal static class SetupTests_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BeforeTests_SetupTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -92,7 +99,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.BeforeTests.SetupTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -112,7 +119,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.SetupTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -120,7 +127,7 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.SetupTests)), Name = "SetupTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -134,9 +141,16 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BeforeTests.SetupTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -144,11 +158,11 @@ internal sealed class SetupTests_Test2_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class SetupTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_BeforeTests_SetupTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new SetupTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BeforeTests.SetupTests), new TUnit_TestProject_BeforeTests_SetupTests_Test2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet10_0.verified.txt index b8fd3e5ea7..01c15f97fd 100644 --- a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.Bugs._2971.Tests), TestMethodName = "SimpleTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Bugs._2971.SomeAttribute(typeof(global::System.Nullable<>)) @@ -34,7 +34,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2971.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2971", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,10 +56,17 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2971.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SimpleTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SimpleTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -67,11 +74,11 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class Tests_SimpleTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new Tests_SimpleTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet8_0.verified.txt index b8fd3e5ea7..01c15f97fd 100644 --- a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.Bugs._2971.Tests), TestMethodName = "SimpleTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Bugs._2971.SomeAttribute(typeof(global::System.Nullable<>)) @@ -34,7 +34,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2971.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2971", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,10 +56,17 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2971.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SimpleTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SimpleTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -67,11 +74,11 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class Tests_SimpleTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new Tests_SimpleTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet9_0.verified.txt index b8fd3e5ea7..01c15f97fd 100644 --- a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.Bugs._2971.Tests), TestMethodName = "SimpleTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Bugs._2971.SomeAttribute(typeof(global::System.Nullable<>)) @@ -34,7 +34,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2971.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2971", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,10 +56,17 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2971.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SimpleTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SimpleTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -67,11 +74,11 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class Tests_SimpleTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new Tests_SimpleTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.Net4_7.verified.txt index e6b3197526..342d08b675 100644 --- a/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Bugs2971NullableTypeTest.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.Bugs._2971.Tests), TestMethodName = "SimpleTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Bugs._2971.SomeAttribute(typeof(global::System.Nullable<>)) @@ -34,7 +34,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2971.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2971.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2971", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,10 +56,17 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2971.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SimpleTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SimpleTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -67,11 +74,11 @@ internal sealed class Tests_SimpleTest_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class Tests_SimpleTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2971_Tests_SimpleTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new Tests_SimpleTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2971.Tests), new TUnit_TestProject_Bugs__2971_Tests_SimpleTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassAndMethodArgumentsTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassAndMethodArgumentsTests.Test.verified.txt index c864b9fc1c..9354f67153 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassAndMethodArgumentsTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassAndMethodArgumentsTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassAndMethodArgumentsTests_Simple_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : glob TestClassType = typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), TestMethodName = "Simple", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute("1"), @@ -39,7 +39,7 @@ internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : glob ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -47,7 +47,7 @@ internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : glob TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests)), Name = "ClassAndMethodArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(string)) @@ -73,9 +73,16 @@ internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : glob { return new global::TUnit.TestProject.ClassAndMethodArgumentsTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Simple(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Simple()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -83,12 +90,12 @@ internal sealed class ClassAndMethodArgumentsTests_Simple_TestSource_GUID : glob yield break; } } -internal static class ClassAndMethodArgumentsTests_Simple_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassAndMethodArgumentsTests_Simple_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new ClassAndMethodArgumentsTests_Simple_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new TUnit_TestProject_ClassAndMethodArgumentsTests_Simple_TestSource()); } } @@ -100,7 +107,7 @@ internal static class ClassAndMethodArgumentsTests_Simple_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassAndMethodArgumentsTests_WithMethodLevel__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -110,7 +117,7 @@ internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GU TestClassType = typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), TestMethodName = "WithMethodLevel", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute("1"), @@ -149,7 +156,7 @@ internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GU ReflectionInfo = typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests).GetMethod("WithMethodLevel", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -157,7 +164,7 @@ internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests)), Name = "ClassAndMethodArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(string)) @@ -183,15 +190,21 @@ internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GU { return new global::TUnit.TestProject.ClassAndMethodArgumentsTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.WithMethodLevel(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.WithMethodLevel(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -200,12 +213,12 @@ internal sealed class ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GU yield break; } } -internal static class ClassAndMethodArgumentsTests_WithMethodLevel_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassAndMethodArgumentsTests_WithMethodLevel__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new ClassAndMethodArgumentsTests_WithMethodLevel_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new TUnit_TestProject_ClassAndMethodArgumentsTests_WithMethodLevel__string_TestSource()); } } @@ -217,7 +230,7 @@ internal static class ClassAndMethodArgumentsTests_WithMethodLevel_ModuleInitial #nullable enable namespace TUnit.Generated; -internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassAndMethodArgumentsTests_IgnoreParameters__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -227,7 +240,7 @@ internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_G TestClassType = typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), TestMethodName = "IgnoreParameters", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute("1"), @@ -266,7 +279,7 @@ internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_G ReflectionInfo = typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests).GetMethod("IgnoreParameters", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassAndMethodArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -274,7 +287,7 @@ internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests)), Name = "ClassAndMethodArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(string)) @@ -300,15 +313,21 @@ internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_G { return new global::TUnit.TestProject.ClassAndMethodArgumentsTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.IgnoreParameters(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.IgnoreParameters(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -317,11 +336,11 @@ internal sealed class ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_G yield break; } } -internal static class ClassAndMethodArgumentsTests_IgnoreParameters_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassAndMethodArgumentsTests_IgnoreParameters__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new ClassAndMethodArgumentsTests_IgnoreParameters_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassAndMethodArgumentsTests), new TUnit_TestProject_ClassAndMethodArgumentsTests_IgnoreParameters__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassConstructorTest.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassConstructorTest.Test.verified.txt index b5a1c9ac47..74e8910822 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassConstructorTest.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassConstructorTest.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassConstructorTest_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.ClassConstructorTest), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ClassConstructorAttribute() @@ -34,7 +34,7 @@ internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit. ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassConstructorTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassConstructorTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassConstructorTest)), Name = "ClassConstructorTest", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.DummyReferenceTypeClass)) @@ -82,10 +82,17 @@ internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit. // ClassConstructor attribute is present - instance creation handled at runtime throw new global::System.NotSupportedException("Instance creation for classes with ClassConstructor attribute is handled at runtime"); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -93,11 +100,11 @@ internal sealed class ClassConstructorTest_Test_TestSource_GUID : global::TUnit. yield break; } } -internal static class ClassConstructorTest_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassConstructorTest_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassConstructorTest), new ClassConstructorTest_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassConstructorTest), new TUnit_TestProject_ClassConstructorTest_Test_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests.Test.verified.txt index b111058afd..3187ccef56 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class__SomeAsyncDisposableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "DataSource_Class", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("DataSource_Class", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.Library.Models.SomeAsyncDisposableClass) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,17 +68,23 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Class(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Class(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -86,12 +92,12 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUI yield break; } } -internal static class ClassDataSourceDrivenTests_DataSource_Class_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class__SomeAsyncDisposableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_DataSource_Class_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class__SomeAsyncDisposableClass_TestSource()); } } @@ -103,7 +109,7 @@ internal static class ClassDataSourceDrivenTests_DataSource_Class_ModuleInitiali #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class_Generic__SomeAsyncDisposableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -113,7 +119,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSo TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "DataSource_Class_Generic", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -146,7 +152,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSo ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("DataSource_Class_Generic", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.Library.Models.SomeAsyncDisposableClass) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -154,7 +160,7 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -168,17 +174,23 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_Class_Generic(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_Class_Generic(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -186,12 +198,12 @@ internal sealed class ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSo yield break; } } -internal static class ClassDataSourceDrivenTests_DataSource_Class_Generic_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class_Generic__SomeAsyncDisposableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_DataSource_Class_Generic_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_DataSource_Class_Generic__SomeAsyncDisposableClass_TestSource()); } } @@ -203,7 +215,7 @@ internal static class ClassDataSourceDrivenTests_DataSource_Class_Generic_Module #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource__InitializableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -213,7 +225,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "IsInitialized_With_1_ClassDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -246,7 +258,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("IsInitialized_With_1_ClassDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(InitializableClass) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -254,7 +266,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -268,15 +280,21 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.IsInitialized_With_1_ClassDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.IsInitialized_With_1_ClassDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -285,12 +303,12 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS yield break; } } -internal static class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource__InitializableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataSource__InitializableClass_TestSource()); } } @@ -302,7 +320,7 @@ internal static class ClassDataSourceDrivenTests_IsInitialized_With_1_ClassDataS #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources__InitializableClass_InitializableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -312,7 +330,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "IsInitialized_With_2_ClassDataSources", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -352,7 +370,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("IsInitialized_With_2_ClassDataSources", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(InitializableClass), typeof(InitializableClass) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -360,7 +378,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -374,15 +392,21 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.IsInitialized_With_2_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.IsInitialized_With_2_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -391,12 +415,12 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS yield break; } } -internal static class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources__InitializableClass_InitializableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataSources__InitializableClass_InitializableClass_TestSource()); } } @@ -408,7 +432,7 @@ internal static class ClassDataSourceDrivenTests_IsInitialized_With_2_ClassDataS #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -418,7 +442,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "IsInitialized_With_3_ClassDataSources", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -465,7 +489,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("IsInitialized_With_3_ClassDataSources", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -473,7 +497,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -487,15 +511,21 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - await instance.IsInitialized_With_3_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.IsInitialized_With_3_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -504,12 +534,12 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS yield break; } } -internal static class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_TestSource()); } } @@ -521,7 +551,7 @@ internal static class ClassDataSourceDrivenTests_IsInitialized_With_3_ClassDataS #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -531,7 +561,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "IsInitialized_With_4_ClassDataSources", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -585,7 +615,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("IsInitialized_With_4_ClassDataSources", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass) }, null)!.GetParameters()[3] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -593,7 +623,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -607,15 +637,21 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 4: + return new global::System.Threading.Tasks.ValueTask(instance.IsInitialized_With_4_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]))); + default: + throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 4: - await instance.IsInitialized_With_4_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -624,12 +660,12 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS yield break; } } -internal static class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_TestSource()); } } @@ -641,7 +677,7 @@ internal static class ClassDataSourceDrivenTests_IsInitialized_With_4_ClassDataS #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_InitializableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -651,7 +687,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataS TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), TestMethodName = "IsInitialized_With_5_ClassDataSources", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -712,7 +748,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataS ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests).GetMethod("IsInitialized_With_5_ClassDataSources", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass), typeof(InitializableClass) }, null)!.GetParameters()[4] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -720,7 +756,7 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests)), Name = "ClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -734,15 +770,21 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 5: + return new global::System.Threading.Tasks.ValueTask(instance.IsInitialized_With_5_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]))); + default: + throw new global::System.ArgumentException($"Expected exactly 5 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 5: - await instance.IsInitialized_With_5_ClassDataSources(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 5 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -751,11 +793,11 @@ internal sealed class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataS yield break; } } -internal static class ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_InitializableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests), new TUnit_TestProject_ClassDataSourceDrivenTests_IsInitialized_With_5_ClassDataSources__InitializableClass_InitializableClass_InitializableClass_InitializableClass_InitializableClass_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests2.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests2.Test.verified.txt index 4b01cde3de..a199ccf933 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests2.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTests2.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), TestMethodName = "Base_Derived1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2)), Name = "ClassDataSourceDrivenTests2", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2.Base)) @@ -74,10 +74,17 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID { return new global::TUnit.TestProject.ClassDataSourceDrivenTests2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Base_Derived1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Base_Derived1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -85,12 +92,12 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID yield break; } } -internal static class ClassDataSourceDrivenTests2_Base_Derived1_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), new ClassDataSourceDrivenTests2_Base_Derived1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), new TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived1_TestSource()); } } @@ -102,7 +109,7 @@ internal static class ClassDataSourceDrivenTests2_Base_Derived1_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -112,7 +119,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), TestMethodName = "Base_Derived2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -139,7 +146,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTests2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -147,7 +154,7 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2)), Name = "ClassDataSourceDrivenTests2", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2.Base)) @@ -173,10 +180,17 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID { return new global::TUnit.TestProject.ClassDataSourceDrivenTests2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Base_Derived2(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Base_Derived2(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -184,11 +198,11 @@ internal sealed class ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID yield break; } } -internal static class ClassDataSourceDrivenTests2_Base_Derived2_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), new ClassDataSourceDrivenTests2_Base_Derived2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTests2), new TUnit_TestProject_ClassDataSourceDrivenTests2_Base_Derived2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTestsSharedKeyed.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTestsSharedKeyed.Test.verified.txt index 7fefb30a3d..23866673ce 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTestsSharedKeyed.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassDataSourceDrivenTestsSharedKeyed.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class__SomeAsyncDisposableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Tes TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), TestMethodName = "DataSource_Class", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -47,7 +47,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Tes ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed).GetMethod("DataSource_Class", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(SomeAsyncDisposableClass) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -55,7 +55,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Tes TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed)), Name = "ClassDataSourceDrivenTestsSharedKeyed", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -69,17 +69,23 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Tes }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Class(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Class(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -87,12 +93,12 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Tes yield break; } } -internal static class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class__SomeAsyncDisposableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), new ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), new TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class__SomeAsyncDisposableClass_TestSource()); } } @@ -104,7 +110,7 @@ internal static class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Mod #nullable enable namespace TUnit.Generated; -internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic__SomeAsyncDisposableClass_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -114,7 +120,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Gen TestClassType = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), TestMethodName = "DataSource_Class_Generic", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -148,7 +154,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Gen ReflectionInfo = typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed).GetMethod("DataSource_Class_Generic", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(SomeAsyncDisposableClass) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -156,7 +162,7 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Gen TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed)), Name = "ClassDataSourceDrivenTestsSharedKeyed", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -170,17 +176,23 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Gen }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_Class_Generic(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_Class_Generic(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -188,11 +200,11 @@ internal sealed class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Gen yield break; } } -internal static class ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic__SomeAsyncDisposableClass_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), new ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassDataSourceDrivenTestsSharedKeyed), new TUnit_TestProject_ClassDataSourceDrivenTestsSharedKeyed_DataSource_Class_Generic__SomeAsyncDisposableClass_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ClassTupleDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ClassTupleDataSourceDrivenTests.Test.verified.txt index 19cee92cf1..dd7c2f5de3 100644 --- a/TUnit.Core.SourceGenerator.Tests/ClassTupleDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ClassTupleDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ClassTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -23,7 +23,7 @@ internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_Tes TestClassType = typeof(global::TUnit.TestProject.ClassTupleDataSourceDrivenTests), TestMethodName = "DataSource_TupleMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -257,7 +257,7 @@ internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_Tes ReflectionInfo = typeof(global::TUnit.TestProject.ClassTupleDataSourceDrivenTests).GetMethod("DataSource_TupleMethod", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassTupleDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ClassTupleDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -265,7 +265,7 @@ internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_Tes TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ClassTupleDataSourceDrivenTests)), Name = "ClassTupleDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -357,17 +357,23 @@ internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_Tes Property4 = default(global::System.ValueTuple), }; }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -375,11 +381,11 @@ internal sealed class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_Tes yield break; } } -internal static class ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_ClassTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassTupleDataSourceDrivenTests), new ClassTupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ClassTupleDataSourceDrivenTests), new TUnit_TestProject_ClassTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ConcreteClassTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ConcreteClassTests.Test.verified.txt index d707fe70a3..fdd9b1edda 100644 --- a/TUnit.Core.SourceGenerator.Tests/ConcreteClassTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ConcreteClassTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "SecondTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -35,7 +35,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SecondTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource()); } } @@ -85,7 +92,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -117,7 +124,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -125,7 +132,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -139,91 +146,16 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class ConcreteClass2_AssertClassName_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_AssertClassName_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "SecondTest", - TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TestMethodName = "SecondTest", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.InheritsTestsAttribute() - ], - DataSources = global::System.Array.Empty(), - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 3, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "SecondTest", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + try { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "ConcreteClass2", - Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -231,12 +163,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource()); } } @@ -248,7 +180,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -258,7 +190,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute() @@ -279,7 +211,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -287,7 +219,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1)), Name = "ConcreteClass1", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -301,9 +233,16 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass1(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -311,11 +250,11 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T yield break; } } -internal static class ConcreteClass1_AssertClassName_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new ConcreteClass1_AssertClassName_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ConstantArgumentsTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ConstantArgumentsTests.Test.verified.txt index d6884401e5..582a7cb6ec 100644 --- a/TUnit.Core.SourceGenerator.Tests/ConstantArgumentsTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ConstantArgumentsTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_String1__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "String1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("String1", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.String1(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.String1(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,12 +91,12 @@ internal sealed class ConstantArgumentsTests_String1_TestSource_GUID : global::T yield break; } } -internal static class ConstantArgumentsTests_String1_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_String1__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_String1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_String1__string_TestSource()); } } @@ -102,7 +108,7 @@ internal static class ConstantArgumentsTests_String1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_Int__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -112,7 +118,7 @@ internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "Int", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -145,7 +151,7 @@ internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("Int", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -153,7 +159,7 @@ internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -167,15 +173,21 @@ internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -184,12 +196,12 @@ internal sealed class ConstantArgumentsTests_Int_TestSource_GUID : global::TUnit yield break; } } -internal static class ConstantArgumentsTests_Int_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_Int__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_Int_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_Int__int_TestSource()); } } @@ -201,7 +213,7 @@ internal static class ConstantArgumentsTests_Int_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_Double__double_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -211,7 +223,7 @@ internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "Double", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -244,7 +256,7 @@ internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TU ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("Double", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(double) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -252,7 +264,7 @@ internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -266,15 +278,21 @@ internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -283,12 +301,12 @@ internal sealed class ConstantArgumentsTests_Double_TestSource_GUID : global::TU yield break; } } -internal static class ConstantArgumentsTests_Double_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_Double__double_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_Double_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_Double__double_TestSource()); } } @@ -300,7 +318,7 @@ internal static class ConstantArgumentsTests_Double_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_Float__float_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -310,7 +328,7 @@ internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "Float", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -343,7 +361,7 @@ internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("Float", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(float) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -351,7 +369,7 @@ internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -365,15 +383,21 @@ internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -382,12 +406,12 @@ internal sealed class ConstantArgumentsTests_Float_TestSource_GUID : global::TUn yield break; } } -internal static class ConstantArgumentsTests_Float_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_Float__float_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_Float_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_Float__float_TestSource()); } } @@ -399,7 +423,7 @@ internal static class ConstantArgumentsTests_Float_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_Long__long_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -409,7 +433,7 @@ internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "Long", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -442,7 +466,7 @@ internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUni ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("Long", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(long) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -450,7 +474,7 @@ internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -464,15 +488,21 @@ internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -481,12 +511,12 @@ internal sealed class ConstantArgumentsTests_Long_TestSource_GUID : global::TUni yield break; } } -internal static class ConstantArgumentsTests_Long_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_Long__long_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_Long_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_Long__long_TestSource()); } } @@ -498,7 +528,7 @@ internal static class ConstantArgumentsTests_Long_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_UInt__uint_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -508,7 +538,7 @@ internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "UInt", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -541,7 +571,7 @@ internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUni ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("UInt", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(uint) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -549,7 +579,7 @@ internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -563,15 +593,21 @@ internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -580,12 +616,12 @@ internal sealed class ConstantArgumentsTests_UInt_TestSource_GUID : global::TUni yield break; } } -internal static class ConstantArgumentsTests_UInt_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_UInt__uint_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_UInt_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_UInt__uint_TestSource()); } } @@ -597,7 +633,7 @@ internal static class ConstantArgumentsTests_UInt_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstantArgumentsTests_ULong__ulong_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -607,7 +643,7 @@ internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.ConstantArgumentsTests), TestMethodName = "ULong", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -640,7 +676,7 @@ internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.ConstantArgumentsTests).GetMethod("ULong", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(ulong) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ConstantArgumentsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -648,7 +684,7 @@ internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConstantArgumentsTests)), Name = "ConstantArgumentsTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -662,15 +698,21 @@ internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConstantArgumentsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -679,11 +721,11 @@ internal sealed class ConstantArgumentsTests_ULong_TestSource_GUID : global::TUn yield break; } } -internal static class ConstantArgumentsTests_ULong_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstantArgumentsTests_ULong__ulong_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new ConstantArgumentsTests_ULong_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstantArgumentsTests), new TUnit_TestProject_ConstantArgumentsTests_ULong__ulong_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ConstantInBaseClassTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ConstantInBaseClassTests.Test.verified.txt index 1c1f6ccc98..33ca6c1b5e 100644 --- a/TUnit.Core.SourceGenerator.Tests/ConstantInBaseClassTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ConstantInBaseClassTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1432_ConstantInBaseClassTests_SomeTest__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests), TestMethodName = "SomeTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests).GetMethod("SomeTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests)), Name = "ConstantInBaseClassTests", Namespace = "TUnit.TestProject.Bugs._1432", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,11 +91,11 @@ internal sealed class ConstantInBaseClassTests_SomeTest_TestSource_GUID : global yield break; } } -internal static class ConstantInBaseClassTests_SomeTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1432_ConstantInBaseClassTests_SomeTest__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests), new ConstantInBaseClassTests_SomeTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.ConstantInBaseClassTests), new TUnit_TestProject_Bugs__1432_ConstantInBaseClassTests_SomeTest__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ConstantsInInterpolatedStringsTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ConstantsInInterpolatedStringsTests.Test.verified.txt index 33020368cb..92048fa458 100644 --- a/TUnit.Core.SourceGenerator.Tests/ConstantsInInterpolatedStringsTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ConstantsInInterpolatedStringsTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1432_ConstantsInInterpolatedStringsTests_SomeTest__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GU TestClassType = typeof(global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests), TestMethodName = "SomeTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GU ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests).GetMethod("SomeTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests)), Name = "ConstantsInInterpolatedStringsTests", Namespace = "TUnit.TestProject.Bugs._1432", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,11 +91,11 @@ internal sealed class ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GU yield break; } } -internal static class ConstantsInInterpolatedStringsTests_SomeTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1432_ConstantsInInterpolatedStringsTests_SomeTest__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests), new ConstantsInInterpolatedStringsTests_SomeTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.ConstantsInInterpolatedStringsTests), new TUnit_TestProject_Bugs__1432_ConstantsInInterpolatedStringsTests_SomeTest__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/CustomDisplayNameTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/CustomDisplayNameTests.Test.verified.txt index 8352e4af20..f28457c175 100644 --- a/TUnit.Core.SourceGenerator.Tests/CustomDisplayNameTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/CustomDisplayNameTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute("A super important test!"), @@ -35,7 +35,7 @@ internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -70,9 +70,16 @@ internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -80,12 +87,12 @@ internal sealed class CustomDisplayNameTests_Test_TestSource_GUID : global::TUni yield break; } } -internal static class CustomDisplayNameTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_Test_TestSource()); } } @@ -97,7 +104,7 @@ internal static class CustomDisplayNameTests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -107,7 +114,7 @@ internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute("Another super important test!"), @@ -129,7 +136,7 @@ internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUn ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -137,7 +144,7 @@ internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -164,9 +171,16 @@ internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -174,12 +188,12 @@ internal sealed class CustomDisplayNameTests_Test2_TestSource_GUID : global::TUn yield break; } } -internal static class CustomDisplayNameTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_Test2_TestSource()); } } @@ -191,7 +205,7 @@ internal static class CustomDisplayNameTests_Test2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_Test3__string_int_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -201,7 +215,7 @@ internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "Test3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute("Test with: $value1 $value2 $value3!"), @@ -250,7 +264,7 @@ internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.CustomDisplayNameTests).GetMethod("Test3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(int), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -258,7 +272,7 @@ internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -285,15 +299,21 @@ internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 3: - await instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -302,12 +322,12 @@ internal sealed class CustomDisplayNameTests_Test3_TestSource_GUID : global::TUn yield break; } } -internal static class CustomDisplayNameTests_Test3_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_Test3__string_int_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_Test3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_Test3__string_int_bool_TestSource()); } } @@ -319,7 +339,7 @@ internal static class CustomDisplayNameTests_Test3_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_MethodDataSourceTest__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -329,7 +349,7 @@ internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "MethodDataSourceTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute("Test using MethodDataSource"), @@ -374,7 +394,7 @@ internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.CustomDisplayNameTests).GetMethod("MethodDataSourceTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -382,7 +402,7 @@ internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -409,15 +429,21 @@ internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.MethodDataSourceTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MethodDataSourceTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -426,12 +452,12 @@ internal sealed class CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUI yield break; } } -internal static class CustomDisplayNameTests_MethodDataSourceTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_MethodDataSourceTest__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_MethodDataSourceTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_MethodDataSourceTest__string_TestSource()); } } @@ -443,7 +469,7 @@ internal static class CustomDisplayNameTests_MethodDataSourceTest_ModuleInitiali #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_TestParameterNamePrefixBug__int_string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -453,7 +479,7 @@ internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSour TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "TestParameterNamePrefixBug", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute("Test this($someValue, $someValueType)"), @@ -496,7 +522,7 @@ internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSour ReflectionInfo = typeof(global::TUnit.TestProject.CustomDisplayNameTests).GetMethod("TestParameterNamePrefixBug", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -504,7 +530,7 @@ internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSour TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -531,15 +557,21 @@ internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSour }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.TestParameterNamePrefixBug(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.TestParameterNamePrefixBug(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -548,12 +580,12 @@ internal sealed class CustomDisplayNameTests_TestParameterNamePrefixBug_TestSour yield break; } } -internal static class CustomDisplayNameTests_TestParameterNamePrefixBug_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_TestParameterNamePrefixBug__int_string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_TestParameterNamePrefixBug_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_TestParameterNamePrefixBug__int_string_TestSource()); } } @@ -565,7 +597,7 @@ internal static class CustomDisplayNameTests_TestParameterNamePrefixBug_ModuleIn #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_PasswordTest__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -575,7 +607,7 @@ internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : glob TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "PasswordTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -608,7 +640,7 @@ internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : glob ReflectionInfo = typeof(global::TUnit.TestProject.CustomDisplayNameTests).GetMethod("PasswordTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -616,7 +648,7 @@ internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : glob TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -643,15 +675,21 @@ internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : glob }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.PasswordTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.PasswordTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -660,12 +698,12 @@ internal sealed class CustomDisplayNameTests_PasswordTest_TestSource_GUID : glob yield break; } } -internal static class CustomDisplayNameTests_PasswordTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_PasswordTest__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_PasswordTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_PasswordTest__string_TestSource()); } } @@ -677,7 +715,7 @@ internal static class CustomDisplayNameTests_PasswordTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_SameClassConstantTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -687,7 +725,7 @@ internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GU TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "SameClassConstantTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute($"My test {"My constant"}"), @@ -709,7 +747,7 @@ internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GU ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -717,7 +755,7 @@ internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -744,9 +782,16 @@ internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.SameClassConstantTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.SameClassConstantTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -754,12 +799,12 @@ internal sealed class CustomDisplayNameTests_SameClassConstantTest_TestSource_GU yield break; } } -internal static class CustomDisplayNameTests_SameClassConstantTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_SameClassConstantTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_SameClassConstantTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_SameClassConstantTest_TestSource()); } } @@ -771,7 +816,7 @@ internal static class CustomDisplayNameTests_SameClassConstantTest_ModuleInitial #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_DifferentClassConstantTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -781,7 +826,7 @@ internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSour TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "DifferentClassConstantTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute($"My test {"My constant"}"), @@ -803,7 +848,7 @@ internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSour ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -811,7 +856,7 @@ internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSour TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -838,9 +883,16 @@ internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSour }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.DifferentClassConstantTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.DifferentClassConstantTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -848,12 +900,12 @@ internal sealed class CustomDisplayNameTests_DifferentClassConstantTest_TestSour yield break; } } -internal static class CustomDisplayNameTests_DifferentClassConstantTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_DifferentClassConstantTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_DifferentClassConstantTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_DifferentClassConstantTest_TestSource()); } } @@ -865,7 +917,7 @@ internal static class CustomDisplayNameTests_DifferentClassConstantTest_ModuleIn #nullable enable namespace TUnit.Generated; -internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_CustomDisplayNameTests_NestedClassConstantTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -875,7 +927,7 @@ internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_ TestClassType = typeof(global::TUnit.TestProject.CustomDisplayNameTests), TestMethodName = "NestedClassConstantTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.DisplayNameAttribute($"My test {"My constant"}"), @@ -897,7 +949,7 @@ internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_ ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.CustomDisplayNameTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -905,7 +957,7 @@ internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.CustomDisplayNameTests)), Name = "CustomDisplayNameTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -932,9 +984,16 @@ internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.CustomDisplayNameTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.NestedClassConstantTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.NestedClassConstantTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -942,11 +1001,11 @@ internal sealed class CustomDisplayNameTests_NestedClassConstantTest_TestSource_ yield break; } } -internal static class CustomDisplayNameTests_NestedClassConstantTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_CustomDisplayNameTests_NestedClassConstantTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new CustomDisplayNameTests_NestedClassConstantTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.CustomDisplayNameTests), new TUnit_TestProject_CustomDisplayNameTests_NestedClassConstantTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DataDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/DataDrivenTests.Test.verified.txt index 336de1cd0c..c49443a6ac 100644 --- a/TUnit.Core.SourceGenerator.Tests/DataDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DataDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_DataSource_Method__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "DataSource_Method", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -48,7 +48,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("DataSource_Method", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -56,7 +56,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -70,17 +70,23 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -88,12 +94,12 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global yield break; } } -internal static class DataDrivenTests_DataSource_Method_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_DataSource_Method__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_DataSource_Method_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_DataSource_Method__int_TestSource()); } } @@ -105,7 +111,7 @@ internal static class DataDrivenTests_DataSource_Method_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_DataSource_Method__int_string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -115,7 +121,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "DataSource_Method", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -157,7 +163,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("DataSource_Method", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -165,7 +171,7 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -179,17 +185,23 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -197,12 +209,12 @@ internal sealed class DataDrivenTests_DataSource_Method_TestSource_GUID : global yield break; } } -internal static class DataDrivenTests_DataSource_Method_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_DataSource_Method__int_string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_DataSource_Method_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_DataSource_Method__int_string_TestSource()); } } @@ -214,7 +226,7 @@ internal static class DataDrivenTests_DataSource_Method_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_EnumValue__TestEnum_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -224,7 +236,7 @@ internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "EnumValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -259,7 +271,7 @@ internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("EnumValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.TestEnum) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -267,7 +279,7 @@ internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -281,17 +293,23 @@ internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.EnumValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.EnumValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -299,12 +317,12 @@ internal sealed class DataDrivenTests_EnumValue_TestSource_GUID : global::TUnit. yield break; } } -internal static class DataDrivenTests_EnumValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_EnumValue__TestEnum_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_EnumValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_EnumValue__TestEnum_TestSource()); } } @@ -316,7 +334,7 @@ internal static class DataDrivenTests_EnumValue_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_NullValue__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -326,7 +344,7 @@ internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "NullValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -359,7 +377,7 @@ internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("NullValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -367,7 +385,7 @@ internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -381,17 +399,23 @@ internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.NullValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.NullValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -399,12 +423,12 @@ internal sealed class DataDrivenTests_NullValue_TestSource_GUID : global::TUnit. yield break; } } -internal static class DataDrivenTests_NullValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_NullValue__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_NullValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_NullValue__string__TestSource()); } } @@ -416,7 +440,7 @@ internal static class DataDrivenTests_NullValue_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_EmptyString__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -426,7 +450,7 @@ internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "EmptyString", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -459,7 +483,7 @@ internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUni ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("EmptyString", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -467,7 +491,7 @@ internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -481,17 +505,23 @@ internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.EmptyString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.EmptyString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -499,12 +529,12 @@ internal sealed class DataDrivenTests_EmptyString_TestSource_GUID : global::TUni yield break; } } -internal static class DataDrivenTests_EmptyString_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_EmptyString__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_EmptyString_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_EmptyString__string__TestSource()); } } @@ -516,7 +546,7 @@ internal static class DataDrivenTests_EmptyString_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_NonEmptyString__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -526,7 +556,7 @@ internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "NonEmptyString", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -559,7 +589,7 @@ internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("NonEmptyString", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -567,7 +597,7 @@ internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -581,17 +611,23 @@ internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.NonEmptyString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.NonEmptyString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -599,12 +635,12 @@ internal sealed class DataDrivenTests_NonEmptyString_TestSource_GUID : global::T yield break; } } -internal static class DataDrivenTests_NonEmptyString_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_NonEmptyString__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_NonEmptyString_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_NonEmptyString__string__TestSource()); } } @@ -616,7 +652,7 @@ internal static class DataDrivenTests_NonEmptyString_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_BooleanString__bool__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -626,7 +662,7 @@ internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "BooleanString", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -661,7 +697,7 @@ internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TU ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("BooleanString", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool?) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -669,7 +705,7 @@ internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -683,17 +719,23 @@ internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.BooleanString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.BooleanString(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -701,12 +743,12 @@ internal sealed class DataDrivenTests_BooleanString_TestSource_GUID : global::TU yield break; } } -internal static class DataDrivenTests_BooleanString_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_BooleanString__bool__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_BooleanString_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_BooleanString__bool__TestSource()); } } @@ -718,7 +760,7 @@ internal static class DataDrivenTests_BooleanString_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_Type__Type_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -728,7 +770,7 @@ internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core. TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "Type", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -761,7 +803,7 @@ internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core. ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("Type", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Type) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -769,7 +811,7 @@ internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -783,17 +825,23 @@ internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Type(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Type(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -801,12 +849,12 @@ internal sealed class DataDrivenTests_Type_TestSource_GUID : global::TUnit.Core. yield break; } } -internal static class DataDrivenTests_Type_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_Type__Type_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_Type_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_Type__Type_TestSource()); } } @@ -818,7 +866,7 @@ internal static class DataDrivenTests_Type_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_IntegerArray__int___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -828,7 +876,7 @@ internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "IntegerArray", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -861,7 +909,7 @@ internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("IntegerArray", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int[]) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -869,7 +917,7 @@ internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -883,17 +931,23 @@ internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.IntegerArray(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.IntegerArray(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -901,12 +955,12 @@ internal sealed class DataDrivenTests_IntegerArray_TestSource_GUID : global::TUn yield break; } } -internal static class DataDrivenTests_IntegerArray_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_IntegerArray__int___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_IntegerArray_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_IntegerArray__int___TestSource()); } } @@ -918,7 +972,7 @@ internal static class DataDrivenTests_IntegerArray_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataDrivenTests_IntMaxValue__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -928,7 +982,7 @@ internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.DataDrivenTests), TestMethodName = "IntMaxValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -961,7 +1015,7 @@ internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUni ReflectionInfo = typeof(global::TUnit.TestProject.DataDrivenTests).GetMethod("IntMaxValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -969,7 +1023,7 @@ internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataDrivenTests)), Name = "DataDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -983,17 +1037,23 @@ internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DataDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.IntMaxValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.IntMaxValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1001,11 +1061,11 @@ internal sealed class DataDrivenTests_IntMaxValue_TestSource_GUID : global::TUni yield break; } } -internal static class DataDrivenTests_IntMaxValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataDrivenTests_IntMaxValue__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new DataDrivenTests_IntMaxValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataDrivenTests), new TUnit_TestProject_DataDrivenTests_IntMaxValue__int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DataSourceClassCombinedWithDataSourceMethodTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/DataSourceClassCombinedWithDataSourceMethodTests.Test.verified.txt index c05cf8ad4d..f3385cb194 100644 --- a/TUnit.Core.SourceGenerator.Tests/DataSourceClassCombinedWithDataSourceMethodTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DataSourceClassCombinedWithDataSourceMethodTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClas TestClassType = typeof(global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod), TestMethodName = "DataSourceClassCombinedWithDataSourceMethodTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -122,7 +122,7 @@ internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClas ReflectionInfo = typeof(global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod).GetMethod("DataSourceClassCombinedWithDataSourceMethodTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -130,7 +130,7 @@ internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClas TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod)), Name = "DataSourceClassCombinedWithDataSourceMethod", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -156,17 +156,23 @@ internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClas { return new global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSourceClassCombinedWithDataSourceMethodTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSourceClassCombinedWithDataSourceMethodTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -174,11 +180,11 @@ internal sealed class DataSourceClassCombinedWithDataSourceMethod_DataSourceClas yield break; } } -internal static class DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod), new DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceClassCombinedWithDataSourceMethod), new TUnit_TestProject_DataSourceClassCombinedWithDataSourceMethod_DataSourceClassCombinedWithDataSourceMethodTest__int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Typed.verified.txt b/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Typed.verified.txt index eca84acf16..9bd5b95edd 100644 --- a/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Typed.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Typed.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_G TestClassType = typeof(global::TUnit.TestProject.DataSourceGeneratorTests), TestMethodName = "GeneratedData_Method", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -52,7 +52,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_G ReflectionInfo = typeof(global::TUnit.TestProject.DataSourceGeneratorTests).GetMethod("GeneratedData_Method", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -60,7 +60,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataSourceGeneratorTests)), Name = "DataSourceGeneratorTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -100,17 +100,23 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_G { return new global::TUnit.TestProject.DataSourceGeneratorTests(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.GeneratedData_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.GeneratedData_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -118,12 +124,12 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method_TestSource_G yield break; } } -internal static class DataSourceGeneratorTests_GeneratedData_Method_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new DataSourceGeneratorTests_GeneratedData_Method_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method__int_TestSource()); } } @@ -135,7 +141,7 @@ internal static class DataSourceGeneratorTests_GeneratedData_Method_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method2__int_string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -145,7 +151,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_ TestClassType = typeof(global::TUnit.TestProject.DataSourceGeneratorTests), TestMethodName = "GeneratedData_Method2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -198,7 +204,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.DataSourceGeneratorTests).GetMethod("GeneratedData_Method2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -206,7 +212,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataSourceGeneratorTests)), Name = "DataSourceGeneratorTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -246,17 +252,23 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_ { return new global::TUnit.TestProject.DataSourceGeneratorTests(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 3: + instance.GeneratedData_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 3: - instance.GeneratedData_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -264,12 +276,12 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method2_TestSource_ yield break; } } -internal static class DataSourceGeneratorTests_GeneratedData_Method2_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method2__int_string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new DataSourceGeneratorTests_GeneratedData_Method2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method2__int_string_bool_TestSource()); } } @@ -281,7 +293,7 @@ internal static class DataSourceGeneratorTests_GeneratedData_Method2_ModuleIniti #nullable enable namespace TUnit.Generated; -internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method3__int_string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -291,7 +303,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_ TestClassType = typeof(global::TUnit.TestProject.DataSourceGeneratorTests), TestMethodName = "GeneratedData_Method3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -344,7 +356,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.DataSourceGeneratorTests).GetMethod("GeneratedData_Method3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DataSourceGeneratorTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -352,7 +364,7 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DataSourceGeneratorTests)), Name = "DataSourceGeneratorTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -392,17 +404,23 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_ { return new global::TUnit.TestProject.DataSourceGeneratorTests(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 3: + instance.GeneratedData_Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 3: - instance.GeneratedData_Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -410,11 +428,11 @@ internal sealed class DataSourceGeneratorTests_GeneratedData_Method3_TestSource_ yield break; } } -internal static class DataSourceGeneratorTests_GeneratedData_Method3_ModuleInitializer_GUID +internal static class TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method3__int_string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new DataSourceGeneratorTests_GeneratedData_Method3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DataSourceGeneratorTests), new TUnit_TestProject_DataSourceGeneratorTests_GeneratedData_Method3__int_string_bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Untyped.verified.txt b/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Untyped.verified.txt index f52d004117..bd26b22a7c 100644 --- a/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Untyped.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DataSourceGeneratorTests.Untyped.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AutoDataTests_Test1__string_int_double_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.I TestClassType = typeof(global::TUnit.TestProject.AutoDataTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -66,7 +66,7 @@ internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.I ReflectionInfo = typeof(global::TUnit.TestProject.AutoDataTests).GetMethod("Test1", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(int), typeof(double), typeof(bool) }, null)!.GetParameters()[3] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AutoDataTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AutoDataTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -74,7 +74,7 @@ internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.I TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AutoDataTests)), Name = "AutoDataTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -88,15 +88,21 @@ internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.I }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AutoDataTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 4: - await instance.Test1(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + switch (args.Length) + { + case 4: + return new global::System.Threading.Tasks.ValueTask(instance.Test1(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]))); + default: + throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -105,11 +111,11 @@ internal sealed class AutoDataTests_Test1_TestSource_GUID : global::TUnit.Core.I yield break; } } -internal static class AutoDataTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_AutoDataTests_Test1__string_int_double_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AutoDataTests), new AutoDataTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AutoDataTests), new TUnit_TestProject_AutoDataTests_Test1__string_int_double_bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DecimalArgumentTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/DecimalArgumentTests.Test.verified.txt index c408aadbe5..894195d62b 100644 --- a/TUnit.Core.SourceGenerator.Tests/DecimalArgumentTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DecimalArgumentTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_Transfer__decimal_decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "Transfer", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -55,7 +55,7 @@ internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TU ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("Transfer", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal), typeof(decimal) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -63,7 +63,7 @@ internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -77,15 +77,21 @@ internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 2: - await instance.Transfer(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.Transfer(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -94,12 +100,12 @@ internal sealed class DecimalArgumentTests_Transfer_TestSource_GUID : global::TU yield break; } } -internal static class DecimalArgumentTests_Transfer_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_Transfer__decimal_decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_Transfer_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_Transfer__decimal_decimal_TestSource()); } } @@ -111,7 +117,7 @@ internal static class DecimalArgumentTests_Transfer_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_SimpleDecimal__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -121,7 +127,7 @@ internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "SimpleDecimal", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -154,7 +160,7 @@ internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : globa ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("SimpleDecimal", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -162,7 +168,7 @@ internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -176,15 +182,21 @@ internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.SimpleDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.SimpleDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -193,12 +205,12 @@ internal sealed class DecimalArgumentTests_SimpleDecimal_TestSource_GUID : globa yield break; } } -internal static class DecimalArgumentTests_SimpleDecimal_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_SimpleDecimal__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_SimpleDecimal_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_SimpleDecimal__decimal_TestSource()); } } @@ -210,7 +222,7 @@ internal static class DecimalArgumentTests_SimpleDecimal_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_SmallDecimal__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -220,7 +232,7 @@ internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "SmallDecimal", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -253,7 +265,7 @@ internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("SmallDecimal", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -261,7 +273,7 @@ internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -275,15 +287,21 @@ internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.SmallDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.SmallDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -292,12 +310,12 @@ internal sealed class DecimalArgumentTests_SmallDecimal_TestSource_GUID : global yield break; } } -internal static class DecimalArgumentTests_SmallDecimal_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_SmallDecimal__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_SmallDecimal_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_SmallDecimal__decimal_TestSource()); } } @@ -309,7 +327,7 @@ internal static class DecimalArgumentTests_SmallDecimal_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_MaxDecimal__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -319,7 +337,7 @@ internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "MaxDecimal", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -352,7 +370,7 @@ internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global:: ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("MaxDecimal", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -360,7 +378,7 @@ internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -374,15 +392,21 @@ internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.MaxDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MaxDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -391,12 +415,12 @@ internal sealed class DecimalArgumentTests_MaxDecimal_TestSource_GUID : global:: yield break; } } -internal static class DecimalArgumentTests_MaxDecimal_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_MaxDecimal__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_MaxDecimal_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_MaxDecimal__decimal_TestSource()); } } @@ -408,7 +432,7 @@ internal static class DecimalArgumentTests_MaxDecimal_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_MinDecimal__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -418,7 +442,7 @@ internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "MinDecimal", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -451,7 +475,7 @@ internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global:: ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("MinDecimal", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -459,7 +483,7 @@ internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -473,15 +497,21 @@ internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MinDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.MinDecimal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -490,12 +520,12 @@ internal sealed class DecimalArgumentTests_MinDecimal_TestSource_GUID : global:: yield break; } } -internal static class DecimalArgumentTests_MinDecimal_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_MinDecimal__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_MinDecimal_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_MinDecimal__decimal_TestSource()); } } @@ -507,7 +537,7 @@ internal static class DecimalArgumentTests_MinDecimal_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_ExplicitDecimalValue__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -517,7 +547,7 @@ internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "ExplicitDecimalValue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -550,7 +580,7 @@ internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("ExplicitDecimalValue", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -558,7 +588,7 @@ internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -572,15 +602,21 @@ internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.ExplicitDecimalValue(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.ExplicitDecimalValue(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -589,12 +625,12 @@ internal sealed class DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID yield break; } } -internal static class DecimalArgumentTests_ExplicitDecimalValue_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_ExplicitDecimalValue__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_ExplicitDecimalValue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_ExplicitDecimalValue__decimal_TestSource()); } } @@ -606,7 +642,7 @@ internal static class DecimalArgumentTests_ExplicitDecimalValue_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_MultipleDecimals__decimal_decimal_decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -616,7 +652,7 @@ internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "MultipleDecimals", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -663,7 +699,7 @@ internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : gl ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("MultipleDecimals", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal), typeof(decimal), typeof(decimal) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -671,7 +707,7 @@ internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -685,15 +721,21 @@ internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - await instance.MultipleDecimals(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.MultipleDecimals(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -702,12 +744,12 @@ internal sealed class DecimalArgumentTests_MultipleDecimals_TestSource_GUID : gl yield break; } } -internal static class DecimalArgumentTests_MultipleDecimals_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_MultipleDecimals__decimal_decimal_decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_MultipleDecimals_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_MultipleDecimals__decimal_decimal_decimal_TestSource()); } } @@ -719,7 +761,7 @@ internal static class DecimalArgumentTests_MultipleDecimals_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_Test__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -729,7 +771,7 @@ internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -764,7 +806,7 @@ internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -772,7 +814,7 @@ internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -786,17 +828,23 @@ internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -804,12 +852,12 @@ internal sealed class DecimalArgumentTests_Test_TestSource_GUID : global::TUnit. yield break; } } -internal static class DecimalArgumentTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_Test__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_Test__decimal_TestSource()); } } @@ -821,7 +869,7 @@ internal static class DecimalArgumentTests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_TransactionDiscountCalculations__decimal_decimal_decimal_decimal_decimal_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -831,7 +879,7 @@ internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestS TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "TransactionDiscountCalculations", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -901,7 +949,7 @@ internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestS ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("TransactionDiscountCalculations", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal), typeof(decimal), typeof(decimal), typeof(decimal), typeof(decimal), typeof(bool) }, null)!.GetParameters()[5] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -909,7 +957,7 @@ internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -923,17 +971,23 @@ internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 6: + instance.TransactionDiscountCalculations(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 6 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 6: - instance.TransactionDiscountCalculations(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 6 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -941,12 +995,12 @@ internal sealed class DecimalArgumentTests_TransactionDiscountCalculations_TestS yield break; } } -internal static class DecimalArgumentTests_TransactionDiscountCalculations_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_TransactionDiscountCalculations__decimal_decimal_decimal_decimal_decimal_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_TransactionDiscountCalculations_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_TransactionDiscountCalculations__decimal_decimal_decimal_decimal_decimal_bool_TestSource()); } } @@ -958,7 +1012,7 @@ internal static class DecimalArgumentTests_TransactionDiscountCalculations_Modul #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_Equality3__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -968,7 +1022,7 @@ internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "Equality3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -1001,7 +1055,7 @@ internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("Equality3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1009,7 +1063,7 @@ internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1023,15 +1077,21 @@ internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Equality3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Equality3(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1040,12 +1100,12 @@ internal sealed class DecimalArgumentTests_Equality3_TestSource_GUID : global::T yield break; } } -internal static class DecimalArgumentTests_Equality3_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_Equality3__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_Equality3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_Equality3__decimal_TestSource()); } } @@ -1057,7 +1117,7 @@ internal static class DecimalArgumentTests_Equality3_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_Equality4__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1067,7 +1127,7 @@ internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "Equality4", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -1100,7 +1160,7 @@ internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("Equality4", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1108,7 +1168,7 @@ internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1122,15 +1182,21 @@ internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Equality4(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Equality4(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1139,12 +1205,12 @@ internal sealed class DecimalArgumentTests_Equality4_TestSource_GUID : global::T yield break; } } -internal static class DecimalArgumentTests_Equality4_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_Equality4__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_Equality4_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_Equality4__decimal_TestSource()); } } @@ -1156,7 +1222,7 @@ internal static class DecimalArgumentTests_Equality4_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_DecimalArgumentTests_TestMethod__decimal_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1166,7 +1232,7 @@ internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.DecimalArgumentTests), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -1199,7 +1265,7 @@ internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global:: ReflectionInfo = typeof(global::TUnit.TestProject.DecimalArgumentTests).GetMethod("TestMethod", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(decimal) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DecimalArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1207,7 +1273,7 @@ internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DecimalArgumentTests)), Name = "DecimalArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1221,15 +1287,21 @@ internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.DecimalArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.TestMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.TestMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1238,11 +1310,11 @@ internal sealed class DecimalArgumentTests_TestMethod_TestSource_GUID : global:: yield break; } } -internal static class DecimalArgumentTests_TestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_DecimalArgumentTests_TestMethod__decimal_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new DecimalArgumentTests_TestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.DecimalArgumentTests), new TUnit_TestProject_DecimalArgumentTests_TestMethod__decimal_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet10_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet8_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet9_0.verified.txt index a1305087b5..c8a67d8392 100644 --- a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.Net4_7.verified.txt index a2665445d5..f5b2d3d7d7 100644 --- a/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/DisableReflectionScannerTests.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_SynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "SynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SynchronousTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SynchronousTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class BasicTests_SynchronousTest_TestSource_GUID : global::TUnit yield break; } } -internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_SynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_SynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_SynchronousTest_TestSource()); } } @@ -83,7 +90,7 @@ internal static class BasicTests_SynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_AsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "AsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -113,7 +120,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -121,7 +128,7 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -135,9 +142,16 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AsynchronousTest(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AsynchronousTest()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -145,12 +159,12 @@ internal sealed class BasicTests_AsynchronousTest_TestSource_GUID : global::TUni yield break; } } -internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_AsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_AsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_AsynchronousTest_TestSource()); } } @@ -162,7 +176,7 @@ internal static class BasicTests_AsynchronousTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -172,7 +186,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.BasicTests), TestMethodName = "ValueTaskAsynchronousTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -192,7 +206,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.ValueTask), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.ValueTask)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BasicTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -200,7 +214,7 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BasicTests)), Name = "BasicTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -214,9 +228,16 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.BasicTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.ValueTaskAsynchronousTest(); + try + { + return instance.ValueTaskAsynchronousTest(); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -224,11 +245,11 @@ internal sealed class BasicTests_ValueTaskAsynchronousTest_TestSource_GUID : glo yield break; } } -internal static class BasicTests_ValueTaskAsynchronousTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new BasicTests_ValueTaskAsynchronousTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.BasicTests), new TUnit_TestProject_BasicTests_ValueTaskAsynchronousTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/EnumMemberNamesTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/EnumMemberNamesTests.Test.verified.txt index 712d336307..7b793e1562 100644 --- a/TUnit.Core.SourceGenerator.Tests/EnumMemberNamesTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/EnumMemberNamesTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1432_EnumMemberNamesTests_SomeTest__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests), TestMethodName = "SomeTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -48,7 +48,7 @@ internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TU ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests).GetMethod("SomeTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -56,7 +56,7 @@ internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests)), Name = "EnumMemberNamesTests", Namespace = "TUnit.TestProject.Bugs._1432", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -70,17 +70,23 @@ internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.SomeTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -88,11 +94,11 @@ internal sealed class EnumMemberNamesTests_SomeTest_TestSource_GUID : global::TU yield break; } } -internal static class EnumMemberNamesTests_SomeTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1432_EnumMemberNamesTests_SomeTest__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests), new EnumMemberNamesTests_SomeTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1432.EnumMemberNamesTests), new TUnit_TestProject_Bugs__1432_EnumMemberNamesTests_SomeTest__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/EnumerableDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/EnumerableDataSourceDrivenTests.Test.verified.txt index c300f0066d..6ba8139e62 100644 --- a/TUnit.Core.SourceGenerator.Tests/EnumerableDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/EnumerableDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSour TestClassType = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), TestMethodName = "DataSource_Method", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -67,7 +67,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSour ReflectionInfo = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests).GetMethod("DataSource_Method", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -75,7 +75,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSour TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests)), Name = "EnumerableDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -89,15 +89,21 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSour }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.EnumerableDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -106,12 +112,12 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method_TestSour yield break; } } -internal static class EnumerableDataSourceDrivenTests_DataSource_Method_ModuleInitializer_GUID +internal static class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new EnumerableDataSourceDrivenTests_DataSource_Method_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method__int_TestSource()); } } @@ -123,7 +129,7 @@ internal static class EnumerableDataSourceDrivenTests_DataSource_Method_ModuleIn #nullable enable namespace TUnit.Generated; -internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method2__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -133,7 +139,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSou TestClassType = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), TestMethodName = "DataSource_Method2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -187,7 +193,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSou ReflectionInfo = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests).GetMethod("DataSource_Method2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -195,7 +201,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSou TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests)), Name = "EnumerableDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -209,15 +215,21 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSou }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.EnumerableDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.DataSource_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.DataSource_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -226,12 +238,12 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_Method2_TestSou yield break; } } -internal static class EnumerableDataSourceDrivenTests_DataSource_Method2_ModuleInitializer_GUID +internal static class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method2__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new EnumerableDataSourceDrivenTests_DataSource_Method2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_Method2__int_TestSource()); } } @@ -243,7 +255,7 @@ internal static class EnumerableDataSourceDrivenTests_DataSource_Method2_ModuleI #nullable enable namespace TUnit.Generated; -internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -253,7 +265,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ TestClassType = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), TestMethodName = "DataSource_WithBaseReturn", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -307,7 +319,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ ReflectionInfo = typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests).GetMethod("DataSource_WithBaseReturn", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests.BaseValue) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -315,7 +327,7 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests)), Name = "EnumerableDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -329,17 +341,23 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.EnumerableDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_WithBaseReturn(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_WithBaseReturn(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -347,11 +365,11 @@ internal sealed class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ yield break; } } -internal static class EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_ModuleInitializer_GUID +internal static class TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableDataSourceDrivenTests), new TUnit_TestProject_EnumerableDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/EnumerableTupleDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/EnumerableTupleDataSourceDrivenTests.Test.verified.txt index fefd09ae86..3a9a293f16 100644 --- a/TUnit.Core.SourceGenerator.Tests/EnumerableTupleDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/EnumerableTupleDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMetho TestClassType = typeof(global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests), TestMethodName = "DataSource_TupleMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -103,7 +103,7 @@ internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMetho ReflectionInfo = typeof(global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests).GetMethod("DataSource_TupleMethod", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -111,7 +111,7 @@ internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMetho TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests)), Name = "EnumerableTupleDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -125,17 +125,23 @@ internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMetho }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -143,11 +149,11 @@ internal sealed class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMetho yield break; } } -internal static class EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests), new EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.EnumerableTupleDataSourceDrivenTests), new TUnit_TestProject_EnumerableTupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/ExpectedArgumentTypeTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/ExpectedArgumentTypeTests.Test.verified.txt index 1187ae1508..bda4e49e2b 100644 --- a/TUnit.Core.SourceGenerator.Tests/ExpectedArgumentTypeTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/ExpectedArgumentTypeTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ExpectedArgumentTypeTests_TypedArguments__object_Type_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), TestMethodName = "TypedArguments", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -65,7 +65,7 @@ internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : ReflectionInfo = typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests).GetMethod("TypedArguments", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(object), typeof(global::System.Type) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ExpectedArgumentTypeTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ExpectedArgumentTypeTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -73,7 +73,7 @@ internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests)), Name = "ExpectedArgumentTypeTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -87,15 +87,21 @@ internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ExpectedArgumentTypeTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 2: - await instance.TypedArguments(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.TypedArguments(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -104,12 +110,12 @@ internal sealed class ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID : yield break; } } -internal static class ExpectedArgumentTypeTests_TypedArguments_ModuleInitializer_GUID +internal static class TUnit_TestProject_ExpectedArgumentTypeTests_TypedArguments__object_Type_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), new ExpectedArgumentTypeTests_TypedArguments_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), new TUnit_TestProject_ExpectedArgumentTypeTests_TypedArguments__object_Type_TestSource()); } } @@ -121,7 +127,7 @@ internal static class ExpectedArgumentTypeTests_TypedArguments_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ExpectedArgumentTypeTests_EnumTypes__object_Type_Type_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -131,7 +137,7 @@ internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : glob TestClassType = typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), TestMethodName = "EnumTypes", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -185,7 +191,7 @@ internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : glob ReflectionInfo = typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests).GetMethod("EnumTypes", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(object), typeof(global::System.Type), typeof(global::System.Type) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ExpectedArgumentTypeTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.ExpectedArgumentTypeTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -193,7 +199,7 @@ internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : glob TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests)), Name = "ExpectedArgumentTypeTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -207,15 +213,21 @@ internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : glob }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ExpectedArgumentTypeTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.EnumTypes(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 3: - await instance.EnumTypes(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -224,11 +236,11 @@ internal sealed class ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID : glob yield break; } } -internal static class ExpectedArgumentTypeTests_EnumTypes_ModuleInitializer_GUID +internal static class TUnit_TestProject_ExpectedArgumentTypeTests_EnumTypes__object_Type_Type_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), new ExpectedArgumentTypeTests_EnumTypes_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ExpectedArgumentTypeTests), new TUnit_TestProject_ExpectedArgumentTypeTests_EnumTypes__object_Type_Type_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericMethodTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericMethodTests.Test.verified.txt index 6d5d9cf9b7..27c24ace39 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericMethodTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericMethodTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_GenericMethodTests_AggregateBy_HasExpectedOutput__IEnumerable_TSource__Func_TSource__TKey__Func_TKey__TAccumulate__Func_TAccumulate__TSource__TAccumulate__IEqualityComparer_TKey___IEnumerable_KeyValuePair_TKey__TAccumulate___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TestClassType = typeof(global::TUnit.TestProject.GenericMethodTests), TestMethodName = "AggregateBy_HasExpectedOutput", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -79,7 +79,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.GenericMethodTests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "AggregateBy_HasExpectedOutput" && m.GetParameters().Length == 6)?.GetParameters()[5]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -87,7 +87,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.GenericMethodTests)), Name = "GenericMethodTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -100,7 +100,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.GenericMethodTests(); }, @@ -114,7 +114,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TestMethodName = "AggregateBy_HasExpectedOutput", GenericMethodTypeArguments = new global::System.Type[] { typeof(int), typeof(int), typeof(int)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.MethodDataSourceAttribute("AggregateBy_Numeric_TestData"), @@ -228,7 +228,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.GenericMethodTests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "AggregateBy_HasExpectedOutput" && m.GetParameters().Length == 6)?.GetParameters()[5]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -236,7 +236,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.GenericMethodTests)), Name = "GenericMethodTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -249,14 +249,21 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.GenericMethodTests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.GenericMethodTests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.AggregateBy_HasExpectedOutput((global::System.Collections.Generic.IEnumerable)args[0]!, (global::System.Func)args[1]!, (global::System.Func)args[2]!, (global::System.Func)args[3]!, (global::System.Collections.Generic.IEqualityComparer)args[4]!, (global::System.Collections.Generic.IEnumerable>)args[5]!)); + try + { + var typedInstance = (global::TUnit.TestProject.GenericMethodTests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.AggregateBy_HasExpectedOutput((global::System.Collections.Generic.IEnumerable)args[0]!, (global::System.Func)args[1]!, (global::System.Func)args[2]!, (global::System.Func)args[3]!, (global::System.Collections.Generic.IEqualityComparer)args[4]!, (global::System.Collections.Generic.IEnumerable>)args[5]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -268,7 +275,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TestMethodName = "AggregateBy_HasExpectedOutput", GenericMethodTypeArguments = new global::System.Type[] { typeof(string), typeof(string), typeof(string)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.MethodDataSourceAttribute("AggregateBy_Numeric_TestData"), @@ -382,7 +389,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.GenericMethodTests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "AggregateBy_HasExpectedOutput" && m.GetParameters().Length == 6)?.GetParameters()[5]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.GenericMethodTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -390,7 +397,7 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.GenericMethodTests)), Name = "GenericMethodTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -403,14 +410,21 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.GenericMethodTests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.GenericMethodTests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.AggregateBy_HasExpectedOutput((global::System.Collections.Generic.IEnumerable)args[0]!, (global::System.Func)args[1]!, (global::System.Func)args[2]!, (global::System.Func)args[3]!, (global::System.Collections.Generic.IEqualityComparer)args[4]!, (global::System.Collections.Generic.IEnumerable>)args[5]!)); + try + { + var typedInstance = (global::TUnit.TestProject.GenericMethodTests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.AggregateBy_HasExpectedOutput((global::System.Collections.Generic.IEnumerable)args[0]!, (global::System.Func)args[1]!, (global::System.Func)args[2]!, (global::System.Func)args[3]!, (global::System.Collections.Generic.IEqualityComparer)args[4]!, (global::System.Collections.Generic.IEnumerable>)args[5]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -421,11 +435,11 @@ internal sealed class GenericMethodTests_AggregateBy_HasExpectedOutput_TestSourc yield break; } } -internal static class GenericMethodTests_AggregateBy_HasExpectedOutput_ModuleInitializer_GUID +internal static class TUnit_TestProject_GenericMethodTests_AggregateBy_HasExpectedOutput__IEnumerable_TSource__Func_TSource__TKey__Func_TKey__TAccumulate__Func_TAccumulate__TSource__TAccumulate__IEqualityComparer_TKey___IEnumerable_KeyValuePair_TKey__TAccumulate___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.GenericMethodTests), new GenericMethodTests_AggregateBy_HasExpectedOutput_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.GenericMethodTests), new TUnit_TestProject_GenericMethodTests_AggregateBy_HasExpectedOutput__IEnumerable_TSource__Func_TSource__TKey__Func_TKey__TAccumulate__Func_TAccumulate__TSource__TAccumulate__IEqualityComparer_TKey___IEnumerable_KeyValuePair_TKey__TAccumulate___TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_EmptyGenericRegistry_WhenNoGenericsFound.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_EmptyGenericRegistry_WhenNoGenericsFound.verified.txt index e74f85cd61..2c1596bc85 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_EmptyGenericRegistry_WhenNoGenericsFound.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_EmptyGenericRegistry_WhenNoGenericsFound.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_SimpleTestClass_NonGenericTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.SimpleTestClass), TestMethodName = "NonGenericTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::T ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.SimpleTestClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.SimpleTestClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.SimpleTestClass)), Name = "SimpleTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.SimpleTestClass(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.NonGenericTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.NonGenericTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,11 +73,11 @@ internal sealed class SimpleTestClass_NonGenericTest_TestSource_GUID : global::T yield break; } } -internal static class SimpleTestClass_NonGenericTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_SimpleTestClass_NonGenericTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.SimpleTestClass), new SimpleTestClass_NonGenericTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.SimpleTestClass), new TUnit_TestProject_SimpleTestClass_NonGenericTest_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericConstraints_WithInstantiation.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericConstraints_WithInstantiation.verified.txt index 5f4b487e50..d4b07e0d6f 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericConstraints_WithInstantiation.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericConstraints_WithInstantiation.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConstrainedGenericTestClass_T_TestMethod_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -36,7 +36,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "ConstrainedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,7 +57,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { var genericType = typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>); if (typeArgs.Length > 0) @@ -76,7 +76,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.ConstrainedGenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -99,7 +99,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -107,7 +107,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "ConstrainedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -120,14 +120,21 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.ConstrainedGenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.ConstrainedGenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.ConstrainedGenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -138,7 +145,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.ConstrainedGenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -161,7 +168,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.ConstrainedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -169,7 +176,7 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "ConstrainedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -182,14 +189,21 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.ConstrainedGenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.ConstrainedGenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.ConstrainedGenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -200,11 +214,11 @@ internal sealed class ConstrainedGenericTestClass_TestMethod_TestSource_GUID : g yield break; } } -internal static class ConstrainedGenericTestClass_TestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConstrainedGenericTestClass_T_TestMethod_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), new ConstrainedGenericTestClass_TestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConstrainedGenericTestClass<>), new TUnit_TestProject_ConstrainedGenericTestClass_T_TestMethod_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestClass_WithExplicitInstantiation.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestClass_WithExplicitInstantiation.verified.txt index 0915b76c23..d14b92862b 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestClass_WithExplicitInstantiation.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestClass_WithExplicitInstantiation.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_GenericTestClass_T_TestMethod_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.GenericTestClass<>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), @@ -36,7 +36,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.GenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "GenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,7 +57,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { var genericType = typeof(global::TUnit.TestProject.GenericTestClass<>); if (typeArgs.Length > 0) @@ -76,7 +76,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.GenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), @@ -99,7 +99,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -107,7 +107,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.GenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "GenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -120,14 +120,21 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.GenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.GenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.GenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -138,7 +145,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.GenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), @@ -161,7 +168,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.GenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -169,7 +176,7 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.GenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "GenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -182,14 +189,21 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.GenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.GenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.GenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -200,11 +214,11 @@ internal sealed class GenericTestClass_TestMethod_TestSource_GUID : global::TUni yield break; } } -internal static class GenericTestClass_TestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_GenericTestClass_T_TestMethod_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.GenericTestClass<>), new GenericTestClass_TestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.GenericTestClass<>), new TUnit_TestProject_GenericTestClass_T_TestMethod_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestMethod_WithExplicitInstantiation.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestMethod_WithExplicitInstantiation.verified.txt index 365c22e4b6..7651fbdfec 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestMethod_WithExplicitInstantiation.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_GenericTestMethod_WithExplicitInstantiation.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TestClass_GenericTestMethod_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.TestClass), TestMethodName = "GenericTestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -36,7 +36,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TestClass)), Name = "TestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,7 +57,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.TestClass(); }, @@ -71,7 +71,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TestMethodName = "GenericTestMethod", GenericMethodTypeArguments = new global::System.Type[] { typeof(int)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -94,7 +94,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -102,7 +102,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TestClass)), Name = "TestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -115,14 +115,21 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.TestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.TestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericTestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.TestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericTestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -134,7 +141,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TestMethodName = "GenericTestMethod", GenericMethodTypeArguments = new global::System.Type[] { typeof(string)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int)), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), @@ -157,7 +164,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.TestClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -165,7 +172,7 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TestClass)), Name = "TestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -178,14 +185,21 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.TestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.TestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericTestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.TestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericTestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -196,11 +210,11 @@ internal sealed class TestClass_GenericTestMethod_TestSource_GUID : global::TUni yield break; } } -internal static class TestClass_GenericTestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_TestClass_GenericTestMethod_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TestClass), new TestClass_GenericTestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TestClass), new TUnit_TestProject_TestClass_GenericTestMethod_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_MultipleGenericParameters.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_MultipleGenericParameters.verified.txt index 30b0e79edd..ecf6ff1e70 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_MultipleGenericParameters.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_MultipleGenericParameters.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MultiGenericTestClass_T1_T2_TestMethod_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int), typeof(string)), @@ -36,7 +36,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), [new global::TUnit.Core.GenericParameter(0, false, "T1"), new global::TUnit.Core.GenericParameter(1, false, "T2")]), Name = "MultiGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,7 +57,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { var genericType = typeof(global::TUnit.TestProject.MultiGenericTestClass<,>); if (typeArgs.Length > 0) @@ -76,7 +76,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.MultiGenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int), typeof(string)), @@ -99,7 +99,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -107,7 +107,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), [new global::TUnit.Core.GenericParameter(0, false, "T1"), new global::TUnit.Core.GenericParameter(1, false, "T2")]), Name = "MultiGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -120,14 +120,21 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.MultiGenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.MultiGenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.MultiGenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -138,7 +145,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.MultiGenericTestClass), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(int), typeof(string)), @@ -161,7 +168,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.MultiGenericTestClass<,>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -169,7 +176,7 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), [new global::TUnit.Core.GenericParameter(0, false, "T1"), new global::TUnit.Core.GenericParameter(1, false, "T2")]), Name = "MultiGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -182,14 +189,21 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.MultiGenericTestClass(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.MultiGenericTestClass)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.MultiGenericTestClass)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -200,11 +214,11 @@ internal sealed class MultiGenericTestClass_TestMethod_TestSource_GUID : global: yield break; } } -internal static class MultiGenericTestClass_TestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_MultiGenericTestClass_T1_T2_TestMethod_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), new MultiGenericTestClass_TestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultiGenericTestClass<,>), new TUnit_TestProject_MultiGenericTestClass_T1_T2_TestMethod_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_NestedGenericTypes.verified.txt b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_NestedGenericTypes.verified.txt index f56db59444..711d56824e 100644 --- a/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_NestedGenericTypes.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GenericTypeResolverTests.Test_NestedGenericTypes.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NestedGenericTestClass_T_TestMethod_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.NestedGenericTestClass<>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(global::System.Collections.Generic.List)), @@ -36,7 +36,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.NestedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "NestedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,7 +57,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { var genericType = typeof(global::TUnit.TestProject.NestedGenericTestClass<>); if (typeArgs.Length > 0) @@ -76,7 +76,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.NestedGenericTestClass>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(global::System.Collections.Generic.List)), @@ -99,7 +99,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -107,7 +107,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.NestedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "NestedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -120,14 +120,21 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.NestedGenericTestClass>(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.NestedGenericTestClass>)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.NestedGenericTestClass>)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -138,7 +145,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.NestedGenericTestClass>), TestMethodName = "TestMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.GenerateGenericTestAttribute(typeof(global::System.Collections.Generic.List)), @@ -161,7 +168,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("GenericTypeResolverTests:global::TUnit.TestProject.NestedGenericTestClass<>", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -169,7 +176,7 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.NestedGenericTestClass<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), Name = "NestedGenericTestClass", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("GenericTypeResolverTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "GenericTypeResolverTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -182,14 +189,21 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.NestedGenericTestClass>(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.NestedGenericTestClass>)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + try + { + var typedInstance = (global::TUnit.TestProject.NestedGenericTestClass>)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.TestMethod()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -200,11 +214,11 @@ internal sealed class NestedGenericTestClass_TestMethod_TestSource_GUID : global yield break; } } -internal static class NestedGenericTestClass_TestMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_NestedGenericTestClass_T_TestMethod_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NestedGenericTestClass<>), new NestedGenericTestClass_TestMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NestedGenericTestClass<>), new TUnit_TestProject_NestedGenericTestClass_T_TestMethod_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/GlobalStaticAfterEachTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/GlobalStaticAfterEachTests.Test.verified.txt index dcd0744239..dde41a56cf 100644 --- a/TUnit.Core.SourceGenerator.Tests/GlobalStaticAfterEachTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GlobalStaticAfterEachTests.Test.verified.txt @@ -15,8 +15,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase1_AfterEach1_After_Test_GUID; -internal static class GlobalBase1_AfterEach1_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase1_AfterEach1_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase1_AfterEach1_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -35,7 +35,7 @@ internal static class GlobalBase1_AfterEach1_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal static class GlobalBase1_AfterEach1_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase1)), Name = "GlobalBase1", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -90,8 +90,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase2_AfterEach2_After_Test_GUID; -internal static class GlobalBase2_AfterEach2_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase2_AfterEach2_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase2_AfterEach2_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -110,7 +110,7 @@ internal static class GlobalBase2_AfterEach2_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -118,7 +118,7 @@ internal static class GlobalBase2_AfterEach2_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase2)), Name = "GlobalBase2", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -165,8 +165,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase3_AfterEach3_After_Test_GUID; -internal static class GlobalBase3_AfterEach3_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase3_AfterEach3_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase3_AfterEach3_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -185,7 +185,7 @@ internal static class GlobalBase3_AfterEach3_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -193,7 +193,7 @@ internal static class GlobalBase3_AfterEach3_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase3)), Name = "GlobalBase3", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -240,8 +240,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_CleanUp_After_Test_GUID; -internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUp_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUp_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -260,7 +260,7 @@ internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -268,7 +268,7 @@ internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -315,8 +315,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_CleanUp_After_Test_GUID; -internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUp__CancellationToken_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUp__CancellationToken_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -344,7 +344,7 @@ internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("CleanUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -352,7 +352,7 @@ internal static class GlobalCleanUpTests_CleanUp_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -399,8 +399,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_CleanUpWithContext_After_Test_GUID; -internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUpWithContext__TestContext_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUpWithContext__TestContext_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -428,7 +428,7 @@ internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDIniti ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("CleanUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -436,7 +436,7 @@ internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDIniti TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -483,8 +483,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_CleanUpWithContext_After_Test_GUID; -internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUpWithContext__TestContext_CancellationToken_After_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_CleanUpWithContext__TestContext_CancellationToken_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -519,7 +519,7 @@ internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDIniti ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("CleanUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -527,7 +527,7 @@ internal static class GlobalCleanUpTests_CleanUpWithContext_After_Test_GUIDIniti TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -574,8 +574,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase1_AfterAll1_AfterEvery_Test_GUID; -internal static class GlobalBase1_AfterAll1_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase1_AfterAll1__TestContext_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase1_AfterAll1__TestContext_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -601,7 +601,7 @@ internal static class GlobalBase1_AfterAll1_AfterEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalBase1).GetMethod("AfterAll1", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -609,7 +609,7 @@ internal static class GlobalBase1_AfterAll1_AfterEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase1)), Name = "GlobalBase1", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -657,8 +657,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase2_AfterAll2_AfterEvery_Test_GUID; -internal static class GlobalBase2_AfterAll2_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase2_AfterAll2__TestContext_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase2_AfterAll2__TestContext_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -684,7 +684,7 @@ internal static class GlobalBase2_AfterAll2_AfterEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalBase2).GetMethod("AfterAll2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -692,7 +692,7 @@ internal static class GlobalBase2_AfterAll2_AfterEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase2)), Name = "GlobalBase2", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -740,8 +740,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase3_AfterAll3_AfterEvery_Test_GUID; -internal static class GlobalBase3_AfterAll3_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalBase3_AfterAll3__TestContext_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalBase3_AfterAll3__TestContext_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -767,7 +767,7 @@ internal static class GlobalBase3_AfterAll3_AfterEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalBase3).GetMethod("AfterAll3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -775,7 +775,7 @@ internal static class GlobalBase3_AfterAll3_AfterEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalBase3)), Name = "GlobalBase3", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -823,8 +823,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUID; -internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUp__TestContext_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUp__TestContext_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -850,7 +850,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDIni ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("AfterAllCleanUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -858,7 +858,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDIni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -906,8 +906,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUID; -internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUp__TestContext_CancellationToken_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUp__TestContext_CancellationToken_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -940,7 +940,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDIni ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("AfterAllCleanUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -948,7 +948,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUp_AfterEvery_Test_GUIDIni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -996,8 +996,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_Test_GUID; -internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUpWithContext__TestContext_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUpWithContext__TestContext_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1023,7 +1023,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_T ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("AfterAllCleanUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1031,7 +1031,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1079,8 +1079,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_Test_GUID; -internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUpWithContext__TestContext_CancellationToken_AfterEvery_Test; +internal static class TUnit_TestProject_AfterTests_GlobalCleanUpTests_AfterAllCleanUpWithContext__TestContext_CancellationToken_AfterEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1113,7 +1113,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_T ReflectionInfo = typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests).GetMethod("AfterAllCleanUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AfterTests.GlobalCleanUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1121,7 +1121,7 @@ internal static class GlobalCleanUpTests_AfterAllCleanUpWithContext_AfterEvery_T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AfterTests.GlobalCleanUpTests)), Name = "GlobalCleanUpTests", Namespace = "TUnit.TestProject.AfterTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null diff --git a/TUnit.Core.SourceGenerator.Tests/GlobalStaticBeforeEachTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/GlobalStaticBeforeEachTests.Test.verified.txt index 225d8f88cf..945e9a3f3e 100644 --- a/TUnit.Core.SourceGenerator.Tests/GlobalStaticBeforeEachTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/GlobalStaticBeforeEachTests.Test.verified.txt @@ -15,8 +15,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase1_BeforeEach1_Before_Test_GUID; -internal static class GlobalBase1_BeforeEach1_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase1_BeforeEach1_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase1_BeforeEach1_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -35,7 +35,7 @@ internal static class GlobalBase1_BeforeEach1_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal static class GlobalBase1_BeforeEach1_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase1)), Name = "GlobalBase1", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -90,8 +90,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase2_BeforeEach2_Before_Test_GUID; -internal static class GlobalBase2_BeforeEach2_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase2_BeforeEach2_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase2_BeforeEach2_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -110,7 +110,7 @@ internal static class GlobalBase2_BeforeEach2_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -118,7 +118,7 @@ internal static class GlobalBase2_BeforeEach2_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase2)), Name = "GlobalBase2", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -165,8 +165,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase3_BeforeEach3_Before_Test_GUID; -internal static class GlobalBase3_BeforeEach3_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase3_BeforeEach3_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase3_BeforeEach3_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -185,7 +185,7 @@ internal static class GlobalBase3_BeforeEach3_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -193,7 +193,7 @@ internal static class GlobalBase3_BeforeEach3_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase3)), Name = "GlobalBase3", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -240,8 +240,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_SetUp_Before_Test_GUID; -internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUp_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUp_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -260,7 +260,7 @@ internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -268,7 +268,7 @@ internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -315,8 +315,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_SetUp_Before_Test_GUID; -internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUp__CancellationToken_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUp__CancellationToken_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -344,7 +344,7 @@ internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("SetUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -352,7 +352,7 @@ internal static class GlobalSetUpTests_SetUp_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -399,8 +399,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_SetUpWithContext_Before_Test_GUID; -internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUpWithContext__TestContext_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUpWithContext__TestContext_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -428,7 +428,7 @@ internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitiali ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("SetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -436,7 +436,7 @@ internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitiali TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -483,8 +483,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_SetUpWithContext_Before_Test_GUID; -internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUpWithContext__TestContext_CancellationToken_Before_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_SetUpWithContext__TestContext_CancellationToken_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -519,7 +519,7 @@ internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitiali ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("SetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -527,7 +527,7 @@ internal static class GlobalSetUpTests_SetUpWithContext_Before_Test_GUIDInitiali TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -574,8 +574,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase1_BeforeAll1_BeforeEvery_Test_GUID; -internal static class GlobalBase1_BeforeAll1_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase1_BeforeAll1__TestContext_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase1_BeforeAll1__TestContext_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -601,7 +601,7 @@ internal static class GlobalBase1_BeforeAll1_BeforeEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalBase1).GetMethod("BeforeAll1", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -609,7 +609,7 @@ internal static class GlobalBase1_BeforeAll1_BeforeEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase1)), Name = "GlobalBase1", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -657,8 +657,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase2_BeforeAll2_BeforeEvery_Test_GUID; -internal static class GlobalBase2_BeforeAll2_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase2_BeforeAll2__TestContext_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase2_BeforeAll2__TestContext_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -684,7 +684,7 @@ internal static class GlobalBase2_BeforeAll2_BeforeEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalBase2).GetMethod("BeforeAll2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -692,7 +692,7 @@ internal static class GlobalBase2_BeforeAll2_BeforeEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase2)), Name = "GlobalBase2", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -740,8 +740,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalBase3_BeforeAll3_BeforeEvery_Test_GUID; -internal static class GlobalBase3_BeforeAll3_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalBase3_BeforeAll3__TestContext_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalBase3_BeforeAll3__TestContext_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -767,7 +767,7 @@ internal static class GlobalBase3_BeforeAll3_BeforeEvery_Test_GUIDInitializer ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalBase3).GetMethod("BeforeAll3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalBase3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -775,7 +775,7 @@ internal static class GlobalBase3_BeforeAll3_BeforeEvery_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalBase3)), Name = "GlobalBase3", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -823,8 +823,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUID; -internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUp__TestContext_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUp__TestContext_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -850,7 +850,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDIniti ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("BeforeAllSetUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -858,7 +858,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDIniti TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -906,8 +906,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUID; -internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUp__TestContext_CancellationToken_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUp__TestContext_CancellationToken_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -940,7 +940,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDIniti ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("BeforeAllSetUp", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -948,7 +948,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUp_BeforeEvery_Test_GUIDIniti TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -996,8 +996,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Test_GUID; -internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUpWithContext__TestContext_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUpWithContext__TestContext_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1023,7 +1023,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Tes ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("BeforeAllSetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1031,7 +1031,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Tes TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1079,8 +1079,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Test_GUID; -internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUpWithContext__TestContext_CancellationToken_BeforeEvery_Test; +internal static class TUnit_TestProject_BeforeTests_GlobalSetUpTests_BeforeAllSetUpWithContext__TestContext_CancellationToken_BeforeEvery_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -1113,7 +1113,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Tes ReflectionInfo = typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests).GetMethod("BeforeAllSetUpWithContext", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Static, null, new global::System.Type[] { typeof(global::TUnit.Core.TestContext), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.BeforeTests.GlobalSetUpTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1121,7 +1121,7 @@ internal static class GlobalSetUpTests_BeforeAllSetUpWithContext_BeforeEvery_Tes TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.BeforeTests.GlobalSetUpTests)), Name = "GlobalSetUpTests", Namespace = "TUnit.TestProject.BeforeTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null diff --git a/TUnit.Core.SourceGenerator.Tests/Hooks1589.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Hooks1589.Test.verified.txt index b34b16e7dd..715c01f082 100644 --- a/TUnit.Core.SourceGenerator.Tests/Hooks1589.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Hooks1589.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1589_MyTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TestClassType = typeof(global::TUnit.TestProject.Bugs._1589.MyTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1589.MyTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1589.MyTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1589.MyTests)), Name = "MyTests", Namespace = "TUnit.TestProject.Bugs._1589", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1589.MyFixture)) @@ -74,9 +74,16 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa { return new global::TUnit.TestProject.Bugs._1589.MyTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -84,11 +91,11 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa yield break; } } -internal static class MyTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1589_MyTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1589.MyTests), new MyTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1589.MyTests), new TUnit_TestProject_Bugs__1589_MyTests_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Hooks1594.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Hooks1594.Test.verified.txt index b8277907aa..9d5d9f0ecd 100644 --- a/TUnit.Core.SourceGenerator.Tests/Hooks1594.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Hooks1594.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1594_MyTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TestClassType = typeof(global::TUnit.TestProject.Bugs._1594.MyTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1594.MyTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1594.MyTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1594.MyTests)), Name = "MyTests", Namespace = "TUnit.TestProject.Bugs._1594", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1594.MyFixture)) @@ -74,10 +74,17 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa { return new global::TUnit.TestProject.Bugs._1594.MyTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -85,11 +92,11 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa yield break; } } -internal static class MyTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1594_MyTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1594.MyTests), new MyTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1594.MyTests), new TUnit_TestProject_Bugs__1594_MyTests_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/HooksTests.DisposableFieldTests.verified.txt b/TUnit.Core.SourceGenerator.Tests/HooksTests.DisposableFieldTests.verified.txt index 924876fdcb..ed1c7c23dc 100644 --- a/TUnit.Core.SourceGenerator.Tests/HooksTests.DisposableFieldTests.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/HooksTests.DisposableFieldTests.verified.txt @@ -15,8 +15,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.DisposableFieldTests_Setup_Before_Test_GUID; -internal static class DisposableFieldTests_Setup_Before_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_DisposableFieldTests_Setup_Before_Test; +internal static class TUnit_TestProject_DisposableFieldTests_Setup_Before_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -35,7 +35,7 @@ internal static class DisposableFieldTests_Setup_Before_Test_GUIDInitializer ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DisposableFieldTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DisposableFieldTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal static class DisposableFieldTests_Setup_Before_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DisposableFieldTests)), Name = "DisposableFieldTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -90,8 +90,8 @@ using global::TUnit.Core.Hooks; using global::TUnit.Core.Interfaces.SourceGenerator; using global::TUnit.Core.Models; using HookType = global::TUnit.Core.HookType; -namespace TUnit.Generated.Hooks.DisposableFieldTests_Blah_After_Test_GUID; -internal static class DisposableFieldTests_Blah_After_Test_GUIDInitializer +namespace TUnit.Generated.Hooks.TUnit_TestProject_DisposableFieldTests_Blah_After_Test; +internal static class TUnit_TestProject_DisposableFieldTests_Blah_After_TestInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() @@ -110,7 +110,7 @@ internal static class DisposableFieldTests_Blah_After_Test_GUIDInitializer ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DisposableFieldTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.DisposableFieldTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -118,7 +118,7 @@ internal static class DisposableFieldTests_Blah_After_Test_GUIDInitializer TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.DisposableFieldTests)), Name = "DisposableFieldTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null diff --git a/TUnit.Core.SourceGenerator.Tests/InheritedPropertySetterTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/InheritedPropertySetterTests.Test.verified.txt index 033da0ac0c..2612f8d4f3 100644 --- a/TUnit.Core.SourceGenerator.Tests/InheritedPropertySetterTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/InheritedPropertySetterTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PropertySetterTests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -27,7 +27,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.PropertySetterTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -199,7 +199,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PropertySetterTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PropertySetterTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -207,7 +207,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PropertySetterTests)), Name = "PropertySetterTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -320,9 +320,16 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C Property6 = default!, Property7 = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -330,12 +337,12 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C yield break; } } -internal static class PropertySetterTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_PropertySetterTests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PropertySetterTests), new PropertySetterTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PropertySetterTests), new TUnit_TestProject_PropertySetterTests_Test_TestSource()); } } @@ -347,7 +354,7 @@ internal static class PropertySetterTests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedPropertySetterTests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -371,7 +378,7 @@ internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global TestClassType = typeof(global::TUnit.TestProject.InheritedPropertySetterTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -533,7 +540,7 @@ internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedPropertySetterTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedPropertySetterTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -541,7 +548,7 @@ internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedPropertySetterTests)), Name = "InheritedPropertySetterTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -564,9 +571,16 @@ internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global Property6 = default!, Property7 = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -574,11 +588,11 @@ internal sealed class InheritedPropertySetterTests_Test_TestSource_GUID : global yield break; } } -internal static class InheritedPropertySetterTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedPropertySetterTests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedPropertySetterTests), new InheritedPropertySetterTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedPropertySetterTests), new TUnit_TestProject_InheritedPropertySetterTests_Test_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/InheritedTestsFromDifferentProjectTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/InheritedTestsFromDifferentProjectTests.Test.verified.txt index a115c268da..2994f8ddff 100644 --- a/TUnit.Core.SourceGenerator.Tests/InheritedTestsFromDifferentProjectTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/InheritedTestsFromDifferentProjectTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(Pass), @@ -36,7 +36,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +44,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -58,10 +58,17 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -69,12 +76,12 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_Test_TestSource()); } } @@ -86,7 +93,7 @@ internal static class InheritedTestsFromDifferentProjectTests_Test_ModuleInitial #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_GenericMethodDataSource__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -96,7 +103,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataS TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "GenericMethodDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(Pass), @@ -131,7 +138,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataS ReflectionInfo = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests).GetMethod("GenericMethodDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -139,7 +146,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataS TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -153,17 +160,23 @@ internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataS }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.GenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.GenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -171,12 +184,12 @@ internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataS yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_GenericMethodDataSource__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_GenericMethodDataSource__string_TestSource()); } } @@ -188,7 +201,7 @@ internal static class InheritedTestsFromDifferentProjectTests_GenericMethodDataS #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -198,7 +211,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "NonGenericMethodDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(Pass), @@ -244,7 +257,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa ReflectionInfo = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests).GetMethod("NonGenericMethodDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -252,7 +265,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -266,17 +279,23 @@ internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.NonGenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.NonGenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -284,12 +303,12 @@ internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource__string_TestSource()); } } @@ -301,7 +320,7 @@ internal static class InheritedTestsFromDifferentProjectTests_NonGenericMethodDa #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -311,7 +330,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "VerifyInheritedCategoriesAreAvailable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(Pass), @@ -334,7 +353,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -342,7 +361,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -356,9 +375,16 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.VerifyInheritedCategoriesAreAvailable(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.VerifyInheritedCategoriesAreAvailable()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -366,12 +392,12 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource()); } } @@ -383,7 +409,7 @@ internal static class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -393,7 +419,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSourc TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "BaseTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.CategoryAttribute("BaseCategory"), @@ -417,7 +443,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSourc ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -425,7 +451,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSourc TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -439,10 +465,17 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSourc }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.BaseTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.BaseTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -450,12 +483,12 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTest_TestSourc yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_BaseTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_BaseTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTest_TestSource()); } } @@ -467,7 +500,7 @@ internal static class InheritedTestsFromDifferentProjectTests_BaseTest_ModuleIni #nullable enable namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -477,7 +510,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTestWithMultip TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), TestMethodName = "BaseTestWithMultipleCategories", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.CategoryAttribute("AnotherBaseCategory"), @@ -502,90 +535,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_BaseTestWithMultip ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => - { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "InheritedTestsFromDifferentProjectTests", - Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - instance.BaseTestWithMultipleCategories(); - await global::System.Threading.Tasks.Task.CompletedTask; - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "Test", - TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TestMethodName = "Test", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.TestProject.Attributes.EngineTest(Pass), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.CategoryAttribute("BaseCategoriesOnClass") - ], - DataSources = global::System.Array.Empty(), - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 5, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "Test", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -593,7 +543,7 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), Name = "InheritedTestsFromDifferentProjectTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -607,307 +557,17 @@ internal sealed class InheritedTestsFromDifferentProjectTests_Test_TestSource_GU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - instance.Test(); - await global::System.Threading.Tasks.Task.CompletedTask; - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class InheritedTestsFromDifferentProjectTests_Test_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_Test_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "GenericMethodDataSource", - TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TestMethodName = "GenericMethodDataSource", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.TestProject.Attributes.EngineTest(Pass), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.CategoryAttribute("BaseCategoriesOnClass") - ], - DataSources = new global::TUnit.Core.IDataSourceAttribute[] - { - new global::TUnit.Core.MethodDataSourceAttribute("Foo"), - }, - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 5, - MethodMetadata = new global::TUnit.Core.MethodMetadata + InvokeTypedTest = static (instance, args, cancellationToken) => { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "GenericMethodDataSource", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = new global::TUnit.Core.ParameterMetadata[] - { - new global::TUnit.Core.ParameterMetadata(typeof(string)) - { - Name = "value", - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(string)), - IsNullable = false, - ReflectionInfo = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests).GetMethod("GenericMethodDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] - } - }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => + try { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "InheritedTestsFromDifferentProjectTests", - Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - switch (args.Length) - { - case 1: - instance.GenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + instance.BaseTestWithMultipleCategories(); + return default(global::System.Threading.Tasks.ValueTask); } - await global::System.Threading.Tasks.Task.CompletedTask; - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_GenericMethodDataSource_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "NonGenericMethodDataSource", - TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TestMethodName = "NonGenericMethodDataSource", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.TestProject.Attributes.EngineTest(Pass), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.CategoryAttribute("BaseCategoriesOnClass") - ], - DataSources = new global::TUnit.Core.IDataSourceAttribute[] - { - new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.TestData), "Foo") + catch (global::System.Exception ex) { - Factory = (dataGeneratorMetadata) => - { - async global::System.Collections.Generic.IAsyncEnumerable>> Factory() - { - var result = global::TUnit.TestProject.TestData.Foo(); - yield return () => global::System.Threading.Tasks.Task.FromResult(global::TUnit.Core.Helpers.DataSourceHelpers.ToObjectArray(result)); - } - return Factory(); - } - }, - }, - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 5, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "NonGenericMethodDataSource", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = new global::TUnit.Core.ParameterMetadata[] - { - new global::TUnit.Core.ParameterMetadata(typeof(string)) - { - Name = "value", - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(string)), - IsNullable = false, - ReflectionInfo = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests).GetMethod("NonGenericMethodDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] - } - }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => - { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "InheritedTestsFromDifferentProjectTests", - Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - switch (args.Length) - { - case 1: - instance.NonGenericMethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_NonGenericMethodDataSource_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "VerifyInheritedCategoriesAreAvailable", - TestClassType = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TestMethodName = "VerifyInheritedCategoriesAreAvailable", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.TestProject.Attributes.EngineTest(Pass), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.CategoryAttribute("BaseCategoriesOnClass") - ], - DataSources = global::System.Array.Empty(), - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 5, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "VerifyInheritedCategoriesAreAvailable", - GenericTypeCount = 0, - ReturnType = typeof(global::System.Threading.Tasks.Task), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), - Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests", () => - { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests)), - Name = "InheritedTestsFromDifferentProjectTests", - Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - await instance.VerifyInheritedCategoriesAreAvailable(); }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -915,11 +575,11 @@ internal sealed class InheritedTestsFromDifferentProjectTests_VerifyInheritedCat yield break; } } -internal static class InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_ModuleInitializer_GUID +internal static class TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new InheritedTestsFromDifferentProjectTests_VerifyInheritedCategoriesAreAvailable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.InheritedTestsFromDifferentProjectTests), new TUnit_TestProject_InheritedTestsFromDifferentProjectTests_BaseTestWithMultipleCategories_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/InheritsTestsAbstractTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/InheritsTestsAbstractTests.Test.verified.txt index d707fe70a3..fdd9b1edda 100644 --- a/TUnit.Core.SourceGenerator.Tests/InheritsTestsAbstractTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/InheritsTestsAbstractTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "SecondTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -35,7 +35,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.SecondTest(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_SecondTest_TestSource()); } } @@ -85,7 +92,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute(), @@ -117,7 +124,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -125,7 +132,7 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), Name = "ConcreteClass2", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -139,91 +146,16 @@ internal sealed class ConcreteClass2_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); - }, - }; - metadata.UseRuntimeDataGeneration(testSessionId); - yield return metadata; - yield break; - } -} -internal static class ConcreteClass2_AssertClassName_ModuleInitializer_GUID -{ - [global::System.Runtime.CompilerServices.ModuleInitializer] - public static void Initialize() - { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_AssertClassName_TestSource_GUID()); - } -} - - -// ===== FILE SEPARATOR ===== - -// -#pragma warning disable - -#nullable enable -namespace TUnit.Generated; -internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource -{ - public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) - { - var metadata = new global::TUnit.Core.TestMetadata - { - TestName = "SecondTest", - TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TestMethodName = "SecondTest", - Dependencies = global::System.Array.Empty(), - AttributeFactory = () => - [ - new global::TUnit.Core.TestAttribute(), - new global::TUnit.Core.InheritsTestsAttribute(), - new global::TUnit.Core.InheritsTestsAttribute() - ], - DataSources = global::System.Array.Empty(), - ClassDataSources = global::System.Array.Empty(), - PropertyDataSources = global::System.Array.Empty(), - PropertyInjections = global::System.Array.Empty(), - InheritanceDepth = 0, - FilePath = @"", - LineNumber = 3, - MethodMetadata = new global::TUnit.Core.MethodMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "SecondTest", - GenericTypeCount = 0, - ReturnType = typeof(void), - ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), - Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass2", () => + try { - var classMetadata = new global::TUnit.Core.ClassMetadata - { - Type = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), - TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2)), - Name = "ConcreteClass2", - Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), - Parameters = global::System.Array.Empty(), - Properties = global::System.Array.Empty(), - Parent = null - }; - foreach (var prop in classMetadata.Properties) - { - prop.ClassMetadata = classMetadata; - prop.ContainingTypeMetadata = classMetadata; - } - return classMetadata; - }) - }, - InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass2(), - InvokeTypedTest = async (instance, args, cancellationToken) => - { - instance.SecondTest(); - await global::System.Threading.Tasks.Task.CompletedTask; + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -231,12 +163,12 @@ internal sealed class ConcreteClass2_SecondTest_TestSource_GUID : global::TUnit. yield break; } } -internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new ConcreteClass2_SecondTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass2), new TUnit_TestProject_AbstractTests_ConcreteClass2_AssertClassName_TestSource()); } } @@ -248,7 +180,7 @@ internal static class ConcreteClass2_SecondTest_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -258,7 +190,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), TestMethodName = "AssertClassName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.InheritsTestsAttribute() @@ -279,7 +211,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.AbstractTests.ConcreteClass1", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -287,7 +219,7 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1)), Name = "ConcreteClass1", Namespace = "TUnit.TestProject.AbstractTests", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -301,9 +233,16 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AbstractTests.ConcreteClass1(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.AssertClassName(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.AssertClassName()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -311,11 +250,11 @@ internal sealed class ConcreteClass1_AssertClassName_TestSource_GUID : global::T yield break; } } -internal static class ConcreteClass1_AssertClassName_ModuleInitializer_GUID +internal static class TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new ConcreteClass1_AssertClassName_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AbstractTests.ConcreteClass1), new TUnit_TestProject_AbstractTests_ConcreteClass1_AssertClassName_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/InheritsTestsTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/InheritsTestsTests.Test.verified.txt index ec9d285ff6..94339aecb1 100644 --- a/TUnit.Core.SourceGenerator.Tests/InheritsTestsTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/InheritsTestsTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1924_None_BaseClass_Test__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -17,12 +17,13 @@ internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interf TestClassType = typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(10), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) ], + RepeatCount = 10, DataSources = new global::TUnit.Core.IDataSourceAttribute[] { new global::TUnit.Core.ArgumentsAttribute(1), @@ -79,7 +80,7 @@ internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interf ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.BaseClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.BaseClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -87,7 +88,7 @@ internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interf TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass)), Name = "BaseClass", Namespace = "TUnit.TestProject.Bugs._1924.None", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -117,15 +118,21 @@ internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interf { Data = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -134,12 +141,12 @@ internal sealed class BaseClass_Test_TestSource_GUID : global::TUnit.Core.Interf yield break; } } -internal static class BaseClass_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1924_None_BaseClass_Test__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass), new BaseClass_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass), new TUnit_TestProject_Bugs__1924_None_BaseClass_Test__int_TestSource()); } } @@ -151,7 +158,7 @@ internal static class BaseClass_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1924_None_Tests_Test__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -165,13 +172,14 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TestClassType = typeof(global::TUnit.TestProject.Bugs._1924.None.Tests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(10), new global::TUnit.Core.InheritsTestsAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) ], + RepeatCount = 10, DataSources = new global::TUnit.Core.IDataSourceAttribute[] { new global::TUnit.Core.ArgumentsAttribute(1), @@ -228,7 +236,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -236,7 +244,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1924.None", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -253,15 +261,21 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces { Data = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -270,12 +284,12 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces yield break; } } -internal static class Tests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1924_None_Tests_Test__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests), new Tests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests), new TUnit_TestProject_Bugs__1924_None_Tests_Test__int_TestSource()); } } @@ -287,7 +301,7 @@ internal static class Tests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1924_None_Tests2_Test__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -301,13 +315,14 @@ internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interface TestClassType = typeof(global::TUnit.TestProject.Bugs._1924.None.Tests2), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(10), new global::TUnit.Core.InheritsTestsAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) ], + RepeatCount = 10, DataSources = new global::TUnit.Core.IDataSourceAttribute[] { new global::TUnit.Core.ArgumentsAttribute(1), @@ -364,7 +379,7 @@ internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interface ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests2", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests2", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -372,7 +387,7 @@ internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interface TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests2)), Name = "Tests2", Namespace = "TUnit.TestProject.Bugs._1924.None", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -389,15 +404,21 @@ internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interface { Data = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -406,12 +427,12 @@ internal sealed class Tests2_Test_TestSource_GUID : global::TUnit.Core.Interface yield break; } } -internal static class Tests2_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1924_None_Tests2_Test__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests2), new Tests2_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests2), new TUnit_TestProject_Bugs__1924_None_Tests2_Test__int_TestSource()); } } @@ -423,7 +444,7 @@ internal static class Tests2_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1924_None_Tests3_Test__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -437,13 +458,14 @@ internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interface TestClassType = typeof(global::TUnit.TestProject.Bugs._1924.None.Tests3), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(10), new global::TUnit.Core.InheritsTestsAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) ], + RepeatCount = 10, DataSources = new global::TUnit.Core.IDataSourceAttribute[] { new global::TUnit.Core.ArgumentsAttribute(1), @@ -500,7 +522,7 @@ internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interface ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1924.None.BaseClass).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests3", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1924.None.Tests3", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -508,7 +530,7 @@ internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interface TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests3)), Name = "Tests3", Namespace = "TUnit.TestProject.Bugs._1924.None", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -525,15 +547,21 @@ internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interface { Data = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -542,11 +570,11 @@ internal sealed class Tests3_Test_TestSource_GUID : global::TUnit.Core.Interface yield break; } } -internal static class Tests3_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1924_None_Tests3_Test__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests3), new Tests3_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1924.None.Tests3), new TUnit_TestProject_Bugs__1924_None_Tests3_Test__int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Issue2887Tests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Issue2887Tests.Test.verified.txt index bea8884396..716c20d744 100644 --- a/TUnit.Core.SourceGenerator.Tests/Issue2887Tests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Issue2887Tests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__Issue2887_ActualTestClass_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core TestClassType = typeof(global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ClassConstructorAttribute() @@ -34,7 +34,7 @@ internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass)), Name = "ActualTestClass", Namespace = "TUnit.TestProject.Bugs._Issue2887", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._Issue2887.IServiceProvider)) @@ -69,10 +69,17 @@ internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core // ClassConstructor attribute is present - instance creation handled at runtime throw new global::System.NotSupportedException("Instance creation for classes with ClassConstructor attribute is handled at runtime"); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -80,11 +87,11 @@ internal sealed class ActualTestClass_Test1_TestSource_GUID : global::TUnit.Core yield break; } } -internal static class ActualTestClass_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__Issue2887_ActualTestClass_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass), new ActualTestClass_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._Issue2887.ActualTestClass), new TUnit_TestProject_Bugs__Issue2887_ActualTestClass_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/MatrixTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/MatrixTests.Test.verified.txt index 3a0fcf13fe..f3e953ed52 100644 --- a/TUnit.Core.SourceGenerator.Tests/MatrixTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/MatrixTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_MatrixTest_One__string_int_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "MatrixTest_One", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -60,7 +60,7 @@ internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("MatrixTest_One", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(int), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -68,7 +68,7 @@ internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -82,15 +82,21 @@ internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - await instance.MatrixTest_One(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.MatrixTest_One(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -99,12 +105,12 @@ internal sealed class MatrixTests_MatrixTest_One_TestSource_GUID : global::TUnit yield break; } } -internal static class MatrixTests_MatrixTest_One_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_MatrixTest_One__string_int_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_MatrixTest_One_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_MatrixTest_One__string_int_bool_TestSource()); } } @@ -116,7 +122,7 @@ internal static class MatrixTests_MatrixTest_One_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_MatrixTest_Two__int_int_int_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -126,7 +132,7 @@ internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "MatrixTest_Two", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -180,7 +186,7 @@ internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("MatrixTest_Two", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(int), typeof(int), typeof(bool) }, null)!.GetParameters()[3] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -188,7 +194,7 @@ internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -202,15 +208,21 @@ internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 4: + return new global::System.Threading.Tasks.ValueTask(instance.MatrixTest_Two(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]))); + default: + throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 4: - await instance.MatrixTest_Two(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 4 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -219,12 +231,12 @@ internal sealed class MatrixTests_MatrixTest_Two_TestSource_GUID : global::TUnit yield break; } } -internal static class MatrixTests_MatrixTest_Two_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_MatrixTest_Two__int_int_int_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_MatrixTest_Two_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_MatrixTest_Two__int_int_int_bool_TestSource()); } } @@ -236,7 +248,7 @@ internal static class MatrixTests_MatrixTest_Two_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_MatrixTest_Enum__int_TestEnum_TestEnum__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -246,7 +258,7 @@ internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUni TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "MatrixTest_Enum", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -293,7 +305,7 @@ internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUni ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("MatrixTest_Enum", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::TUnit.TestProject.TestEnum), typeof(global::TUnit.TestProject.TestEnum?) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -301,7 +313,7 @@ internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUni TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -315,15 +327,21 @@ internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUni }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 3: + return new global::System.Threading.Tasks.ValueTask(instance.MatrixTest_Enum(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]))); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 3: - await instance.MatrixTest_Enum(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -332,12 +350,12 @@ internal sealed class MatrixTests_MatrixTest_Enum_TestSource_GUID : global::TUni yield break; } } -internal static class MatrixTests_MatrixTest_Enum_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_MatrixTest_Enum__int_TestEnum_TestEnum__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_MatrixTest_Enum_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_MatrixTest_Enum__int_TestEnum_TestEnum__TestSource()); } } @@ -349,7 +367,7 @@ internal static class MatrixTests_MatrixTest_Enum_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_AutoGenerateBools__string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -359,7 +377,7 @@ internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "AutoGenerateBools", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -399,7 +417,7 @@ internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TU ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("AutoGenerateBools", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(bool) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -407,7 +425,7 @@ internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -421,15 +439,21 @@ internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 2: - await instance.AutoGenerateBools(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.AutoGenerateBools(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -438,12 +462,12 @@ internal sealed class MatrixTests_AutoGenerateBools_TestSource_GUID : global::TU yield break; } } -internal static class MatrixTests_AutoGenerateBools_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_AutoGenerateBools__string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_AutoGenerateBools_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_AutoGenerateBools__string_bool_TestSource()); } } @@ -455,7 +479,7 @@ internal static class MatrixTests_AutoGenerateBools_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_AutoGenerateBools2__string_bool__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -465,7 +489,7 @@ internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "AutoGenerateBools2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -505,7 +529,7 @@ internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("AutoGenerateBools2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(bool?) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -513,7 +537,7 @@ internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -527,15 +551,21 @@ internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.AutoGenerateBools2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.AutoGenerateBools2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -544,12 +574,12 @@ internal sealed class MatrixTests_AutoGenerateBools2_TestSource_GUID : global::T yield break; } } -internal static class MatrixTests_AutoGenerateBools2_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_AutoGenerateBools2__string_bool__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_AutoGenerateBools2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_AutoGenerateBools2__string_bool__TestSource()); } } @@ -561,7 +591,7 @@ internal static class MatrixTests_AutoGenerateBools2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_ImplicitConversion__OneOf_TestEnum__TestEnum2__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -571,7 +601,7 @@ internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "ImplicitConversion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -611,7 +641,7 @@ internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("ImplicitConversion", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(OneOf), typeof(bool) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -619,7 +649,7 @@ internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -633,15 +663,21 @@ internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.ImplicitConversion(TUnit.Core.Helpers.CastHelper.Cast>(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.ImplicitConversion(TUnit.Core.Helpers.CastHelper.Cast>(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -650,12 +686,12 @@ internal sealed class MatrixTests_ImplicitConversion_TestSource_GUID : global::T yield break; } } -internal static class MatrixTests_ImplicitConversion_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_ImplicitConversion__OneOf_TestEnum__TestEnum2__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_ImplicitConversion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_ImplicitConversion__OneOf_TestEnum__TestEnum2__bool_TestSource()); } } @@ -667,7 +703,7 @@ internal static class MatrixTests_ImplicitConversion_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_ExcludingAutoGeneratedMatrixValues__CountToTenEnum_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -677,7 +713,7 @@ internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_ TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "ExcludingAutoGeneratedMatrixValues", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -717,7 +753,7 @@ internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("ExcludingAutoGeneratedMatrixValues", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.MatrixTests.CountToTenEnum), typeof(bool) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -725,7 +761,7 @@ internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -739,15 +775,21 @@ internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 2: - await instance.ExcludingAutoGeneratedMatrixValues(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.ExcludingAutoGeneratedMatrixValues(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -756,12 +798,12 @@ internal sealed class MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_ yield break; } } -internal static class MatrixTests_ExcludingAutoGeneratedMatrixValues_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_ExcludingAutoGeneratedMatrixValues__CountToTenEnum_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_ExcludingAutoGeneratedMatrixValues_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_ExcludingAutoGeneratedMatrixValues__CountToTenEnum_bool_TestSource()); } } @@ -773,7 +815,7 @@ internal static class MatrixTests_ExcludingAutoGeneratedMatrixValues_ModuleIniti #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_Method1__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -783,7 +825,7 @@ internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.I TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "Method1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -816,7 +858,7 @@ internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.I ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("Method1", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -824,7 +866,7 @@ internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.I TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -838,15 +880,21 @@ internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.I }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Method1(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Method1(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -855,12 +903,12 @@ internal sealed class MatrixTests_Method1_TestSource_GUID : global::TUnit.Core.I yield break; } } -internal static class MatrixTests_Method1_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_Method1__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_Method1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_Method1__int_TestSource()); } } @@ -872,7 +920,7 @@ internal static class MatrixTests_Method1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_Method2__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -882,7 +930,7 @@ internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.I TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "Method2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -915,7 +963,7 @@ internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.I ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("Method2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -923,7 +971,7 @@ internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.I TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -937,15 +985,21 @@ internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.I }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -954,12 +1008,12 @@ internal sealed class MatrixTests_Method2_TestSource_GUID : global::TUnit.Core.I yield break; } } -internal static class MatrixTests_Method2_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_Method2__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_Method2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_Method2__int_TestSource()); } } @@ -971,7 +1025,7 @@ internal static class MatrixTests_Method2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_Method3__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -981,7 +1035,7 @@ internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.I TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "Method3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -1014,7 +1068,7 @@ internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.I ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("Method3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1022,7 +1076,7 @@ internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.I TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1036,15 +1090,21 @@ internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.I }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1053,12 +1113,12 @@ internal sealed class MatrixTests_Method3_TestSource_GUID : global::TUnit.Core.I yield break; } } -internal static class MatrixTests_Method3_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_Method3__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_Method3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_Method3__int_TestSource()); } } @@ -1070,7 +1130,7 @@ internal static class MatrixTests_Method3_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_Method4__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1080,7 +1140,7 @@ internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.I TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "Method4", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -1113,7 +1173,7 @@ internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.I ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("Method4", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1121,7 +1181,7 @@ internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.I TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1135,15 +1195,21 @@ internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.I }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Method4(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Method4(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1152,12 +1218,12 @@ internal sealed class MatrixTests_Method4_TestSource_GUID : global::TUnit.Core.I yield break; } } -internal static class MatrixTests_Method4_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_Method4__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_Method4_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_Method4__int_TestSource()); } } @@ -1169,7 +1235,7 @@ internal static class MatrixTests_Method4_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MatrixTests_Exclusion__int_int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1179,7 +1245,7 @@ internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core TestClassType = typeof(global::TUnit.TestProject.MatrixTests), TestMethodName = "Exclusion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.MatrixExclusionAttribute(1, 1), @@ -1222,7 +1288,7 @@ internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core ReflectionInfo = typeof(global::TUnit.TestProject.MatrixTests).GetMethod("Exclusion", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(int) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MatrixTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1230,7 +1296,7 @@ internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MatrixTests)), Name = "MatrixTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1244,15 +1310,21 @@ internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MatrixTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + return new global::System.Threading.Tasks.ValueTask(instance.Exclusion(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - await instance.Exclusion(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -1261,11 +1333,11 @@ internal sealed class MatrixTests_Exclusion_TestSource_GUID : global::TUnit.Core yield break; } } -internal static class MatrixTests_Exclusion_ModuleInitializer_GUID +internal static class TUnit_TestProject_MatrixTests_Exclusion__int_int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new MatrixTests_Exclusion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MatrixTests), new TUnit_TestProject_MatrixTests_Exclusion__int_int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenTests.Test.verified.txt index 57b813f643..4ac45b08bb 100644 --- a/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_G TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_Method", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -57,7 +57,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_G ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_Method", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -65,7 +65,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -79,17 +79,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_G }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Method(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -97,12 +103,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_TestSource_G yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_Method_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_Method_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method__int_TestSource()); } } @@ -114,7 +120,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_Method_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method2__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -124,7 +130,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_ TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_Method2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -168,7 +174,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_Method2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -176,7 +182,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -190,17 +196,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_Method2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -208,12 +220,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method2_TestSource_ yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_Method2_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method2__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_Method2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method2__int_TestSource()); } } @@ -225,7 +237,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_Method2_ModuleIniti #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method_WithAction__Action_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -235,7 +247,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_T TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_Method_WithAction", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -279,7 +291,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_T ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_Method_WithAction", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Action) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -287,7 +299,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -301,17 +313,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Method_WithAction(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Method_WithAction(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -319,12 +337,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method_WithAction_T yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_Method_WithAction_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method_WithAction__Action_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_Method_WithAction_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method_WithAction__Action_TestSource()); } } @@ -336,7 +354,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_Method_WithAction_M #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method3__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -346,7 +364,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_ TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_Method3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -405,7 +423,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_Method3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -413,7 +431,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -427,17 +445,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_Method3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -445,12 +469,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method3_TestSource_ yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_Method3_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method3__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_Method3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method3__int_TestSource()); } } @@ -462,7 +486,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_Method3_ModuleIniti #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method4__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -472,7 +496,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_ TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_Method4", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -558,7 +582,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_ ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_Method4", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -566,7 +590,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_ TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -580,17 +604,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_ }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.DataSource_Method4(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.DataSource_Method4(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -598,12 +628,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_Method4_TestSource_ yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_Method4_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method4__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_Method4_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_Method4__int_TestSource()); } } @@ -615,7 +645,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_Method4_ModuleIniti #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -625,7 +655,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Test TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "DataSource_WithBaseReturn", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -669,7 +699,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Test ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("DataSource_WithBaseReturn", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests.BaseValue) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -677,7 +707,7 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Test TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -691,17 +721,23 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Test }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.DataSource_WithBaseReturn(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.DataSource_WithBaseReturn(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -709,12 +745,12 @@ internal sealed class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Test yield break; } } -internal static class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_DataSource_WithBaseReturn_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_DataSource_WithBaseReturn__BaseValue_TestSource()); } } @@ -726,7 +762,7 @@ internal static class MethodDataSourceDrivenTests_DataSource_WithBaseReturn_Modu #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenTests_EnumerableFuncArrayTest__string___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -736,7 +772,7 @@ internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSo TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), TestMethodName = "EnumerableFuncArrayTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -790,7 +826,7 @@ internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSo ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests).GetMethod("EnumerableFuncArrayTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string[]) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -798,7 +834,7 @@ internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests)), Name = "MethodDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -812,15 +848,21 @@ internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.EnumerableFuncArrayTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.EnumerableFuncArrayTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -829,11 +871,11 @@ internal sealed class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSo yield break; } } -internal static class MethodDataSourceDrivenTests_EnumerableFuncArrayTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenTests_EnumerableFuncArrayTest__string___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new MethodDataSourceDrivenTests_EnumerableFuncArrayTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenTests), new TUnit_TestProject_MethodDataSourceDrivenTests_EnumerableFuncArrayTest__string___TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenWithCancellationTokenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenWithCancellationTokenTests.Test.verified.txt index 1eaea23564..91193caa00 100644 --- a/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenWithCancellationTokenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/MethodDataSourceDrivenWithCancellationTokenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MethodDataSourceDrivenWithCancellationTokenTests_MyTest__int_CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_Te TestClassType = typeof(global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests), TestMethodName = "MyTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -165,7 +165,7 @@ internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_Te ReflectionInfo = typeof(global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests).GetMethod("MyTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -173,7 +173,7 @@ internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_Te TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests)), Name = "MethodDataSourceDrivenWithCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -187,18 +187,24 @@ internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_Te }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var context = global::TUnit.Core.TestContext.Current; - switch (args.Length) + try { - case 1: - instance.MyTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + var context = global::TUnit.Core.TestContext.Current; + switch (args.Length) + { + case 1: + instance.MyTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -206,11 +212,11 @@ internal sealed class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_Te yield break; } } -internal static class MethodDataSourceDrivenWithCancellationTokenTests_MyTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_MethodDataSourceDrivenWithCancellationTokenTests_MyTest__int_CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests), new MethodDataSourceDrivenWithCancellationTokenTests_MyTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MethodDataSourceDrivenWithCancellationTokenTests), new TUnit_TestProject_MethodDataSourceDrivenWithCancellationTokenTests_MyTest__int_CancellationToken_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/MultipleClassDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/MultipleClassDataSourceDrivenTests.Test.verified.txt index d2eb0561e2..e96980da8b 100644 --- a/TUnit.Core.SourceGenerator.Tests/MultipleClassDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/MultipleClassDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MultipleClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MultipleClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests)), Name = "MultipleClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests.Inject1)) @@ -102,10 +102,17 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : { return new global::TUnit.TestProject.MultipleClassDataSourceDrivenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -113,12 +120,12 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID : yield break; } } -internal static class MultipleClassDataSourceDrivenTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), new MultipleClassDataSourceDrivenTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), new TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test1_TestSource()); } } @@ -130,7 +137,7 @@ internal static class MultipleClassDataSourceDrivenTests_Test1_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -140,7 +147,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -167,7 +174,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MultipleClassDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.MultipleClassDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -175,7 +182,7 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests)), Name = "MultipleClassDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests.Inject1)) @@ -229,10 +236,17 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : { return new global::TUnit.TestProject.MultipleClassDataSourceDrivenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test2(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test2(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -240,11 +254,11 @@ internal sealed class MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID : yield break; } } -internal static class MultipleClassDataSourceDrivenTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), new MultipleClassDataSourceDrivenTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.MultipleClassDataSourceDrivenTests), new TUnit_TestProject_MultipleClassDataSourceDrivenTests_Test2_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/NameOfArgumentTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/NameOfArgumentTests.Test.verified.txt index 7c31faacbb..a89cf44b80 100644 --- a/TUnit.Core.SourceGenerator.Tests/NameOfArgumentTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/NameOfArgumentTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NameOfArgumentTests_TestName__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.NameOfArgumentTests), TestMethodName = "TestName", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.NameOfArgumentTests).GetMethod("TestName", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NameOfArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NameOfArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NameOfArgumentTests)), Name = "NameOfArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NameOfArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.TestName(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.TestName(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,11 +91,11 @@ internal sealed class NameOfArgumentTests_TestName_TestSource_GUID : global::TUn yield break; } } -internal static class NameOfArgumentTests_TestName_ModuleInitializer_GUID +internal static class TUnit_TestProject_NameOfArgumentTests_TestName__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NameOfArgumentTests), new NameOfArgumentTests_TestName_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NameOfArgumentTests), new TUnit_TestProject_NameOfArgumentTests_TestName__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/NullableByteArgumentTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/NullableByteArgumentTests.Test.verified.txt index 8b0b835493..7683db8709 100644 --- a/TUnit.Core.SourceGenerator.Tests/NullableByteArgumentTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/NullableByteArgumentTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NullableByteArgumentTests_Test__byte__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.NullableByteArgumentTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -47,7 +47,7 @@ internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::T ReflectionInfo = typeof(global::TUnit.TestProject.NullableByteArgumentTests).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(byte?) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NullableByteArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NullableByteArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -55,7 +55,7 @@ internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NullableByteArgumentTests)), Name = "NullableByteArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -69,17 +69,23 @@ internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NullableByteArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -87,12 +93,12 @@ internal sealed class NullableByteArgumentTests_Test_TestSource_GUID : global::T yield break; } } -internal static class NullableByteArgumentTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_NullableByteArgumentTests_Test__byte__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NullableByteArgumentTests), new NullableByteArgumentTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NullableByteArgumentTests), new TUnit_TestProject_NullableByteArgumentTests_Test__byte__TestSource()); } } @@ -104,7 +110,7 @@ internal static class NullableByteArgumentTests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NullableByteArgumentTests_Test2__byte_byte__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -114,7 +120,7 @@ internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.NullableByteArgumentTests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -155,7 +161,7 @@ internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global:: ReflectionInfo = typeof(global::TUnit.TestProject.NullableByteArgumentTests).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(byte), typeof(byte?) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NullableByteArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NullableByteArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -163,7 +169,7 @@ internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NullableByteArgumentTests)), Name = "NullableByteArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -177,17 +183,23 @@ internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NullableByteArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 2: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 2: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -195,11 +207,11 @@ internal sealed class NullableByteArgumentTests_Test2_TestSource_GUID : global:: yield break; } } -internal static class NullableByteArgumentTests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_NullableByteArgumentTests_Test2__byte_byte__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NullableByteArgumentTests), new NullableByteArgumentTests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NullableByteArgumentTests), new TUnit_TestProject_NullableByteArgumentTests_Test2__byte_byte__TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.Test.verified.txt index 232c005380..f953755712 100644 --- a/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Int__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Int", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Int", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,17 +68,23 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -86,12 +92,12 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class NumberArgumentTests_Int_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Int__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Int_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Int__int_TestSource()); } } @@ -103,7 +109,7 @@ internal static class NumberArgumentTests_Int_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Double__double_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -113,7 +119,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Double", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -146,7 +152,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Double", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(double) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -154,7 +160,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -168,17 +174,23 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -186,12 +198,12 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit yield break; } } -internal static class NumberArgumentTests_Double_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Double__double_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Double_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Double__double_TestSource()); } } @@ -203,7 +215,7 @@ internal static class NumberArgumentTests_Double_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Float__float_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -213,7 +225,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Float", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -246,7 +258,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Float", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(float) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -254,7 +266,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -268,17 +280,23 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -286,12 +304,12 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. yield break; } } -internal static class NumberArgumentTests_Float_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Float__float_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Float_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Float__float_TestSource()); } } @@ -303,7 +321,7 @@ internal static class NumberArgumentTests_Float_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Long__long_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -313,7 +331,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Long", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -346,7 +364,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Long", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(long) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -354,7 +372,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -368,17 +386,23 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -386,12 +410,12 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C yield break; } } -internal static class NumberArgumentTests_Long_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Long__long_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Long_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Long__long_TestSource()); } } @@ -403,7 +427,7 @@ internal static class NumberArgumentTests_Long_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_ULong__ulong_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -413,7 +437,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "ULong", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -446,7 +470,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("ULong", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(ulong) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -454,7 +478,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -468,17 +492,23 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -486,12 +516,12 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. yield break; } } -internal static class NumberArgumentTests_ULong_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_ULong__ulong_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_ULong_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_ULong__ulong_TestSource()); } } @@ -503,7 +533,7 @@ internal static class NumberArgumentTests_ULong_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_UInt__uint_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -513,7 +543,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "UInt", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -546,7 +576,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("UInt", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(uint) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -554,7 +584,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -568,17 +598,23 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -586,11 +622,11 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C yield break; } } -internal static class NumberArgumentTests_UInt_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_UInt__uint_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_UInt_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_UInt__uint_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.TestDE.verified.txt b/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.TestDE.verified.txt index 232c005380..f953755712 100644 --- a/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.TestDE.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/NumberArgumentTests.TestDE.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Int__int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Int", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Int", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,17 +68,23 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Int(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -86,12 +92,12 @@ internal sealed class NumberArgumentTests_Int_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class NumberArgumentTests_Int_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Int__int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Int_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Int__int_TestSource()); } } @@ -103,7 +109,7 @@ internal static class NumberArgumentTests_Int_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Double__double_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -113,7 +119,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Double", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -146,7 +152,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Double", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(double) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -154,7 +160,7 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -168,17 +174,23 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Double(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -186,12 +198,12 @@ internal sealed class NumberArgumentTests_Double_TestSource_GUID : global::TUnit yield break; } } -internal static class NumberArgumentTests_Double_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Double__double_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Double_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Double__double_TestSource()); } } @@ -203,7 +215,7 @@ internal static class NumberArgumentTests_Double_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Float__float_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -213,7 +225,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Float", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -246,7 +258,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Float", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(float) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -254,7 +266,7 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -268,17 +280,23 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Float(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -286,12 +304,12 @@ internal sealed class NumberArgumentTests_Float_TestSource_GUID : global::TUnit. yield break; } } -internal static class NumberArgumentTests_Float_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Float__float_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Float_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Float__float_TestSource()); } } @@ -303,7 +321,7 @@ internal static class NumberArgumentTests_Float_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_Long__long_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -313,7 +331,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "Long", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -346,7 +364,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("Long", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(long) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -354,7 +372,7 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -368,17 +386,23 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Long(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -386,12 +410,12 @@ internal sealed class NumberArgumentTests_Long_TestSource_GUID : global::TUnit.C yield break; } } -internal static class NumberArgumentTests_Long_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_Long__long_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_Long_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_Long__long_TestSource()); } } @@ -403,7 +427,7 @@ internal static class NumberArgumentTests_Long_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_ULong__ulong_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -413,7 +437,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "ULong", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -446,7 +470,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("ULong", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(ulong) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -454,7 +478,7 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -468,17 +492,23 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.ULong(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -486,12 +516,12 @@ internal sealed class NumberArgumentTests_ULong_TestSource_GUID : global::TUnit. yield break; } } -internal static class NumberArgumentTests_ULong_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_ULong__ulong_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_ULong_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_ULong__ulong_TestSource()); } } @@ -503,7 +533,7 @@ internal static class NumberArgumentTests_ULong_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_NumberArgumentTests_UInt__uint_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -513,7 +543,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.NumberArgumentTests), TestMethodName = "UInt", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -546,7 +576,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C ReflectionInfo = typeof(global::TUnit.TestProject.NumberArgumentTests).GetMethod("UInt", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(uint) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.NumberArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -554,7 +584,7 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.NumberArgumentTests)), Name = "NumberArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -568,17 +598,23 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.NumberArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.UInt(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -586,11 +622,11 @@ internal sealed class NumberArgumentTests_UInt_TestSource_GUID : global::TUnit.C yield break; } } -internal static class NumberArgumentTests_UInt_ModuleInitializer_GUID +internal static class TUnit_TestProject_NumberArgumentTests_UInt__uint_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new NumberArgumentTests_UInt_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.NumberArgumentTests), new TUnit_TestProject_NumberArgumentTests_UInt__uint_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/PriorityFilteringTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/PriorityFilteringTests.Test.verified.txt index e898fd0735..90776b2e04 100644 --- a/TUnit.Core.SourceGenerator.Tests/PriorityFilteringTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/PriorityFilteringTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_High_1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "High_1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.High) @@ -34,7 +34,7 @@ internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TU ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -42,7 +42,7 @@ internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -56,9 +56,16 @@ internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.High_1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.High_1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,12 +73,12 @@ internal sealed class PriorityFilteringTests_High_1_TestSource_GUID : global::TU yield break; } } -internal static class PriorityFilteringTests_High_1_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_High_1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_High_1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_High_1_TestSource()); } } @@ -83,7 +90,7 @@ internal static class PriorityFilteringTests_High_1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_High_2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -93,7 +100,7 @@ internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "High_2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.High) @@ -114,7 +121,7 @@ internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TU ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -122,7 +129,7 @@ internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -136,9 +143,16 @@ internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.High_2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.High_2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -146,12 +160,12 @@ internal sealed class PriorityFilteringTests_High_2_TestSource_GUID : global::TU yield break; } } -internal static class PriorityFilteringTests_High_2_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_High_2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_High_2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_High_2_TestSource()); } } @@ -163,7 +177,7 @@ internal static class PriorityFilteringTests_High_2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_High_3_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -173,7 +187,7 @@ internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TU TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "High_3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.High) @@ -194,7 +208,7 @@ internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TU ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -202,7 +216,7 @@ internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -216,9 +230,16 @@ internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TU }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.High_3(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.High_3()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -226,12 +247,12 @@ internal sealed class PriorityFilteringTests_High_3_TestSource_GUID : global::TU yield break; } } -internal static class PriorityFilteringTests_High_3_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_High_3_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_High_3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_High_3_TestSource()); } } @@ -243,7 +264,7 @@ internal static class PriorityFilteringTests_High_3_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_Medium_1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -253,7 +274,7 @@ internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "Medium_1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.Medium) @@ -274,7 +295,7 @@ internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global:: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -282,7 +303,7 @@ internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -296,9 +317,16 @@ internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Medium_1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Medium_1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -306,12 +334,12 @@ internal sealed class PriorityFilteringTests_Medium_1_TestSource_GUID : global:: yield break; } } -internal static class PriorityFilteringTests_Medium_1_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_Medium_1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_Medium_1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_Medium_1_TestSource()); } } @@ -323,7 +351,7 @@ internal static class PriorityFilteringTests_Medium_1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_Medium_2_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -333,7 +361,7 @@ internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "Medium_2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.Medium) @@ -354,7 +382,7 @@ internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global:: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -362,7 +390,7 @@ internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -376,9 +404,16 @@ internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Medium_2(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Medium_2()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -386,12 +421,12 @@ internal sealed class PriorityFilteringTests_Medium_2_TestSource_GUID : global:: yield break; } } -internal static class PriorityFilteringTests_Medium_2_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_Medium_2_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_Medium_2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_Medium_2_TestSource()); } } @@ -403,7 +438,7 @@ internal static class PriorityFilteringTests_Medium_2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PriorityFilteringTests_Low_1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -413,7 +448,7 @@ internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.PriorityFilteringTests), TestMethodName = "Low_1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.PriorityAttribute(global::TUnit.TestProject.Enums.PriorityLevel.Low) @@ -434,7 +469,7 @@ internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUn ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PriorityFilteringTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -442,7 +477,7 @@ internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PriorityFilteringTests)), Name = "PriorityFilteringTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -456,9 +491,16 @@ internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.PriorityFilteringTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Low_1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Low_1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -466,11 +508,11 @@ internal sealed class PriorityFilteringTests_Low_1_TestSource_GUID : global::TUn yield break; } } -internal static class PriorityFilteringTests_Low_1_ModuleInitializer_GUID +internal static class TUnit_TestProject_PriorityFilteringTests_Low_1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new PriorityFilteringTests_Low_1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PriorityFilteringTests), new TUnit_TestProject_PriorityFilteringTests_Low_1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/PropertySetterTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/PropertySetterTests.Test.verified.txt index 393b67c291..6ca53de893 100644 --- a/TUnit.Core.SourceGenerator.Tests/PropertySetterTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/PropertySetterTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_PropertySetterTests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { #if NET8_0_OR_GREATER [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "k__BackingField")] @@ -27,7 +27,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C TestClassType = typeof(global::TUnit.TestProject.PropertySetterTests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -199,7 +199,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PropertySetterTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.PropertySetterTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -207,7 +207,7 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.PropertySetterTests)), Name = "PropertySetterTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = new global::TUnit.Core.PropertyMetadata[] { @@ -320,9 +320,16 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C Property6 = default!, Property7 = default!, }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -330,11 +337,11 @@ internal sealed class PropertySetterTests_Test_TestSource_GUID : global::TUnit.C yield break; } } -internal static class PropertySetterTests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_PropertySetterTests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PropertySetterTests), new PropertySetterTests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.PropertySetterTests), new TUnit_TestProject_PropertySetterTests_Test_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/RepeatTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/RepeatTests.Test.verified.txt index 93bb58d725..c359cf4a4f 100644 --- a/TUnit.Core.SourceGenerator.Tests/RepeatTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/RepeatTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_RepeatTests_One_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,13 +13,14 @@ internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Inter TestClassType = typeof(global::TUnit.TestProject.RepeatTests), TestMethodName = "One", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(1), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), new global::TUnit.Core.RepeatAttribute(3) ], + RepeatCount = 1, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -36,7 +37,7 @@ internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Inter ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -44,7 +45,7 @@ internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Inter TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.RepeatTests)), Name = "RepeatTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -58,10 +59,17 @@ internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Inter }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.RepeatTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.One(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.One(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -69,12 +77,12 @@ internal sealed class RepeatTests_One_TestSource_GUID : global::TUnit.Core.Inter yield break; } } -internal static class RepeatTests_One_ModuleInitializer_GUID +internal static class TUnit_TestProject_RepeatTests_One_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new RepeatTests_One_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new TUnit_TestProject_RepeatTests_One_TestSource()); } } @@ -86,7 +94,7 @@ internal static class RepeatTests_One_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_RepeatTests_Two_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -96,13 +104,14 @@ internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Inter TestClassType = typeof(global::TUnit.TestProject.RepeatTests), TestMethodName = "Two", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.RepeatAttribute(2), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), new global::TUnit.Core.RepeatAttribute(3) ], + RepeatCount = 2, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -119,7 +128,7 @@ internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Inter ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -127,7 +136,7 @@ internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Inter TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.RepeatTests)), Name = "RepeatTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -141,10 +150,17 @@ internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Inter }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.RepeatTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Two(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Two(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -152,12 +168,12 @@ internal sealed class RepeatTests_Two_TestSource_GUID : global::TUnit.Core.Inter yield break; } } -internal static class RepeatTests_Two_ModuleInitializer_GUID +internal static class TUnit_TestProject_RepeatTests_Two_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new RepeatTests_Two_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new TUnit_TestProject_RepeatTests_Two_TestSource()); } } @@ -169,7 +185,7 @@ internal static class RepeatTests_Two_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_RepeatTests_Three_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -179,12 +195,13 @@ internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.RepeatTests), TestMethodName = "Three", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), new global::TUnit.Core.RepeatAttribute(3) ], + RepeatCount = 3, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -201,7 +218,7 @@ internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.RepeatTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -209,7 +226,7 @@ internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.RepeatTests)), Name = "RepeatTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -223,10 +240,17 @@ internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.RepeatTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Three(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Three(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -234,11 +258,11 @@ internal sealed class RepeatTests_Three_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class RepeatTests_Three_ModuleInitializer_GUID +internal static class TUnit_TestProject_RepeatTests_Three_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new RepeatTests_Three_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.RepeatTests), new TUnit_TestProject_RepeatTests_Three_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet10_0.verified.txt index e869041ae4..6f2ad0396b 100644 --- a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_With_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "With_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -22,6 +22,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -38,7 +39,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -46,7 +47,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -60,9 +61,16 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.With_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.With_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -70,12 +78,12 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class STAThreadTests_With_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_With_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_With_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_With_STA_TestSource()); } } @@ -87,7 +95,7 @@ internal static class STAThreadTests_With_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_Without_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -97,7 +105,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "Without_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -105,6 +113,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -121,7 +130,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -129,7 +138,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -143,9 +152,16 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Without_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Without_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -153,12 +169,12 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit yield break; } } -internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_Without_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_Without_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_Without_STA_TestSource()); } } @@ -170,7 +186,7 @@ internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -180,7 +196,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithSimpleAwait", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -189,6 +205,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -205,7 +222,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -213,7 +230,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -227,9 +244,16 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithSimpleAwait(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithSimpleAwait()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -237,12 +261,12 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithSimpleAwait_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource()); } } @@ -254,7 +278,7 @@ internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -264,7 +288,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskYield", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -273,6 +297,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -289,7 +314,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -297,7 +322,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -311,9 +336,16 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskYield(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskYield()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -321,12 +353,12 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: yield break; } } -internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskYield_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource()); } } @@ -338,7 +370,7 @@ internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -348,7 +380,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithConfigureAwaitTrue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -357,6 +389,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -373,7 +406,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -381,7 +414,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -395,9 +428,16 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithConfigureAwaitTrue(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithConfigureAwaitTrue()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -405,12 +445,12 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID yield break; } } -internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource()); } } @@ -422,7 +462,7 @@ internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -432,7 +472,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithNestedAsyncCalls", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -441,6 +481,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -457,7 +498,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -465,7 +506,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -479,9 +520,16 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithNestedAsyncCalls(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithNestedAsyncCalls()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -489,12 +537,12 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource()); } } @@ -506,7 +554,7 @@ internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -516,7 +564,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskFromResult", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -525,6 +573,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -541,7 +590,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -549,7 +598,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -563,9 +612,16 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskFromResult(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskFromResult()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -573,12 +629,12 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskFromResult_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource()); } } @@ -590,7 +646,7 @@ internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -600,7 +656,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithCompletedTask", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -609,6 +665,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -625,7 +682,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -633,7 +690,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -647,9 +704,16 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithCompletedTask(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithCompletedTask()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -657,12 +721,12 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithCompletedTask_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource()); } } @@ -674,7 +738,7 @@ internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUI #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -684,7 +748,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskRun", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -693,6 +757,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -709,7 +774,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -717,7 +782,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -731,9 +796,16 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskRun(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskRun()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -741,12 +813,12 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T yield break; } } -internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskRun_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource()); } } @@ -758,7 +830,7 @@ internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -768,7 +840,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithMultipleAwaits", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -777,6 +849,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -793,7 +866,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -801,7 +874,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -815,9 +888,16 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithMultipleAwaits(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithMultipleAwaits()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -825,12 +905,12 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource()); } } @@ -842,7 +922,7 @@ internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -852,7 +932,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithAsyncEnumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -861,6 +941,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -877,7 +958,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -885,7 +966,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -899,9 +980,16 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithAsyncEnumerable(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithAsyncEnumerable()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -909,12 +997,12 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g yield break; } } -internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource()); } } @@ -926,7 +1014,7 @@ internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -936,7 +1024,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskWhenAll", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -945,6 +1033,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -961,7 +1050,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -969,7 +1058,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -983,9 +1072,16 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskWhenAll(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskWhenAll()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -993,12 +1089,12 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource()); } } @@ -1010,7 +1106,7 @@ internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1020,7 +1116,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithExceptionHandling", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1029,6 +1125,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1045,7 +1142,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1053,7 +1150,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1067,9 +1164,16 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithExceptionHandling(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithExceptionHandling()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1077,12 +1181,12 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithExceptionHandling_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource()); } } @@ -1094,7 +1198,7 @@ internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1104,7 +1208,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithThrowsNothingAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1113,6 +1217,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1129,7 +1234,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1137,7 +1242,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1151,9 +1256,16 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithThrowsNothingAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithThrowsNothingAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1161,12 +1273,12 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G yield break; } } -internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource()); } } @@ -1178,7 +1290,7 @@ internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1188,7 +1300,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithFuncAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1197,6 +1309,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1213,7 +1326,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1221,7 +1334,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1235,9 +1348,16 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithFuncAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithFuncAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1245,11 +1365,11 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithFuncAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithFuncAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet8_0.verified.txt index e869041ae4..6f2ad0396b 100644 --- a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_With_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "With_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -22,6 +22,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -38,7 +39,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -46,7 +47,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -60,9 +61,16 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.With_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.With_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -70,12 +78,12 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class STAThreadTests_With_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_With_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_With_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_With_STA_TestSource()); } } @@ -87,7 +95,7 @@ internal static class STAThreadTests_With_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_Without_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -97,7 +105,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "Without_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -105,6 +113,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -121,7 +130,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -129,7 +138,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -143,9 +152,16 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Without_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Without_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -153,12 +169,12 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit yield break; } } -internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_Without_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_Without_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_Without_STA_TestSource()); } } @@ -170,7 +186,7 @@ internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -180,7 +196,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithSimpleAwait", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -189,6 +205,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -205,7 +222,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -213,7 +230,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -227,9 +244,16 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithSimpleAwait(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithSimpleAwait()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -237,12 +261,12 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithSimpleAwait_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource()); } } @@ -254,7 +278,7 @@ internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -264,7 +288,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskYield", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -273,6 +297,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -289,7 +314,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -297,7 +322,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -311,9 +336,16 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskYield(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskYield()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -321,12 +353,12 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: yield break; } } -internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskYield_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource()); } } @@ -338,7 +370,7 @@ internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -348,7 +380,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithConfigureAwaitTrue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -357,6 +389,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -373,7 +406,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -381,7 +414,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -395,9 +428,16 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithConfigureAwaitTrue(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithConfigureAwaitTrue()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -405,12 +445,12 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID yield break; } } -internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource()); } } @@ -422,7 +462,7 @@ internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -432,7 +472,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithNestedAsyncCalls", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -441,6 +481,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -457,7 +498,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -465,7 +506,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -479,9 +520,16 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithNestedAsyncCalls(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithNestedAsyncCalls()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -489,12 +537,12 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource()); } } @@ -506,7 +554,7 @@ internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -516,7 +564,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskFromResult", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -525,6 +573,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -541,7 +590,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -549,7 +598,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -563,9 +612,16 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskFromResult(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskFromResult()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -573,12 +629,12 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskFromResult_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource()); } } @@ -590,7 +646,7 @@ internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -600,7 +656,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithCompletedTask", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -609,6 +665,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -625,7 +682,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -633,7 +690,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -647,9 +704,16 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithCompletedTask(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithCompletedTask()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -657,12 +721,12 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithCompletedTask_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource()); } } @@ -674,7 +738,7 @@ internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUI #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -684,7 +748,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskRun", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -693,6 +757,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -709,7 +774,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -717,7 +782,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -731,9 +796,16 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskRun(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskRun()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -741,12 +813,12 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T yield break; } } -internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskRun_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource()); } } @@ -758,7 +830,7 @@ internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -768,7 +840,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithMultipleAwaits", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -777,6 +849,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -793,7 +866,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -801,7 +874,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -815,9 +888,16 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithMultipleAwaits(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithMultipleAwaits()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -825,12 +905,12 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource()); } } @@ -842,7 +922,7 @@ internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -852,7 +932,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithAsyncEnumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -861,6 +941,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -877,7 +958,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -885,7 +966,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -899,9 +980,16 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithAsyncEnumerable(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithAsyncEnumerable()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -909,12 +997,12 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g yield break; } } -internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource()); } } @@ -926,7 +1014,7 @@ internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -936,7 +1024,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskWhenAll", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -945,6 +1033,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -961,7 +1050,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -969,7 +1058,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -983,9 +1072,16 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskWhenAll(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskWhenAll()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -993,12 +1089,12 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource()); } } @@ -1010,7 +1106,7 @@ internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1020,7 +1116,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithExceptionHandling", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1029,6 +1125,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1045,7 +1142,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1053,7 +1150,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1067,9 +1164,16 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithExceptionHandling(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithExceptionHandling()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1077,12 +1181,12 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithExceptionHandling_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource()); } } @@ -1094,7 +1198,7 @@ internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1104,7 +1208,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithThrowsNothingAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1113,6 +1217,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1129,7 +1234,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1137,7 +1242,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1151,9 +1256,16 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithThrowsNothingAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithThrowsNothingAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1161,12 +1273,12 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G yield break; } } -internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource()); } } @@ -1178,7 +1290,7 @@ internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1188,7 +1300,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithFuncAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1197,6 +1309,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1213,7 +1326,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1221,7 +1334,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1235,9 +1348,16 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithFuncAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithFuncAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1245,11 +1365,11 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithFuncAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithFuncAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet9_0.verified.txt index e869041ae4..6f2ad0396b 100644 --- a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_With_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "With_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -22,6 +22,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -38,7 +39,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -46,7 +47,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -60,9 +61,16 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.With_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.With_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -70,12 +78,12 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class STAThreadTests_With_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_With_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_With_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_With_STA_TestSource()); } } @@ -87,7 +95,7 @@ internal static class STAThreadTests_With_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_Without_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -97,7 +105,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "Without_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -105,6 +113,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -121,7 +130,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -129,7 +138,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -143,9 +152,16 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Without_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Without_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -153,12 +169,12 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit yield break; } } -internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_Without_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_Without_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_Without_STA_TestSource()); } } @@ -170,7 +186,7 @@ internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -180,7 +196,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithSimpleAwait", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -189,6 +205,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -205,7 +222,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -213,7 +230,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -227,9 +244,16 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithSimpleAwait(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithSimpleAwait()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -237,12 +261,12 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithSimpleAwait_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource()); } } @@ -254,7 +278,7 @@ internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -264,7 +288,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskYield", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -273,6 +297,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -289,7 +314,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -297,7 +322,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -311,9 +336,16 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskYield(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskYield()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -321,12 +353,12 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: yield break; } } -internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskYield_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource()); } } @@ -338,7 +370,7 @@ internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -348,7 +380,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithConfigureAwaitTrue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -357,6 +389,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -373,7 +406,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -381,7 +414,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -395,9 +428,16 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithConfigureAwaitTrue(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithConfigureAwaitTrue()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -405,12 +445,12 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID yield break; } } -internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource()); } } @@ -422,7 +462,7 @@ internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -432,7 +472,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithNestedAsyncCalls", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -441,6 +481,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -457,7 +498,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -465,7 +506,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -479,9 +520,16 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithNestedAsyncCalls(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithNestedAsyncCalls()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -489,12 +537,12 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource()); } } @@ -506,7 +554,7 @@ internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -516,7 +564,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskFromResult", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -525,6 +573,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -541,7 +590,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -549,7 +598,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -563,9 +612,16 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskFromResult(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskFromResult()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -573,12 +629,12 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskFromResult_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource()); } } @@ -590,7 +646,7 @@ internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -600,7 +656,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithCompletedTask", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -609,6 +665,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -625,7 +682,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -633,7 +690,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -647,9 +704,16 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithCompletedTask(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithCompletedTask()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -657,12 +721,12 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithCompletedTask_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource()); } } @@ -674,7 +738,7 @@ internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUI #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -684,7 +748,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskRun", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -693,6 +757,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -709,7 +774,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -717,7 +782,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -731,9 +796,16 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskRun(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskRun()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -741,12 +813,12 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T yield break; } } -internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskRun_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource()); } } @@ -758,7 +830,7 @@ internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -768,7 +840,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithMultipleAwaits", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -777,6 +849,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -793,7 +866,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -801,7 +874,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -815,9 +888,16 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithMultipleAwaits(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithMultipleAwaits()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -825,12 +905,12 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource()); } } @@ -842,7 +922,7 @@ internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -852,7 +932,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithAsyncEnumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -861,6 +941,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -877,7 +958,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -885,7 +966,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -899,9 +980,16 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithAsyncEnumerable(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithAsyncEnumerable()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -909,12 +997,12 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g yield break; } } -internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource()); } } @@ -926,7 +1014,7 @@ internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -936,7 +1024,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskWhenAll", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -945,6 +1033,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -961,7 +1050,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -969,7 +1058,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -983,9 +1072,16 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskWhenAll(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskWhenAll()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -993,12 +1089,12 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource()); } } @@ -1010,7 +1106,7 @@ internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1020,7 +1116,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithExceptionHandling", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1029,6 +1125,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1045,7 +1142,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1053,7 +1150,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1067,9 +1164,16 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithExceptionHandling(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithExceptionHandling()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1077,12 +1181,12 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithExceptionHandling_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource()); } } @@ -1094,7 +1198,7 @@ internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1104,7 +1208,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithThrowsNothingAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1113,6 +1217,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1129,7 +1234,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1137,7 +1242,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1151,9 +1256,16 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithThrowsNothingAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithThrowsNothingAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1161,12 +1273,12 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G yield break; } } -internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource()); } } @@ -1178,7 +1290,7 @@ internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1188,7 +1300,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithFuncAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1197,6 +1309,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1213,7 +1326,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1221,7 +1334,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1235,9 +1348,16 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithFuncAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithFuncAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1245,11 +1365,11 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithFuncAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithFuncAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.Net4_7.verified.txt index a31a6cc141..b31c36229f 100644 --- a/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/STAThreadTests.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_With_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "With_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -22,6 +22,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -38,7 +39,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -46,7 +47,7 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -60,9 +61,16 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.With_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.With_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -70,12 +78,12 @@ internal sealed class STAThreadTests_With_STA_TestSource_GUID : global::TUnit.Co yield break; } } -internal static class STAThreadTests_With_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_With_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_With_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_With_STA_TestSource()); } } @@ -87,7 +95,7 @@ internal static class STAThreadTests_With_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_Without_STA_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -97,7 +105,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "Without_STA", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -105,6 +113,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -121,7 +130,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -129,7 +138,7 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -143,9 +152,16 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Without_STA(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Without_STA()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -153,12 +169,12 @@ internal sealed class STAThreadTests_Without_STA_TestSource_GUID : global::TUnit yield break; } } -internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_Without_STA_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_Without_STA_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_Without_STA_TestSource()); } } @@ -170,7 +186,7 @@ internal static class STAThreadTests_Without_STA_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -180,7 +196,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithSimpleAwait", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -189,6 +205,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -205,7 +222,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -213,7 +230,7 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -227,9 +244,16 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithSimpleAwait(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithSimpleAwait()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -237,12 +261,12 @@ internal sealed class STAThreadTests_STA_WithSimpleAwait_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithSimpleAwait_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithSimpleAwait_TestSource()); } } @@ -254,7 +278,7 @@ internal static class STAThreadTests_STA_WithSimpleAwait_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -264,7 +288,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskYield", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -273,6 +297,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -289,7 +314,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -297,7 +322,7 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -311,9 +336,16 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskYield(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskYield()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -321,12 +353,12 @@ internal sealed class STAThreadTests_STA_WithTaskYield_TestSource_GUID : global: yield break; } } -internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskYield_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskYield_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskYield_TestSource()); } } @@ -338,7 +370,7 @@ internal static class STAThreadTests_STA_WithTaskYield_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -348,7 +380,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithConfigureAwaitTrue", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -357,6 +389,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -373,7 +406,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -381,7 +414,7 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -395,9 +428,16 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithConfigureAwaitTrue(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithConfigureAwaitTrue()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -405,12 +445,12 @@ internal sealed class STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID yield break; } } -internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithConfigureAwaitTrue_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithConfigureAwaitTrue_TestSource()); } } @@ -422,7 +462,7 @@ internal static class STAThreadTests_STA_WithConfigureAwaitTrue_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -432,7 +472,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithNestedAsyncCalls", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -441,6 +481,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -457,7 +498,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -465,7 +506,7 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -479,9 +520,16 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithNestedAsyncCalls(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithNestedAsyncCalls()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -489,12 +537,12 @@ internal sealed class STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithNestedAsyncCalls_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithNestedAsyncCalls_TestSource()); } } @@ -506,7 +554,7 @@ internal static class STAThreadTests_STA_WithNestedAsyncCalls_ModuleInitializer_ #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -516,7 +564,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskFromResult", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -525,6 +573,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -541,7 +590,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -549,7 +598,7 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -563,9 +612,16 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskFromResult(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskFromResult()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -573,12 +629,12 @@ internal sealed class STAThreadTests_STA_WithTaskFromResult_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskFromResult_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskFromResult_TestSource()); } } @@ -590,7 +646,7 @@ internal static class STAThreadTests_STA_WithTaskFromResult_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -600,7 +656,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithCompletedTask", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -609,6 +665,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -625,7 +682,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -633,7 +690,7 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -647,9 +704,16 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithCompletedTask(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithCompletedTask()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -657,12 +721,12 @@ internal sealed class STAThreadTests_STA_WithCompletedTask_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithCompletedTask_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithCompletedTask_TestSource()); } } @@ -674,7 +738,7 @@ internal static class STAThreadTests_STA_WithCompletedTask_ModuleInitializer_GUI #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -684,7 +748,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskRun", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -693,6 +757,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -709,7 +774,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -717,7 +782,7 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -731,9 +796,16 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskRun(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskRun()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -741,12 +813,12 @@ internal sealed class STAThreadTests_STA_WithTaskRun_TestSource_GUID : global::T yield break; } } -internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskRun_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskRun_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskRun_TestSource()); } } @@ -758,7 +830,7 @@ internal static class STAThreadTests_STA_WithTaskRun_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -768,7 +840,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithMultipleAwaits", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -777,6 +849,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -793,7 +866,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -801,7 +874,7 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -815,9 +888,16 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithMultipleAwaits(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithMultipleAwaits()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -825,12 +905,12 @@ internal sealed class STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID : gl yield break; } } -internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithMultipleAwaits_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithMultipleAwaits_TestSource()); } } @@ -842,7 +922,7 @@ internal static class STAThreadTests_STA_WithMultipleAwaits_ModuleInitializer_GU #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -852,7 +932,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithAsyncEnumerable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -861,6 +941,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -877,7 +958,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -885,7 +966,7 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -899,9 +980,16 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithAsyncEnumerable(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithAsyncEnumerable()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -909,12 +997,12 @@ internal sealed class STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID : g yield break; } } -internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithAsyncEnumerable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithAsyncEnumerable_TestSource()); } } @@ -926,7 +1014,7 @@ internal static class STAThreadTests_STA_WithAsyncEnumerable_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -936,7 +1024,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithTaskWhenAll", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -945,6 +1033,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -961,7 +1050,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -969,7 +1058,7 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -983,9 +1072,16 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithTaskWhenAll(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithTaskWhenAll()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -993,12 +1089,12 @@ internal sealed class STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID : globa yield break; } } -internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithTaskWhenAll_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithTaskWhenAll_TestSource()); } } @@ -1010,7 +1106,7 @@ internal static class STAThreadTests_STA_WithTaskWhenAll_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1020,7 +1116,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithExceptionHandling", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1029,6 +1125,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1045,7 +1142,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1053,7 +1150,7 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1067,9 +1164,16 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithExceptionHandling(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithExceptionHandling()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1077,12 +1181,12 @@ internal sealed class STAThreadTests_STA_WithExceptionHandling_TestSource_GUID : yield break; } } -internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithExceptionHandling_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithExceptionHandling_TestSource()); } } @@ -1094,7 +1198,7 @@ internal static class STAThreadTests_STA_WithExceptionHandling_ModuleInitializer #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1104,7 +1208,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithThrowsNothingAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1113,6 +1217,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1129,7 +1234,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1137,7 +1242,7 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1151,9 +1256,16 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithThrowsNothingAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithThrowsNothingAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1161,12 +1273,12 @@ internal sealed class STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_G yield break; } } -internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithThrowsNothingAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithThrowsNothingAssertion_TestSource()); } } @@ -1178,7 +1290,7 @@ internal static class STAThreadTests_STA_WithThrowsNothingAssertion_ModuleInitia #nullable enable namespace TUnit.Generated; -internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -1188,7 +1300,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.STAThreadTests), TestMethodName = "STA_WithFuncAssertion", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.Executors.STAThreadExecutorAttribute(), @@ -1197,6 +1309,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo new global::TUnit.Core.RepeatAttribute(100), new global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute("Interoperability", "CA1416:Validate platform compatibility") ], + RepeatCount = 100, DataSources = global::System.Array.Empty(), ClassDataSources = global::System.Array.Empty(), PropertyDataSources = global::System.Array.Empty(), @@ -1213,7 +1326,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.STAThreadTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -1221,7 +1334,7 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.STAThreadTests)), Name = "STAThreadTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -1235,9 +1348,16 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.STAThreadTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.STA_WithFuncAssertion(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.STA_WithFuncAssertion()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -1245,11 +1365,11 @@ internal sealed class STAThreadTests_STA_WithFuncAssertion_TestSource_GUID : glo yield break; } } -internal static class STAThreadTests_STA_WithFuncAssertion_ModuleInitializer_GUID +internal static class TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new STAThreadTests_STA_WithFuncAssertion_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.STAThreadTests), new TUnit_TestProject_STAThreadTests_STA_WithFuncAssertion_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/StringArgumentTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/StringArgumentTests.Test.verified.txt index d2f0401e99..ddf79f8751 100644 --- a/TUnit.Core.SourceGenerator.Tests/StringArgumentTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/StringArgumentTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_StringArgumentTests_Normal__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.StringArgumentTests), TestMethodName = "Normal", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -57,7 +57,7 @@ internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.StringArgumentTests).GetMethod("Normal", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.StringArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.StringArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -65,7 +65,7 @@ internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.StringArgumentTests)), Name = "StringArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -79,17 +79,23 @@ internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.StringArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Normal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Normal(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -97,12 +103,12 @@ internal sealed class StringArgumentTests_Normal_TestSource_GUID : global::TUnit yield break; } } -internal static class StringArgumentTests_Normal_ModuleInitializer_GUID +internal static class TUnit_TestProject_StringArgumentTests_Normal__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.StringArgumentTests), new StringArgumentTests_Normal_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.StringArgumentTests), new TUnit_TestProject_StringArgumentTests_Normal__string_TestSource()); } } @@ -114,7 +120,7 @@ internal static class StringArgumentTests_Normal_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_StringArgumentTests_Nullable__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -124,7 +130,7 @@ internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUn TestClassType = typeof(global::TUnit.TestProject.StringArgumentTests), TestMethodName = "Nullable", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -164,7 +170,7 @@ internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUn ReflectionInfo = typeof(global::TUnit.TestProject.StringArgumentTests).GetMethod("Nullable", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.StringArgumentTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.StringArgumentTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -172,7 +178,7 @@ internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUn TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.StringArgumentTests)), Name = "StringArgumentTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -186,17 +192,23 @@ internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUn }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.StringArgumentTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Nullable(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Nullable(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -204,11 +216,11 @@ internal sealed class StringArgumentTests_Nullable_TestSource_GUID : global::TUn yield break; } } -internal static class StringArgumentTests_Nullable_ModuleInitializer_GUID +internal static class TUnit_TestProject_StringArgumentTests_Nullable__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.StringArgumentTests), new StringArgumentTests_Nullable_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.StringArgumentTests), new TUnit_TestProject_StringArgumentTests_Nullable__string__TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests.Test.verified.txt index 8ce3ec135c..62c0396286 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1304_Tests_TryParse_InvalidString_ReturnsFailure__string__CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.Bugs._1304.Tests), TestMethodName = "TryParse_InvalidString_ReturnsFailure", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -57,7 +57,7 @@ internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1304.Tests).GetMethod("TryParse_InvalidString_ReturnsFailure", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -65,7 +65,7 @@ internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1304.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1304", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -79,16 +79,22 @@ internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1304.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var context = global::TUnit.Core.TestContext.Current; - switch (args.Length) + try { - case 1: - await instance.TryParse_InvalidString_ReturnsFailure(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + var context = global::TUnit.Core.TestContext.Current; + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.TryParse_InvalidString_ReturnsFailure(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None)); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -97,12 +103,12 @@ internal sealed class Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUI yield break; } } -internal static class Tests_TryParse_InvalidString_ReturnsFailure_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1304_Tests_TryParse_InvalidString_ReturnsFailure__string__CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new Tests_TryParse_InvalidString_ReturnsFailure_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new TUnit_TestProject_Bugs__1304_Tests_TryParse_InvalidString_ReturnsFailure__string__CancellationToken_TestSource()); } } @@ -114,7 +120,7 @@ internal static class Tests_TryParse_InvalidString_ReturnsFailure_ModuleInitiali #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1304_Tests_Parse_InvalidString_ThrowsException__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -124,7 +130,7 @@ internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.Bugs._1304.Tests), TestMethodName = "Parse_InvalidString_ThrowsException", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -161,7 +167,7 @@ internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1304.Tests).GetMethod("Parse_InvalidString_ThrowsException", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -169,7 +175,7 @@ internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1304.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1304", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -183,15 +189,21 @@ internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1304.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Parse_InvalidString_ThrowsException(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Parse_InvalidString_ThrowsException(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -200,12 +212,12 @@ internal sealed class Tests_Parse_InvalidString_ThrowsException_TestSource_GUID yield break; } } -internal static class Tests_Parse_InvalidString_ThrowsException_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1304_Tests_Parse_InvalidString_ThrowsException__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new Tests_Parse_InvalidString_ThrowsException_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new TUnit_TestProject_Bugs__1304_Tests_Parse_InvalidString_ThrowsException__string__TestSource()); } } @@ -217,7 +229,7 @@ internal static class Tests_Parse_InvalidString_ThrowsException_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1304_Tests_TryParse_ValidString_ReturnsAccountId__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -227,7 +239,7 @@ internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUI TestClassType = typeof(global::TUnit.TestProject.Bugs._1304.Tests), TestMethodName = "TryParse_ValidString_ReturnsAccountId", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -261,7 +273,7 @@ internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUI ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1304.Tests).GetMethod("TryParse_ValidString_ReturnsAccountId", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1304.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -269,7 +281,7 @@ internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUI TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1304.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1304", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -283,15 +295,21 @@ internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUI }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1304.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.TryParse_ValidString_ReturnsAccountId(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.TryParse_ValidString_ReturnsAccountId(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -300,11 +318,11 @@ internal sealed class Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUI yield break; } } -internal static class Tests_TryParse_ValidString_ReturnsAccountId_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1304_Tests_TryParse_ValidString_ReturnsAccountId__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new Tests_TryParse_ValidString_ReturnsAccountId_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1304.Tests), new TUnit_TestProject_Bugs__1304_Tests_TryParse_ValidString_ReturnsAccountId__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1538.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1538.Test.verified.txt index b84d080fb4..f58a3c0aac 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1538.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1538.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1538_Tests_Eight_Args__bool_string__string__string__string__string__string__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Inte TestClassType = typeof(global::TUnit.TestProject.Bugs._1538.Tests), TestMethodName = "Eight_Args", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -116,7 +116,7 @@ internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Inte ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1538.Tests).GetMethod("Eight_Args", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) }, null)!.GetParameters()[7] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1538.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1538.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -124,7 +124,7 @@ internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Inte TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1538.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1538", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -138,17 +138,23 @@ internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Inte }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1538.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 8: - instance.Eight_Args(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]), TUnit.Core.Helpers.CastHelper.Cast(args[7])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 8 arguments, but got {args.Length}"); + switch (args.Length) + { + case 8: + instance.Eight_Args(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]), TUnit.Core.Helpers.CastHelper.Cast(args[7])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 8 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -156,12 +162,12 @@ internal sealed class Tests_Eight_Args_TestSource_GUID : global::TUnit.Core.Inte yield break; } } -internal static class Tests_Eight_Args_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1538_Tests_Eight_Args__bool_string__string__string__string__string__string__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1538.Tests), new Tests_Eight_Args_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1538.Tests), new TUnit_TestProject_Bugs__1538_Tests_Eight_Args__bool_string__string__string__string__string__string__string__TestSource()); } } @@ -173,7 +179,7 @@ internal static class Tests_Eight_Args_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1538_Tests_SixteenArgs__bool_string__string__string__string__string__string__string__string__string__string__string__string__string__string__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -183,7 +189,7 @@ internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1538.Tests), TestMethodName = "SixteenArgs", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -342,7 +348,7 @@ internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1538.Tests).GetMethod("SixteenArgs", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) }, null)!.GetParameters()[15] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1538.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1538.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -350,7 +356,7 @@ internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1538.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1538", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -364,17 +370,23 @@ internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1538.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 16: + instance.SixteenArgs(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]), TUnit.Core.Helpers.CastHelper.Cast(args[7]), TUnit.Core.Helpers.CastHelper.Cast(args[8]), TUnit.Core.Helpers.CastHelper.Cast(args[9]), TUnit.Core.Helpers.CastHelper.Cast(args[10]), TUnit.Core.Helpers.CastHelper.Cast(args[11]), TUnit.Core.Helpers.CastHelper.Cast(args[12]), TUnit.Core.Helpers.CastHelper.Cast(args[13]), TUnit.Core.Helpers.CastHelper.Cast(args[14]), TUnit.Core.Helpers.CastHelper.Cast(args[15])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 16 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 16: - instance.SixteenArgs(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]), TUnit.Core.Helpers.CastHelper.Cast(args[7]), TUnit.Core.Helpers.CastHelper.Cast(args[8]), TUnit.Core.Helpers.CastHelper.Cast(args[9]), TUnit.Core.Helpers.CastHelper.Cast(args[10]), TUnit.Core.Helpers.CastHelper.Cast(args[11]), TUnit.Core.Helpers.CastHelper.Cast(args[12]), TUnit.Core.Helpers.CastHelper.Cast(args[13]), TUnit.Core.Helpers.CastHelper.Cast(args[14]), TUnit.Core.Helpers.CastHelper.Cast(args[15])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 16 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -382,11 +394,11 @@ internal sealed class Tests_SixteenArgs_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class Tests_SixteenArgs_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1538_Tests_SixteenArgs__bool_string__string__string__string__string__string__string__string__string__string__string__string__string__string__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1538.Tests), new Tests_SixteenArgs_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1538.Tests), new TUnit_TestProject_Bugs__1538_Tests_SixteenArgs__bool_string__string__string__string__string__string__string__string__string__string__string__string__string__string__string__TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1539.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1539.Test.verified.txt index 3a739b709a..a80ac7803f 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1539.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1539.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1539_Tests_Test_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TestClassType = typeof(global::TUnit.TestProject.Bugs._1539.Tests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Bugs._1539.Tests.AttributeWithPositionalArgs(), @@ -38,7 +38,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1539.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1539.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -46,7 +46,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1539.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1539", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -60,10 +60,17 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1539.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -71,11 +78,11 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces yield break; } } -internal static class Tests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1539_Tests_Test_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1539.Tests), new Tests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1539.Tests), new TUnit_TestProject_Bugs__1539_Tests_Test_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1589.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1589.Test.verified.txt index b34b16e7dd..715c01f082 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1589.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1589.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1589_MyTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TestClassType = typeof(global::TUnit.TestProject.Bugs._1589.MyTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa ReturnType = typeof(global::System.Threading.Tasks.Task), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.Tasks.Task)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1589.MyTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1589.MyTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1589.MyTests)), Name = "MyTests", Namespace = "TUnit.TestProject.Bugs._1589", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1589.MyFixture)) @@ -74,9 +74,16 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa { return new global::TUnit.TestProject.Bugs._1589.MyTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.Test1(); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Test1()); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -84,11 +91,11 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa yield break; } } -internal static class MyTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1589_MyTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1589.MyTests), new MyTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1589.MyTests), new TUnit_TestProject_Bugs__1589_MyTests_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1594.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1594.Test.verified.txt index b8277907aa..9d5d9f0ecd 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1594.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1594.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1594_MyTests_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TestClassType = typeof(global::TUnit.TestProject.Bugs._1594.MyTests), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -40,7 +40,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1594.MyTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1594.MyTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -48,7 +48,7 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1594.MyTests)), Name = "MyTests", Namespace = "TUnit.TestProject.Bugs._1594", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1594.MyFixture)) @@ -74,10 +74,17 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa { return new global::TUnit.TestProject.Bugs._1594.MyTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -85,11 +92,11 @@ internal sealed class MyTests_Test1_TestSource_GUID : global::TUnit.Core.Interfa yield break; } } -internal static class MyTests_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1594_MyTests_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1594.MyTests), new MyTests_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1594.MyTests), new TUnit_TestProject_Bugs__1594_MyTests_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1603.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1603.Test.verified.txt index b02a1020de..3a4cae1c70 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1603.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1603.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1603_Tests_Casted_Integer_To_Short_Converts__short_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.Bugs._1603.Tests), TestMethodName = "Casted_Integer_To_Short_Converts", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : g ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1603.Tests).GetMethod("Casted_Integer_To_Short_Converts", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(short) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1603.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1603.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1603.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1603", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : g }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1603.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Casted_Integer_To_Short_Converts(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Casted_Integer_To_Short_Converts(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,12 +91,12 @@ internal sealed class Tests_Casted_Integer_To_Short_Converts_TestSource_GUID : g yield break; } } -internal static class Tests_Casted_Integer_To_Short_Converts_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1603_Tests_Casted_Integer_To_Short_Converts__short_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1603.Tests), new Tests_Casted_Integer_To_Short_Converts_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1603.Tests), new TUnit_TestProject_Bugs__1603_Tests_Casted_Integer_To_Short_Converts__short_TestSource()); } } @@ -102,7 +108,7 @@ internal static class Tests_Casted_Integer_To_Short_Converts_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1603_Tests_Integer_To_Short_Converts__short_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -112,7 +118,7 @@ internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global:: TestClassType = typeof(global::TUnit.TestProject.Bugs._1603.Tests), TestMethodName = "Integer_To_Short_Converts", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -145,7 +151,7 @@ internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global:: ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1603.Tests).GetMethod("Integer_To_Short_Converts", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(short) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1603.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1603.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -153,7 +159,7 @@ internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global:: TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1603.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1603", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -167,15 +173,21 @@ internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global:: }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1603.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Integer_To_Short_Converts(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Integer_To_Short_Converts(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -184,11 +196,11 @@ internal sealed class Tests_Integer_To_Short_Converts_TestSource_GUID : global:: yield break; } } -internal static class Tests_Integer_To_Short_Converts_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1603_Tests_Integer_To_Short_Converts__short_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1603.Tests), new Tests_Integer_To_Short_Converts_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1603.Tests), new TUnit_TestProject_Bugs__1603_Tests_Integer_To_Short_Converts__short_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1692.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1692.Test.verified.txt index 968a06b62a..dc434877b6 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1692.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1692.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1692_Tests_NullTest__string__TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interf TestClassType = typeof(global::TUnit.TestProject.Bugs._1692.Tests), TestMethodName = "NullTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -47,7 +47,7 @@ internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interf ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1692.Tests).GetMethod("NullTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1692.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1692.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -55,7 +55,7 @@ internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interf TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1692.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1692", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -69,15 +69,21 @@ internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interf }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1692.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.NullTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.NullTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -86,11 +92,11 @@ internal sealed class Tests_NullTest_TestSource_GUID : global::TUnit.Core.Interf yield break; } } -internal static class Tests_NullTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1692_Tests_NullTest__string__ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1692.Tests), new Tests_NullTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1692.Tests), new TUnit_TestProject_Bugs__1692_Tests_NullTest__string__TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1821.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1821.Test.verified.txt index 01ed351326..13a93df557 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1821.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1821.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1821_Tests_MethodDataSource__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Cor TestClassType = typeof(global::TUnit.TestProject.Bugs._1821.Tests), TestMethodName = "MethodDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -50,7 +50,7 @@ internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Cor ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1821.Tests).GetMethod("MethodDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1821.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1821.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -58,7 +58,7 @@ internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Cor TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1821.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1821", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1821.MyData)) @@ -84,15 +84,21 @@ internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Cor { return new global::TUnit.TestProject.Bugs._1821.Tests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.MethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MethodDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -101,12 +107,12 @@ internal sealed class Tests_MethodDataSource_TestSource_GUID : global::TUnit.Cor yield break; } } -internal static class Tests_MethodDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1821_Tests_MethodDataSource__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1821.Tests), new Tests_MethodDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1821.Tests), new TUnit_TestProject_Bugs__1821_Tests_MethodDataSource__string_TestSource()); } } @@ -118,7 +124,7 @@ internal static class Tests_MethodDataSource_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1821_Tests_MatrixDataSource__string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -128,7 +134,7 @@ internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Cor TestClassType = typeof(global::TUnit.TestProject.Bugs._1821.Tests), TestMethodName = "MatrixDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -165,7 +171,7 @@ internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Cor ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._1821.Tests).GetMethod("MatrixDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(string) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1821.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1821.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -173,7 +179,7 @@ internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Cor TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1821.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._1821", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(global::TUnit.TestProject.Bugs._1821.MyData)) @@ -199,15 +205,21 @@ internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Cor { return new global::TUnit.TestProject.Bugs._1821.Tests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MatrixDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.MatrixDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -216,11 +228,11 @@ internal sealed class Tests_MatrixDataSource_TestSource_GUID : global::TUnit.Cor yield break; } } -internal static class Tests_MatrixDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1821_Tests_MatrixDataSource__string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1821.Tests), new Tests_MatrixDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1821.Tests), new TUnit_TestProject_Bugs__1821_Tests_MatrixDataSource__string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet10_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet10_0.verified.txt index a9ed13dbdc..65d6193dd3 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet10_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet10_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -35,7 +35,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource()); } } @@ -85,7 +92,7 @@ internal static class DerivedTest_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -129,7 +136,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -137,7 +144,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -151,17 +158,23 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -169,12 +182,12 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource()); } } @@ -186,7 +199,7 @@ internal static class DerivedTest_Test2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -196,7 +209,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -231,7 +244,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -239,7 +252,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -253,17 +266,23 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -271,11 +290,11 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test3_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet8_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet8_0.verified.txt index a9ed13dbdc..65d6193dd3 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet8_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet8_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -35,7 +35,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource()); } } @@ -85,7 +92,7 @@ internal static class DerivedTest_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -129,7 +136,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -137,7 +144,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -151,17 +158,23 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -169,12 +182,12 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource()); } } @@ -186,7 +199,7 @@ internal static class DerivedTest_Test2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -196,7 +209,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -231,7 +244,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -239,7 +252,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -253,17 +266,23 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -271,11 +290,11 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test3_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet9_0.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet9_0.verified.txt index a9ed13dbdc..65d6193dd3 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet9_0.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.DotNet9_0.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -35,7 +35,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource()); } } @@ -85,7 +92,7 @@ internal static class DerivedTest_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -129,7 +136,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -137,7 +144,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -151,17 +158,23 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -169,12 +182,12 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource()); } } @@ -186,7 +199,7 @@ internal static class DerivedTest_Test2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -196,7 +209,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -231,7 +244,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -239,7 +252,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -253,17 +266,23 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -271,11 +290,11 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test3_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.Net4_7.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.Net4_7.verified.txt index 110be656ec..aabb7073ca 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.Net4_7.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1889.Test.Net4_7.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -35,7 +35,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,12 +75,12 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test1_TestSource()); } } @@ -85,7 +92,7 @@ internal static class DerivedTest_Test1_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -95,7 +102,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -129,7 +136,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -137,7 +144,7 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -151,17 +158,23 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -169,12 +182,12 @@ internal sealed class DerivedTest_Test2_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test2__bool_TestSource()); } } @@ -186,7 +199,7 @@ internal static class DerivedTest_Test2_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -196,7 +209,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), TestMethodName = "Test3", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -231,7 +244,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int ReflectionInfo = typeof(global::TUnit.TestProject.Library.Bugs._1889.BaseTest).GetMethod("Test3", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(bool) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1889.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -239,7 +252,7 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1889", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -253,17 +266,23 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1889.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test3(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -271,11 +290,11 @@ internal sealed class DerivedTest_Test3_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test3_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new DerivedTest_Test3_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1889.DerivedTest), new TUnit_TestProject_Bugs__1889_DerivedTest_Test3__bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests1899.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests1899.Test.verified.txt index 3c85d2f51e..ac8a778372 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests1899.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests1899.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__1899_DerivedTest_Test1_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TestClassType = typeof(global::TUnit.TestProject.Bugs._1899.DerivedTest), TestMethodName = "Test1", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -35,7 +35,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1899.DerivedTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._1899.DerivedTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -43,7 +43,7 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._1899.DerivedTest)), Name = "DerivedTest", Namespace = "TUnit.TestProject.Bugs._1899", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -57,10 +57,17 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._1899.DerivedTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.Test1(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.Test1(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -68,11 +75,11 @@ internal sealed class DerivedTest_Test1_TestSource_GUID : global::TUnit.Core.Int yield break; } } -internal static class DerivedTest_Test1_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__1899_DerivedTest_Test1_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1899.DerivedTest), new DerivedTest_Test1_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._1899.DerivedTest), new TUnit_TestProject_Bugs__1899_DerivedTest_Test1_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests2083.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests2083.Test.verified.txt index 135fcecda8..7106ee7e81 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests2083.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests2083.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2083_Tests_MyTest__long_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfac TestClassType = typeof(global::TUnit.TestProject.Bugs._2083.Tests), TestMethodName = "MyTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -51,7 +51,7 @@ internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfac ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._2083.Tests).GetMethod("MyTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(long) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2083.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2083.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -59,7 +59,7 @@ internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfac TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2083.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2083", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -73,17 +73,23 @@ internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfac }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2083.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.MyTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.MyTest(TUnit.Core.Helpers.CastHelper.Cast(args[0])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -91,11 +97,11 @@ internal sealed class Tests_MyTest_TestSource_GUID : global::TUnit.Core.Interfac yield break; } } -internal static class Tests_MyTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2083_Tests_MyTest__long_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2083.Tests), new Tests_MyTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2083.Tests), new TUnit_TestProject_Bugs__2083_Tests_MyTest__long_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests2085.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests2085.Test.verified.txt index 30cd222477..aa612dac45 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests2085.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests2085.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2085_Tests_Double_SpecialConsts__double_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.Bugs._2085.Tests), TestMethodName = "Double_SpecialConsts", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -46,7 +46,7 @@ internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._2085.Tests).GetMethod("Double_SpecialConsts", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(double) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2085.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2085.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -54,7 +54,7 @@ internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2085.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2085", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -68,15 +68,21 @@ internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2085.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - await instance.Double_SpecialConsts(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Double_SpecialConsts(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -85,12 +91,12 @@ internal sealed class Tests_Double_SpecialConsts_TestSource_GUID : global::TUnit yield break; } } -internal static class Tests_Double_SpecialConsts_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2085_Tests_Double_SpecialConsts__double_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2085.Tests), new Tests_Double_SpecialConsts_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2085.Tests), new TUnit_TestProject_Bugs__2085_Tests_Double_SpecialConsts__double_TestSource()); } } @@ -102,7 +108,7 @@ internal static class Tests_Double_SpecialConsts_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2085_Tests_Float_SpecialConsts__float_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -112,7 +118,7 @@ internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit. TestClassType = typeof(global::TUnit.TestProject.Bugs._2085.Tests), TestMethodName = "Float_SpecialConsts", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -145,7 +151,7 @@ internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit. ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._2085.Tests).GetMethod("Float_SpecialConsts", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(float) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2085.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2085.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -153,7 +159,7 @@ internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit. TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2085.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2085", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -167,15 +173,21 @@ internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit. }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2085.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.Float_SpecialConsts(TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.Float_SpecialConsts(TUnit.Core.Helpers.CastHelper.Cast(args[0])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -184,11 +196,11 @@ internal sealed class Tests_Float_SpecialConsts_TestSource_GUID : global::TUnit. yield break; } } -internal static class Tests_Float_SpecialConsts_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2085_Tests_Float_SpecialConsts__float_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2085.Tests), new Tests_Float_SpecialConsts_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2085.Tests), new TUnit_TestProject_Bugs__2085_Tests_Float_SpecialConsts__float_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests2112.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests2112.Test.verified.txt index c618ba7264..8d2e037a83 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests2112.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests2112.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2112_Tests_Test__int_long___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TestClassType = typeof(global::TUnit.TestProject.Bugs._2112.Tests), TestMethodName = "Test", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -54,7 +54,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._2112.Tests).GetMethod("Test", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(long[]) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2112.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2112.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -62,7 +62,7 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2112.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2112", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -76,35 +76,41 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2112.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 1: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[0]); - break; - case 2: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), (args[1] is null ? null : args[1] is long[] arr ? arr : new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]) })); - break; - case 3: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); - break; - case 4: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); - break; - case 5: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); - break; - case 6: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); - break; - case 7: - instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]) }); - break; - default: - throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + switch (args.Length) + { + case 1: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[0]); + return default(global::System.Threading.Tasks.ValueTask); + case 2: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), (args[1] is null ? null : args[1] is long[] arr ? arr : new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]) })); + return default(global::System.Threading.Tasks.ValueTask); + case 3: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 4: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 5: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 6: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 7: + instance.Test(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]) }); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -112,12 +118,12 @@ internal sealed class Tests_Test_TestSource_GUID : global::TUnit.Core.Interfaces yield break; } } -internal static class Tests_Test_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2112_Tests_Test__int_long___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2112.Tests), new Tests_Test_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2112.Tests), new TUnit_TestProject_Bugs__2112_Tests_Test__int_long___TestSource()); } } @@ -129,7 +135,7 @@ internal static class Tests_Test_ModuleInitializer_GUID #nullable enable namespace TUnit.Generated; -internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2112_Tests_Test2__int_long___TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -139,7 +145,7 @@ internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interface TestClassType = typeof(global::TUnit.TestProject.Bugs._2112.Tests), TestMethodName = "Test2", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -180,7 +186,7 @@ internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interface ReflectionInfo = typeof(global::TUnit.TestProject.Bugs._2112.Tests).GetMethod("Test2", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(long[]) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2112.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2112.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -188,7 +194,7 @@ internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interface TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2112.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2112", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -202,35 +208,41 @@ internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interface }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.Bugs._2112.Tests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try + { + switch (args.Length) + { + case 1: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[0]); + return default(global::System.Threading.Tasks.ValueTask); + case 2: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), (args[1] is null ? null : args[1] is long[] arr ? arr : new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]) })); + return default(global::System.Threading.Tasks.ValueTask); + case 3: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 4: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 5: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 6: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); + return default(global::System.Threading.Tasks.ValueTask); + case 7: + instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]) }); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[0]); - break; - case 2: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), (args[1] is null ? null : args[1] is long[] arr ? arr : new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]) })); - break; - case 3: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]) }); - break; - case 4: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]) }); - break; - case 5: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]) }); - break; - case 6: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]) }); - break; - case 7: - instance.Test2(TUnit.Core.Helpers.CastHelper.Cast(args[0]), new long[] { TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2]), TUnit.Core.Helpers.CastHelper.Cast(args[3]), TUnit.Core.Helpers.CastHelper.Cast(args[4]), TUnit.Core.Helpers.CastHelper.Cast(args[5]), TUnit.Core.Helpers.CastHelper.Cast(args[6]) }); - break; - default: - throw new global::System.ArgumentException($"Expected between 1 and 2 arguments, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -238,11 +250,11 @@ internal sealed class Tests_Test2_TestSource_GUID : global::TUnit.Core.Interface yield break; } } -internal static class Tests_Test2_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2112_Tests_Test2__int_long___ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2112.Tests), new Tests_Test2_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2112.Tests), new TUnit_TestProject_Bugs__2112_Tests_Test2__int_long___TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/Tests2136.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/Tests2136.Test.verified.txt index 0c05af0089..bc3a3320ab 100644 --- a/TUnit.Core.SourceGenerator.Tests/Tests2136.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/Tests2136.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_Bugs__2136_Tests_GenericArgumentsTest__T_string_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -14,7 +14,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestClassType = typeof(global::TUnit.TestProject.Bugs._2136.Tests), TestMethodName = "GenericArgumentsTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -51,7 +51,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -59,7 +59,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -72,7 +72,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, @@ -86,7 +86,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestMethodName = "GenericArgumentsTest", GenericMethodTypeArguments = new global::System.Type[] { typeof(bool)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute(true, "True"), @@ -128,7 +128,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -136,7 +136,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -149,14 +149,21 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((bool)args[0]!, (string)args[1]!)); + try + { + var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((bool)args[0]!, (string)args[1]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -168,7 +175,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestMethodName = "GenericArgumentsTest", GenericMethodTypeArguments = new global::System.Type[] { typeof(int)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute(1, "1"), @@ -210,7 +217,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -218,7 +225,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -231,14 +238,21 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((int)args[0]!, (string)args[1]!)); + try + { + var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((int)args[0]!, (string)args[1]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -250,7 +264,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestMethodName = "GenericArgumentsTest", GenericMethodTypeArguments = new global::System.Type[] { typeof(double)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute(1.1, "1.1"), @@ -292,7 +306,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -300,7 +314,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -313,14 +327,21 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((double)args[0]!, (string)args[1]!)); + try + { + var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((double)args[0]!, (string)args[1]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -332,7 +353,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestMethodName = "GenericArgumentsTest", GenericMethodTypeArguments = new global::System.Type[] { typeof(string)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute("hello", "hello"), @@ -374,7 +395,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -382,7 +403,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -395,14 +416,21 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((string)args[0]!, (string)args[1]!)); + try + { + var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((string)args[0]!, (string)args[1]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -414,7 +442,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TestMethodName = "GenericArgumentsTest", GenericMethodTypeArguments = new global::System.Type[] { typeof(global::TUnit.TestProject.Bugs._2136.MyEnum)}, Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.ArgumentsAttribute(global::TUnit.TestProject.Bugs._2136.MyEnum.Item, "Item"), @@ -456,7 +484,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit ReflectionInfo = global::System.Linq.Enumerable.FirstOrDefault(typeof(global::TUnit.TestProject.Bugs._2136.Tests).GetMethods(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance | global::System.Reflection.BindingFlags.Static), m => m.Name == "GenericArgumentsTest" && m.GetParameters().Length == 2)?.GetParameters()[1]! } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._2136.Tests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -464,7 +492,7 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._2136.Tests)), Name = "Tests", Namespace = "TUnit.TestProject.Bugs._2136", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -477,14 +505,21 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit return classMetadata; }) }, - InstanceFactory = (typeArgs, args) => + InstanceFactory = static (typeArgs, args) => { return new global::TUnit.TestProject.Bugs._2136.Tests(); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; - await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((global::TUnit.TestProject.Bugs._2136.MyEnum)args[0]!, (string)args[1]!)); + try + { + var typedInstance = (global::TUnit.TestProject.Bugs._2136.Tests)instance; + return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.GenericArgumentsTest((global::TUnit.TestProject.Bugs._2136.MyEnum)args[0]!, (string)args[1]!)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } } } , @@ -495,11 +530,11 @@ internal sealed class Tests_GenericArgumentsTest_TestSource_GUID : global::TUnit yield break; } } -internal static class Tests_GenericArgumentsTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_Bugs__2136_Tests_GenericArgumentsTest__T_string_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2136.Tests), new Tests_GenericArgumentsTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._2136.Tests), new TUnit_TestProject_Bugs__2136_Tests_GenericArgumentsTest__T_string_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/TimeoutCancellationTokenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/TimeoutCancellationTokenTests.Test.verified.txt index 663b37a3b8..180fa355b9 100644 --- a/TUnit.Core.SourceGenerator.Tests/TimeoutCancellationTokenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/TimeoutCancellationTokenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_DefaultTest__CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "DefaultTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), @@ -69,7 +69,7 @@ internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("DefaultTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -77,7 +77,7 @@ internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -103,9 +103,16 @@ internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.DefaultTest(cancellationToken); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.DefaultTest(cancellationToken)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -113,12 +120,12 @@ internal sealed class TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID yield break; } } -internal static class TimeoutCancellationTokenTests_DefaultTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_DefaultTest__CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_DefaultTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_DefaultTest__CancellationToken_TestSource()); } } @@ -130,7 +137,7 @@ internal static class TimeoutCancellationTokenTests_DefaultTest_ModuleInitialize #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_BasicTest__CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -140,7 +147,7 @@ internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "BasicTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.TimeoutAttribute(5_000), @@ -198,7 +205,7 @@ internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("BasicTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -206,7 +213,7 @@ internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -232,9 +239,16 @@ internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.BasicTest(cancellationToken); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.BasicTest(cancellationToken)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -242,12 +256,12 @@ internal sealed class TimeoutCancellationTokenTests_BasicTest_TestSource_GUID : yield break; } } -internal static class TimeoutCancellationTokenTests_BasicTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_BasicTest__CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_BasicTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_BasicTest__CancellationToken_TestSource()); } } @@ -259,7 +273,7 @@ internal static class TimeoutCancellationTokenTests_BasicTest_ModuleInitializer_ #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_InheritedTimeoutAttribute__CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -269,7 +283,7 @@ internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Te TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "InheritedTimeoutAttribute", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.TimeoutCancellationTokenTests.FiveSecondTimeout(), @@ -326,7 +340,7 @@ internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Te ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("InheritedTimeoutAttribute", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -334,7 +348,7 @@ internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Te TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -360,9 +374,16 @@ internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Te { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - await instance.InheritedTimeoutAttribute(cancellationToken); + try + { + return new global::System.Threading.Tasks.ValueTask(instance.InheritedTimeoutAttribute(cancellationToken)); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -370,12 +391,12 @@ internal sealed class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Te yield break; } } -internal static class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_InheritedTimeoutAttribute__CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_InheritedTimeoutAttribute_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_InheritedTimeoutAttribute__CancellationToken_TestSource()); } } @@ -387,7 +408,7 @@ internal static class TimeoutCancellationTokenTests_InheritedTimeoutAttribute_Mo #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_DataTest__int_CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -397,7 +418,7 @@ internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : g TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "DataTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.TimeoutAttribute(5_000), @@ -464,7 +485,7 @@ internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : g ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("DataTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -472,7 +493,7 @@ internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : g TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -498,16 +519,22 @@ internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : g { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var context = global::TUnit.Core.TestContext.Current; - switch (args.Length) + try { - case 1: - await instance.DataTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + var context = global::TUnit.Core.TestContext.Current; + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.DataTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None)); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -516,12 +543,12 @@ internal sealed class TimeoutCancellationTokenTests_DataTest_TestSource_GUID : g yield break; } } -internal static class TimeoutCancellationTokenTests_DataTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_DataTest__int_CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_DataTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_DataTest__int_CancellationToken_TestSource()); } } @@ -533,7 +560,7 @@ internal static class TimeoutCancellationTokenTests_DataTest_ModuleInitializer_G #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_DataSourceTest__int_CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -543,7 +570,7 @@ internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GU TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "DataSourceTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TimeoutAttribute(5_000), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Failure), @@ -631,7 +658,7 @@ internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GU ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("DataSourceTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -639,7 +666,7 @@ internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GU TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -665,16 +692,22 @@ internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GU { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var context = global::TUnit.Core.TestContext.Current; - switch (args.Length) + try + { + var context = global::TUnit.Core.TestContext.Current; + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.DataSourceTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None)); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.DataSourceTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -683,12 +716,12 @@ internal sealed class TimeoutCancellationTokenTests_DataSourceTest_TestSource_GU yield break; } } -internal static class TimeoutCancellationTokenTests_DataSourceTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_DataSourceTest__int_CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_DataSourceTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_DataSourceTest__int_CancellationToken_TestSource()); } } @@ -700,7 +733,7 @@ internal static class TimeoutCancellationTokenTests_DataSourceTest_ModuleInitial #nullable enable namespace TUnit.Generated; -internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TimeoutCancellationTokenTests_MatrixTest__int_CancellationToken_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -710,7 +743,7 @@ internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), TestMethodName = "MatrixTest", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.Core.TimeoutAttribute(5_000), @@ -778,7 +811,7 @@ internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : ReflectionInfo = typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests).GetMethod("MatrixTest", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[1] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TimeoutCancellationTokenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -786,7 +819,7 @@ internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests)), Name = "TimeoutCancellationTokenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = new global::TUnit.Core.ParameterMetadata[] { new global::TUnit.Core.ParameterMetadata(typeof(int)) @@ -812,16 +845,22 @@ internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : { return new global::TUnit.TestProject.TimeoutCancellationTokenTests(TUnit.Core.Helpers.CastHelper.Cast(args[0])); }, - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - var context = global::TUnit.Core.TestContext.Current; - switch (args.Length) + try + { + var context = global::TUnit.Core.TestContext.Current; + switch (args.Length) + { + case 1: + return new global::System.Threading.Tasks.ValueTask(instance.MatrixTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None)); + default: + throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + } + } + catch (global::System.Exception ex) { - case 1: - await instance.MatrixTest(TUnit.Core.Helpers.CastHelper.Cast(args[0]), context?.CancellationToken ?? System.Threading.CancellationToken.None); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 1 argument, but got {args.Length}"); + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } }, }; @@ -830,11 +869,11 @@ internal sealed class TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID : yield break; } } -internal static class TimeoutCancellationTokenTests_MatrixTest_ModuleInitializer_GUID +internal static class TUnit_TestProject_TimeoutCancellationTokenTests_MatrixTest__int_CancellationToken_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TimeoutCancellationTokenTests_MatrixTest_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TimeoutCancellationTokenTests), new TUnit_TestProject_TimeoutCancellationTokenTests_MatrixTest__int_CancellationToken_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/TupleDataSourceDrivenTests.Test.verified.txt b/TUnit.Core.SourceGenerator.Tests/TupleDataSourceDrivenTests.Test.verified.txt index becb42f8cc..11251b1886 100644 --- a/TUnit.Core.SourceGenerator.Tests/TupleDataSourceDrivenTests.Test.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/TupleDataSourceDrivenTests.Test.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSour TestClassType = typeof(global::TUnit.TestProject.TupleDataSourceDrivenTests), TestMethodName = "DataSource_TupleMethod", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute(), new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass) @@ -71,7 +71,7 @@ internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSour ReflectionInfo = typeof(global::TUnit.TestProject.TupleDataSourceDrivenTests).GetMethod("DataSource_TupleMethod", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(string), typeof(bool) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TupleDataSourceDrivenTests", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.TupleDataSourceDrivenTests", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -79,7 +79,7 @@ internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSour TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TupleDataSourceDrivenTests)), Name = "TupleDataSourceDrivenTests", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", static () => new global::TUnit.Core.AssemblyMetadata { Name = "TestsBase`1" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -93,17 +93,23 @@ internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSour }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.TupleDataSourceDrivenTests(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + instance.DataSource_TupleMethod(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -111,11 +117,11 @@ internal sealed class TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSour yield break; } } -internal static class TupleDataSourceDrivenTests_DataSource_TupleMethod_ModuleInitializer_GUID +internal static class TUnit_TestProject_TupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TupleDataSourceDrivenTests), new TupleDataSourceDrivenTests_DataSource_TupleMethod_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TupleDataSourceDrivenTests), new TUnit_TestProject_TupleDataSourceDrivenTests_DataSource_TupleMethod__int_string_bool_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_AotSafeDataSourceFactories.verified.txt b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_AotSafeDataSourceFactories.verified.txt index c886725446..c8205e4f6e 100644 --- a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_AotSafeDataSourceFactories.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_AotSafeDataSourceFactories.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_AotDataSourceTest_TestWithDataSource__int_int_int_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : glo TestClassType = typeof(global::TUnit.TestProject.AotDataSourceTest), TestMethodName = "TestWithDataSource", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -60,7 +60,7 @@ internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : glo ReflectionInfo = typeof(global::TUnit.TestProject.AotDataSourceTest).GetMethod("TestWithDataSource", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(int), typeof(int), typeof(int) }, null)!.GetParameters()[2] } }, - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.AotDataSourceTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.AotDataSourceTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -68,7 +68,7 @@ internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : glo TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.AotDataSourceTest)), Name = "AotDataSourceTest", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -82,17 +82,23 @@ internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : glo }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.AotDataSourceTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - switch (args.Length) + try { - case 3: - instance.TestWithDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); - break; - default: - throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + switch (args.Length) + { + case 3: + instance.TestWithDataSource(TUnit.Core.Helpers.CastHelper.Cast(args[0]), TUnit.Core.Helpers.CastHelper.Cast(args[1]), TUnit.Core.Helpers.CastHelper.Cast(args[2])); + return default(global::System.Threading.Tasks.ValueTask); + default: + throw new global::System.ArgumentException($"Expected exactly 3 arguments, but got {args.Length}"); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); } - await global::System.Threading.Tasks.Task.CompletedTask; }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -100,11 +106,11 @@ internal sealed class AotDataSourceTest_TestWithDataSource_TestSource_GUID : glo yield break; } } -internal static class AotDataSourceTest_TestWithDataSource_ModuleInitializer_GUID +internal static class TUnit_TestProject_AotDataSourceTest_TestWithDataSource__int_int_int_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AotDataSourceTest), new AotDataSourceTest_TestWithDataSource_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.AotDataSourceTest), new TUnit_TestProject_AotDataSourceTest_TestWithDataSource__int_int_int_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ConfigurationSupport.verified.txt b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ConfigurationSupport.verified.txt index fbd1a8c41f..323116974b 100644 --- a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ConfigurationSupport.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ConfigurationSupport.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ConfigurationTest_TestWithConfiguration_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.ConfigurationTest), TestMethodName = "TestWithConfiguration", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.ConfigurationTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.ConfigurationTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ConfigurationTest)), Name = "ConfigurationTest", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ConfigurationTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.TestWithConfiguration(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.TestWithConfiguration(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,11 +73,11 @@ internal sealed class ConfigurationTest_TestWithConfiguration_TestSource_GUID : yield break; } } -internal static class ConfigurationTest_TestWithConfiguration_ModuleInitializer_GUID +internal static class TUnit_TestProject_ConfigurationTest_TestWithConfiguration_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConfigurationTest), new ConfigurationTest_TestWithConfiguration_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ConfigurationTest), new TUnit_TestProject_ConfigurationTest_TestWithConfiguration_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ModuleInitializer_Generation.verified.txt b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ModuleInitializer_Generation.verified.txt index 48d71739df..c545f3a741 100644 --- a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ModuleInitializer_Generation.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_ModuleInitializer_Generation.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_ModuleInitializerTest_TestWithModuleInit_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : TestClassType = typeof(global::TUnit.TestProject.ModuleInitializerTest), TestMethodName = "TestWithModuleInit", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.ModuleInitializerTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.ModuleInitializerTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.ModuleInitializerTest)), Name = "ModuleInitializerTest", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.ModuleInitializerTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.TestWithModuleInit(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.TestWithModuleInit(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,11 +73,11 @@ internal sealed class ModuleInitializerTest_TestWithModuleInit_TestSource_GUID : yield break; } } -internal static class ModuleInitializerTest_TestWithModuleInit_ModuleInitializer_GUID +internal static class TUnit_TestProject_ModuleInitializerTest_TestWithModuleInit_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ModuleInitializerTest), new ModuleInitializerTest_TestWithModuleInit_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.ModuleInitializerTest), new TUnit_TestProject_ModuleInitializerTest_TestWithModuleInit_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_StronglyTypedDelegates_Generation.verified.txt b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_StronglyTypedDelegates_Generation.verified.txt index 46b9c93deb..5754b8bd4e 100644 --- a/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_StronglyTypedDelegates_Generation.verified.txt +++ b/TUnit.Core.SourceGenerator.Tests/UnifiedReflectionFreeTests.Test_StronglyTypedDelegates_Generation.verified.txt @@ -3,7 +3,7 @@ #nullable enable namespace TUnit.Generated; -internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource +internal sealed class TUnit_TestProject_TypedDelegateTest_TestWithDelegate_TestSource : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource { public async global::System.Collections.Generic.IAsyncEnumerable GetTestsAsync(string testSessionId, [global::System.Runtime.CompilerServices.EnumeratorCancellation] global::System.Threading.CancellationToken cancellationToken = default) { @@ -13,7 +13,7 @@ internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : globa TestClassType = typeof(global::TUnit.TestProject.TypedDelegateTest), TestMethodName = "TestWithDelegate", Dependencies = global::System.Array.Empty(), - AttributeFactory = () => + AttributeFactory = static () => [ new global::TUnit.Core.TestAttribute() ], @@ -33,7 +33,7 @@ internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : globa ReturnType = typeof(void), ReturnTypeInfo = new global::TUnit.Core.ConcreteType(typeof(void)), Parameters = global::System.Array.Empty(), - Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.TypedDelegateTest", () => + Class = global::TUnit.Core.ClassMetadata.GetOrAdd("UnifiedReflectionFreeTests:global::TUnit.TestProject.TypedDelegateTest", static () => { var classMetadata = new global::TUnit.Core.ClassMetadata { @@ -41,7 +41,7 @@ internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : globa TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.TypedDelegateTest)), Name = "TypedDelegateTest", Namespace = "TUnit.TestProject", - Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("UnifiedReflectionFreeTests", static () => new global::TUnit.Core.AssemblyMetadata { Name = "UnifiedReflectionFreeTests" }), Parameters = global::System.Array.Empty(), Properties = global::System.Array.Empty(), Parent = null @@ -55,10 +55,17 @@ internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : globa }) }, InstanceFactory = (typeArgs, args) => new global::TUnit.TestProject.TypedDelegateTest(), - InvokeTypedTest = async (instance, args, cancellationToken) => + InvokeTypedTest = static (instance, args, cancellationToken) => { - instance.TestWithDelegate(); - await global::System.Threading.Tasks.Task.CompletedTask; + try + { + instance.TestWithDelegate(); + return default(global::System.Threading.Tasks.ValueTask); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } }, }; metadata.UseRuntimeDataGeneration(testSessionId); @@ -66,11 +73,11 @@ internal sealed class TypedDelegateTest_TestWithDelegate_TestSource_GUID : globa yield break; } } -internal static class TypedDelegateTest_TestWithDelegate_ModuleInitializer_GUID +internal static class TUnit_TestProject_TypedDelegateTest_TestWithDelegate_ModuleInitializer { [global::System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { - global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TypedDelegateTest), new TypedDelegateTest_TestWithDelegate_TestSource_GUID()); + global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.TypedDelegateTest), new TUnit_TestProject_TypedDelegateTest_TestWithDelegate_TestSource()); } } diff --git a/TUnit.Core.SourceGenerator/CodeGenerationHelpers.cs b/TUnit.Core.SourceGenerator/CodeGenerationHelpers.cs index 5c0214dde2..48e70d9a27 100644 --- a/TUnit.Core.SourceGenerator/CodeGenerationHelpers.cs +++ b/TUnit.Core.SourceGenerator/CodeGenerationHelpers.cs @@ -540,7 +540,7 @@ private static string GenerateCustomDataProvider(AttributeData attr) /// - /// Generates all test-related attributes for the TestMetadata.Attributes field. + /// Generates all test-related attributes for the TestMetadata.AttributesByType field as a dictionary. /// public static string GenerateTestAttributes(IMethodSymbol methodSymbol) { @@ -552,24 +552,42 @@ public static string GenerateTestAttributes(IMethodSymbol methodSymbol) if (allAttributes.Count == 0) { - return "System.Array.Empty()"; + return "new System.Collections.Generic.Dictionary>().AsReadOnly()"; } - // Generate as a single line array to avoid CS8802 parser issues + // Group attributes by type + var attributesByType = allAttributes + .GroupBy(attr => attr.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) ?? "System.Attribute") + .ToList(); + using var writer = new CodeWriter("", includeHeader: false); - // Generate inline array to avoid parser issues - using (writer.BeginArrayInitializer("new System.Attribute[]", terminator: "")) + // Generate dictionary initializer + writer.Append("new System.Collections.Generic.Dictionary>()"); + writer.AppendLine(); + writer.AppendLine("{"); + writer.Indent(); + + foreach (var group in attributesByType) { + var typeString = group.Key; + var attrs = group.ToList(); + + writer.Append($"[typeof({typeString})] = new System.Attribute[] {{ "); + var attributeStrings = new List(); - foreach (var attr in allAttributes) + foreach (var attr in attrs) { - // Use unified approach for all attributes attributeStrings.Add(GenerateAttributeInstantiation(attr)); } + writer.Append(string.Join(", ", attributeStrings)); + writer.AppendLine(" },"); } + writer.Unindent(); + writer.Append("}.AsReadOnly()"); + return writer.ToString().Trim(); } diff --git a/TUnit.Core.SourceGenerator/Extensions/AttributeDataExtensions.cs b/TUnit.Core.SourceGenerator/Extensions/AttributeDataExtensions.cs index e13ab939d7..23edbd23f4 100644 --- a/TUnit.Core.SourceGenerator/Extensions/AttributeDataExtensions.cs +++ b/TUnit.Core.SourceGenerator/Extensions/AttributeDataExtensions.cs @@ -1,4 +1,5 @@ using Microsoft.CodeAnalysis; +using TUnit.Core.SourceGenerator.Helpers; namespace TUnit.Core.SourceGenerator.Extensions; @@ -16,19 +17,28 @@ public static bool IsTestAttribute(this AttributeData? attributeData) public static bool IsDataSourceAttribute(this AttributeData? attributeData) { - return attributeData?.AttributeClass?.AllInterfaces.Any(x => - x.GloballyQualified() == WellKnownFullyQualifiedClassNames.IDataSourceAttribute.WithGlobalPrefix) - == true; + if (attributeData?.AttributeClass == null) + { + return false; + } + + // Use InterfaceCache instead of AllInterfaces.Any() for better performance + return InterfaceCache.ImplementsInterface(attributeData.AttributeClass, + WellKnownFullyQualifiedClassNames.IDataSourceAttribute.WithGlobalPrefix); } - + public static bool IsTypedDataSourceAttribute(this AttributeData? attributeData) { - return attributeData?.AttributeClass?.AllInterfaces.Any(x => - x.IsGenericType && - x.ConstructedFrom.GloballyQualified() == WellKnownFullyQualifiedClassNames.ITypedDataSourceAttribute.WithGlobalPrefix + "`1") - == true; + if (attributeData?.AttributeClass == null) + { + return false; + } + + // Use InterfaceCache instead of AllInterfaces.Any() for better performance + return InterfaceCache.ImplementsGenericInterface(attributeData.AttributeClass, + WellKnownFullyQualifiedClassNames.ITypedDataSourceAttribute.WithGlobalPrefix + "`1"); } - + public static ITypeSymbol? GetTypedDataSourceType(this AttributeData? attributeData) { if (attributeData?.AttributeClass == null) @@ -36,10 +46,10 @@ public static bool IsTypedDataSourceAttribute(this AttributeData? attributeData) return null; } - var typedInterface = attributeData.AttributeClass.AllInterfaces - .FirstOrDefault(x => x.IsGenericType && - x.ConstructedFrom.GloballyQualified() == WellKnownFullyQualifiedClassNames.ITypedDataSourceAttribute.WithGlobalPrefix + "`1"); - + // Use InterfaceCache instead of AllInterfaces.FirstOrDefault() for better performance + var typedInterface = InterfaceCache.GetGenericInterface(attributeData.AttributeClass, + WellKnownFullyQualifiedClassNames.ITypedDataSourceAttribute.WithGlobalPrefix + "`1"); + return typedInterface?.TypeArguments.FirstOrDefault(); } diff --git a/TUnit.Core.SourceGenerator/Generators/HookMetadataGenerator.cs b/TUnit.Core.SourceGenerator/Generators/HookMetadataGenerator.cs index c49e6dd639..8be857e086 100644 --- a/TUnit.Core.SourceGenerator/Generators/HookMetadataGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/HookMetadataGenerator.cs @@ -4,6 +4,7 @@ using TUnit.Core.SourceGenerator.CodeGenerators.Helpers; using TUnit.Core.SourceGenerator.CodeGenerators.Writers; using TUnit.Core.SourceGenerator.Extensions; +using TUnit.Core.SourceGenerator.Helpers; namespace TUnit.Core.SourceGenerator.Generators; @@ -132,38 +133,14 @@ private static void GenerateIndividualHookFile(SourceProductionContext context, private static string GetSafeFileName(HookMethodMetadata hook) { - var typeName = hook.TypeSymbol.Name; - var methodName = hook.MethodSymbol.Name; - - // Remove generic type parameters from type name for file safety - if (hook.TypeSymbol.IsGenericType) - { - var genericIndex = typeName.IndexOf('`'); - if (genericIndex > 0) - { - typeName = typeName.Substring(0, genericIndex); - } - } - - var safeTypeName = typeName - .Replace(".", "_") - .Replace("<", "_") - .Replace(">", "_") - .Replace(",", "_") - .Replace(" ", "") - .Replace("`", "_") - .Replace("+", "_"); + // Use FileNameHelper for deterministic naming (fixes GUID issue that breaks incremental compilation) + var baseFileName = FileNameHelper.GetDeterministicFileNameForMethod(hook.TypeSymbol, hook.MethodSymbol); - var safeMethodName = methodName - .Replace(".", "_") - .Replace("<", "_") - .Replace(">", "_") - .Replace(",", "_") - .Replace(" ", ""); + // Remove the .g.cs extension since it's used as an identifier, not just a filename + var fileNameWithoutExtension = baseFileName.Substring(0, baseFileName.Length - ".g.cs".Length); - var guid = System.Guid.NewGuid().ToString("N"); - - return $"{safeTypeName}_{safeMethodName}_{hook.HookKind}_{hook.HookType}_{guid}"; + // Add hook-specific information to make it unique (WITHOUT .g.cs - that's added when registering the source file) + return $"{fileNameWithoutExtension}_{hook.HookKind}_{hook.HookType}"; } private static void GenerateHookRegistration(CodeWriter writer, HookMethodMetadata hook) diff --git a/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs b/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs index 43a2a55606..4a65b807c1 100644 --- a/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs +++ b/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs @@ -123,7 +123,16 @@ private static void GenerateInheritedTestSources(SourceProductionContext context var concreteMethod = FindConcreteMethodImplementation(classInfo.TypeSymbol, method); - var inheritanceDepth = CalculateInheritanceDepth(classInfo.TypeSymbol, method); + // Calculate inheritance depth using concrete method if available + var methodToCheck = concreteMethod ?? method; + var inheritanceDepth = CalculateInheritanceDepth(classInfo.TypeSymbol, methodToCheck); + + // Skip methods declared directly on this class (inheritance depth = 0) + // Those are already handled by the regular test method registration + if (inheritanceDepth == 0) + { + continue; + } var (filePath, lineNumber) = GetTestMethodSourceLocation(method, testAttribute, classInfo); // If the method is from a generic base class, use the constructed version from the inheritance hierarchy @@ -165,7 +174,10 @@ private static void GenerateInheritedTestSources(SourceProductionContext context private static int CalculateInheritanceDepth(INamedTypeSymbol testClass, IMethodSymbol testMethod) { - if (testMethod.ContainingType.Equals(testClass, SymbolEqualityComparer.Default)) + var methodContainingType = testMethod.ContainingType.OriginalDefinition; + var testClassOriginal = testClass.OriginalDefinition; + + if (SymbolEqualityComparer.Default.Equals(methodContainingType, testClassOriginal)) { return 0; } @@ -176,7 +188,8 @@ private static int CalculateInheritanceDepth(INamedTypeSymbol testClass, IMethod while (currentType != null) { depth++; - if (testMethod.ContainingType.Equals(currentType, SymbolEqualityComparer.Default)) + var currentTypeOriginal = currentType.OriginalDefinition; + if (SymbolEqualityComparer.Default.Equals(methodContainingType, currentTypeOriginal)) { return depth; } @@ -202,7 +215,7 @@ private static void GenerateTestMethodSource(SourceProductionContext context, Te GenerateFileHeader(writer); GenerateTestMetadata(writer, testMethod); - var fileName = $"{testMethod.TypeSymbol.Name}_{testMethod.MethodSymbol.Name}_{Guid.NewGuid():N}.g.cs"; + var fileName = FileNameHelper.GetDeterministicFileNameForMethod(testMethod.TypeSymbol, testMethod.MethodSymbol); context.AddSource(fileName, SourceText.From(writer.ToString(), Encoding.UTF8)); } catch (Exception ex) @@ -240,10 +253,12 @@ private static void GenerateTestMetadata(CodeWriter writer, TestMethodMetadata t var className = testMethod.TypeSymbol.GloballyQualified(); var methodName = testMethod.MethodSymbol.Name; - var guid = Guid.NewGuid().ToString("N"); - var combinationGuid = Guid.NewGuid().ToString("N").Substring(0, 8); - writer.AppendLine($"internal sealed class {testMethod.TypeSymbol.Name}_{methodName}_TestSource_{guid} : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource"); + // Generate unique class name using same pattern as filename (without .g.cs extension) + var uniqueClassName = FileNameHelper.GetDeterministicFileNameForMethod(testMethod.TypeSymbol, testMethod.MethodSymbol) + .Replace(".g.cs", "_TestSource"); + + writer.AppendLine($"internal sealed class {uniqueClassName} : global::TUnit.Core.Interfaces.SourceGenerator.ITestSource"); writer.AppendLine("{"); writer.Indent(); @@ -283,16 +298,16 @@ private static void GenerateTestMetadata(CodeWriter writer, TestMethodMetadata t if (hasTypedDataSource || hasGenerateGenericTest || testMethod.IsGenericMethod || hasClassArguments || hasTypedDataSourceForGenericType || hasMethodArgumentsForGenericType || hasMethodDataSourceForGenericType) { - GenerateGenericTestWithConcreteTypes(writer, testMethod, className, combinationGuid); + GenerateGenericTestWithConcreteTypes(writer, testMethod, className, uniqueClassName); } else { - GenerateTestMetadataInstance(writer, testMethod, className, combinationGuid); + GenerateTestMetadataInstance(writer, testMethod, className, uniqueClassName); } } else { - GenerateTestMetadataInstance(writer, testMethod, className, combinationGuid); + GenerateTestMetadataInstance(writer, testMethod, className, uniqueClassName); } writer.AppendLine("yield break;"); @@ -302,7 +317,7 @@ private static void GenerateTestMetadata(CodeWriter writer, TestMethodMetadata t writer.Unindent(); writer.AppendLine("}"); - GenerateModuleInitializer(writer, testMethod, guid); + GenerateModuleInitializer(writer, testMethod, uniqueClassName); } private static void GenerateSpecificGenericInstantiation( @@ -379,7 +394,7 @@ private static void GenerateAotFriendlyInvokers( p.Type.Name == "CancellationToken" && p.Type.ContainingNamespace?.ToString() == "System.Threading"); - writer.AppendLine("InstanceFactory = (typeArgs, args) =>"); + writer.AppendLine("InstanceFactory = static (typeArgs, args) =>"); writer.AppendLine("{"); writer.Indent(); @@ -388,7 +403,12 @@ private static void GenerateAotFriendlyInvokers( writer.Unindent(); writer.AppendLine("},"); - writer.AppendLine("InvokeTypedTest = async (instance, args, cancellationToken) =>"); + writer.AppendLine("InvokeTypedTest = static (instance, args, cancellationToken) =>"); + writer.AppendLine("{"); + writer.Indent(); + + // Wrap entire lambda body in try-catch to handle synchronous exceptions + writer.AppendLine("try"); writer.AppendLine("{"); writer.Indent(); @@ -418,7 +438,16 @@ private static void GenerateAotFriendlyInvokers( } } - writer.AppendLine($"await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}<{typeArgsString}>({string.Join(", ", parameterCasts)}));"); + writer.AppendLine($"return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}<{typeArgsString}>({string.Join(", ", parameterCasts)}));"); + + writer.Unindent(); + writer.AppendLine("}"); + writer.AppendLine("catch (global::System.Exception ex)"); + writer.AppendLine("{"); + writer.Indent(); + writer.AppendLine("return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));"); + writer.Unindent(); + writer.AppendLine("}"); writer.Unindent(); writer.AppendLine("},"); @@ -523,7 +552,7 @@ private static void GenerateMetadata(CodeWriter writer, TestMethodMetadata testM GenerateDependencies(writer, compilation, methodSymbol); - writer.AppendLine("AttributeFactory = () =>"); + writer.AppendLine("AttributeFactory = static () =>"); writer.AppendLine("["); writer.Indent(); @@ -538,6 +567,13 @@ private static void GenerateMetadata(CodeWriter writer, TestMethodMetadata testM writer.Unindent(); writer.AppendLine("],"); + // Extract and emit RepeatCount if present + var repeatCount = ExtractRepeatCount(methodSymbol, testMethod.TypeSymbol); + if (repeatCount.HasValue) + { + writer.AppendLine($"RepeatCount = {repeatCount.Value},"); + } + GenerateDataSources(writer, testMethod); GeneratePropertyInjections(writer, testMethod.TypeSymbol, testMethod.TypeSymbol.GloballyQualified()); @@ -562,7 +598,7 @@ private static void GenerateMetadataForConcreteInstantiation(CodeWriter writer, GenerateDependencies(writer, compilation, methodSymbol); - writer.AppendLine("AttributeFactory = () =>"); + writer.AppendLine("AttributeFactory = static () =>"); writer.AppendLine("["); writer.Indent(); @@ -578,6 +614,13 @@ private static void GenerateMetadataForConcreteInstantiation(CodeWriter writer, writer.Unindent(); writer.AppendLine("],"); + // Extract and emit RepeatCount if present + var repeatCount = ExtractRepeatCount(methodSymbol, testMethod.TypeSymbol); + if (repeatCount.HasValue) + { + writer.AppendLine($"RepeatCount = {repeatCount.Value},"); + } + // No data sources for concrete instantiations writer.AppendLine("DataSources = global::System.Array.Empty(),"); writer.AppendLine("ClassDataSources = global::System.Array.Empty(),"); @@ -1809,17 +1852,23 @@ private static void GenerateTypedInvokers(CodeWriter writer, TestMethodMetadata // Generate InvokeTypedTest for non-generic tests var isAsync = IsAsyncMethod(testMethod.MethodSymbol); + var returnsValueTask = ReturnsValueTask(testMethod.MethodSymbol); if (testMethod is { IsGenericType: false, IsGenericMethod: false }) { - GenerateConcreteTestInvoker(writer, testMethod, className, methodName, isAsync, hasCancellationToken, parametersFromArgs); + GenerateConcreteTestInvoker(writer, testMethod, className, methodName, isAsync, returnsValueTask, hasCancellationToken, parametersFromArgs); } } - private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMetadata testMethod, string className, string methodName, bool isAsync, bool hasCancellationToken, IParameterSymbol[] parametersFromArgs) + private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMetadata testMethod, string className, string methodName, bool isAsync, bool returnsValueTask, bool hasCancellationToken, IParameterSymbol[] parametersFromArgs) { // Generate InvokeTypedTest which is required by CreateExecutableTestFactory - writer.AppendLine("InvokeTypedTest = async (instance, args, cancellationToken) =>"); + writer.AppendLine("InvokeTypedTest = static (instance, args, cancellationToken) =>"); + writer.AppendLine("{"); + writer.Indent(); + + // Wrap entire lambda body in try-catch to handle synchronous exceptions + writer.AppendLine("try"); writer.AppendLine("{"); writer.Indent(); @@ -1853,11 +1902,19 @@ private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMet : $"instance.{methodName}({tupleConstruction})"; if (isAsync) { - writer.AppendLine($"await {methodCallReconstructed};"); + if (returnsValueTask) + { + writer.AppendLine($"return {methodCallReconstructed};"); + } + else + { + writer.AppendLine($"return new global::System.Threading.Tasks.ValueTask({methodCallReconstructed});"); + } } else { writer.AppendLine($"{methodCallReconstructed};"); + writer.AppendLine("return default(global::System.Threading.Tasks.ValueTask);"); } writer.Unindent(); writer.AppendLine("}"); @@ -1870,11 +1927,19 @@ private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMet : $"instance.{methodName}(TUnit.Core.Helpers.CastHelper.Cast<{singleTupleParam.GloballyQualified()}>(args[0]))"; if (isAsync) { - writer.AppendLine($"await {methodCallDirect};"); + if (returnsValueTask) + { + writer.AppendLine($"return {methodCallDirect};"); + } + else + { + writer.AppendLine($"return new global::System.Threading.Tasks.ValueTask({methodCallDirect});"); + } } else { writer.AppendLine($"{methodCallDirect};"); + writer.AppendLine("return default(global::System.Threading.Tasks.ValueTask);"); } writer.Unindent(); writer.AppendLine("}"); @@ -1892,12 +1957,19 @@ private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMet : $"instance.{methodName}()"; if (isAsync) { - writer.AppendLine($"await {typedMethodCall};"); + if (returnsValueTask) + { + writer.AppendLine($"return {typedMethodCall};"); + } + else + { + writer.AppendLine($"return new global::System.Threading.Tasks.ValueTask({typedMethodCall});"); + } } else { writer.AppendLine($"{typedMethodCall};"); - writer.AppendLine("await global::System.Threading.Tasks.Task.CompletedTask;"); + writer.AppendLine("return default(global::System.Threading.Tasks.ValueTask);"); } } else @@ -1937,13 +2009,20 @@ private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMet if (isAsync) { - writer.AppendLine($"await {typedMethodCall};"); + if (returnsValueTask) + { + writer.AppendLine($"return {typedMethodCall};"); + } + else + { + writer.AppendLine($"return new global::System.Threading.Tasks.ValueTask({typedMethodCall});"); + } } else { writer.AppendLine($"{typedMethodCall};"); + writer.AppendLine("return default(global::System.Threading.Tasks.ValueTask);"); } - writer.AppendLine("break;"); writer.Unindent(); } @@ -1961,29 +2040,33 @@ private static void GenerateConcreteTestInvoker(CodeWriter writer, TestMethodMet writer.Unindent(); writer.AppendLine("}"); - - if (!isAsync) - { - writer.AppendLine("await global::System.Threading.Tasks.Task.CompletedTask;"); - } } + writer.Unindent(); + writer.AppendLine("}"); + writer.AppendLine("catch (global::System.Exception ex)"); + writer.AppendLine("{"); + writer.Indent(); + writer.AppendLine("return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));"); + writer.Unindent(); + writer.AppendLine("}"); + writer.Unindent(); writer.AppendLine("},"); } - private static void GenerateModuleInitializer(CodeWriter writer, TestMethodMetadata testMethod, string guid) + private static void GenerateModuleInitializer(CodeWriter writer, TestMethodMetadata testMethod, string uniqueClassName) { writer.AppendLine(); - writer.AppendLine($"internal static class {testMethod.TypeSymbol.Name}_{testMethod.MethodSymbol.Name}_ModuleInitializer_{guid}"); + writer.AppendLine($"internal static class {uniqueClassName.Replace("_TestSource", "_ModuleInitializer")}"); writer.AppendLine("{"); writer.Indent(); writer.AppendLine("[global::System.Runtime.CompilerServices.ModuleInitializer]"); writer.AppendLine("public static void Initialize()"); writer.AppendLine("{"); writer.Indent(); - writer.AppendLine($"global::TUnit.Core.SourceRegistrar.Register({GenerateTypeReference(testMethod.TypeSymbol, testMethod.IsGenericType)}, new {testMethod.TypeSymbol.Name}_{testMethod.MethodSymbol.Name}_TestSource_{guid}());"); + writer.AppendLine($"global::TUnit.Core.SourceRegistrar.Register({GenerateTypeReference(testMethod.TypeSymbol, testMethod.IsGenericType)}, new {uniqueClassName}());"); writer.Unindent(); writer.AppendLine("}"); writer.Unindent(); @@ -2001,6 +2084,12 @@ private static bool IsAsyncMethod(IMethodSymbol method) returnTypeName.StartsWith("ValueTask<"); } + private static bool ReturnsValueTask(IMethodSymbol method) + { + var returnTypeName = method.ReturnType.ToDisplayString(); + return returnTypeName.StartsWith("System.Threading.Tasks.ValueTask"); + } + private static void GenerateDependencies(CodeWriter writer, Compilation compilation, IMethodSymbol methodSymbol) { var dependsOnAttributes = methodSymbol.GetAttributes() @@ -2623,7 +2712,7 @@ private static void GenerateGenericTestWithConcreteTypes( GenerateMetadataForConcreteInstantiation(writer, testMethod); // Generate instance factory that works with generic types - writer.AppendLine("InstanceFactory = (typeArgs, args) =>"); + writer.AppendLine("InstanceFactory = static (typeArgs, args) =>"); writer.AppendLine("{"); writer.Indent(); @@ -2708,9 +2797,6 @@ private static void GenerateGenericTestWithConcreteTypes( var constraintsValid = ValidateClassTypeConstraints(testMethod.TypeSymbol, classTypes) && ValidateTypeConstraints(testMethod.MethodSymbol, methodTypes); - // TODO: Fix ValidateTypeConstraints method - temporarily skip validation - constraintsValid = true; - if (!constraintsValid) { continue; @@ -2808,9 +2894,6 @@ private static void GenerateGenericTestWithConcreteTypes( // Validate class type constraints var constraintsValid = ValidateClassTypeConstraints(testMethod.TypeSymbol, inferredTypes); - // TODO: Fix ValidateClassTypeConstraints method - temporarily skip validation - constraintsValid = true; - if (!constraintsValid) { continue; @@ -4135,7 +4218,7 @@ private static void GenerateConcreteTestMetadata( GenerateConcreteMetadataWithFilteredDataSources(writer, testMethod, specificArgumentsAttribute, typeArguments); // Generate instance factory - writer.AppendLine("InstanceFactory = (typeArgs, args) =>"); + writer.AppendLine("InstanceFactory = static (typeArgs, args) =>"); writer.AppendLine("{"); writer.Indent(); @@ -4184,7 +4267,12 @@ private static void GenerateConcreteTestMetadata( writer.AppendLine("},"); // Generate strongly-typed test invoker - writer.AppendLine("InvokeTypedTest = async (instance, args, cancellationToken) =>"); + writer.AppendLine("InvokeTypedTest = static (instance, args, cancellationToken) =>"); + writer.AppendLine("{"); + writer.Indent(); + + // Wrap entire lambda body in try-catch to handle synchronous exceptions + writer.AppendLine("try"); writer.AppendLine("{"); writer.Indent(); @@ -4215,13 +4303,22 @@ private static void GenerateConcreteTestMetadata( if (methodTypeArgs.Length > 0) { var methodTypeArgsString = string.Join(", ", methodTypeArgs.Select(t => t.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); - writer.AppendLine($"await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}<{methodTypeArgsString}>({string.Join(", ", parameterCasts)}));"); + writer.AppendLine($"return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}<{methodTypeArgsString}>({string.Join(", ", parameterCasts)}));"); } else { - writer.AppendLine($"await global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}({string.Join(", ", parameterCasts)}));"); + writer.AppendLine($"return global::TUnit.Core.AsyncConvert.Convert(() => typedInstance.{methodName}({string.Join(", ", parameterCasts)}));"); } + writer.Unindent(); + writer.AppendLine("}"); + writer.AppendLine("catch (global::System.Exception ex)"); + writer.AppendLine("{"); + writer.Indent(); + writer.AppendLine("return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));"); + writer.Unindent(); + writer.AppendLine("}"); + writer.Unindent(); writer.AppendLine("}"); @@ -4319,13 +4416,20 @@ private static void GenerateConcreteMetadataWithFilteredDataSources( filteredAttributes.AddRange(testMethod.TypeSymbol.GetAttributesIncludingBaseTypes()); filteredAttributes.AddRange(testMethod.TypeSymbol.ContainingAssembly.GetAttributes()); - writer.AppendLine("AttributeFactory = () =>"); + writer.AppendLine("AttributeFactory = static () =>"); writer.AppendLine("["); writer.Indent(); AttributeWriter.WriteAttributes(writer, compilation, filteredAttributes.ToImmutableArray()); writer.Unindent(); writer.AppendLine("],"); + // Extract and emit RepeatCount if present + var repeatCount = ExtractRepeatCount(methodSymbol, typeSymbol); + if (repeatCount.HasValue) + { + writer.AppendLine($"RepeatCount = {repeatCount.Value},"); + } + // Filter data sources based on the specific attribute List methodDataSources; List classDataSources; @@ -4634,7 +4738,7 @@ private static void GenerateConcreteTestMetadataForNonGeneric( GenerateDependencies(writer, compilation, testMethod.MethodSymbol); // Generate attribute factory - writer.AppendLine("AttributeFactory = () =>"); + writer.AppendLine("AttributeFactory = static () =>"); writer.AppendLine("["); writer.Indent(); @@ -4648,6 +4752,13 @@ private static void GenerateConcreteTestMetadataForNonGeneric( writer.Unindent(); writer.AppendLine("],"); + // Extract and emit RepeatCount if present + var repeatCount = ExtractRepeatCount(testMethod.MethodSymbol, testMethod.TypeSymbol); + if (repeatCount.HasValue) + { + writer.AppendLine($"RepeatCount = {repeatCount.Value},"); + } + if (methodDataSourceAttribute == null) { writer.AppendLine("DataSources = global::System.Array.Empty(),"); @@ -4687,7 +4798,7 @@ private static void GenerateConcreteTestMetadataForNonGeneric( SourceInformationWriter.GenerateMethodInformation(writer, compilation, testMethod.TypeSymbol, testMethod.MethodSymbol, null, ','); // Generate instance factory - writer.AppendLine("InstanceFactory = (typeArgs, args) =>"); + writer.AppendLine("InstanceFactory = static (typeArgs, args) =>"); writer.AppendLine("{"); writer.Indent(); @@ -4752,6 +4863,32 @@ private static void GenerateConcreteTestMetadataForNonGeneric( writer.AppendLine("yield return metadata;"); } + + private static int? ExtractRepeatCount(IMethodSymbol methodSymbol, INamedTypeSymbol typeSymbol) + { + // Check method-level RepeatAttribute first + var repeatAttribute = methodSymbol.GetAttributes() + .FirstOrDefault(a => a.AttributeClass?.Name == "RepeatAttribute"); + + if (repeatAttribute?.ConstructorArguments.Length > 0 + && repeatAttribute.ConstructorArguments[0].Value is int methodCount) + { + return methodCount; + } + + // Check class-level RepeatAttribute (can be inherited) + var classRepeatAttr = typeSymbol.GetAttributesIncludingBaseTypes() + .FirstOrDefault(a => a.AttributeClass?.Name == "RepeatAttribute"); + + if (classRepeatAttr?.ConstructorArguments.Length > 0 + && classRepeatAttr.ConstructorArguments[0].Value is int classCount) + { + return classCount; + } + + // No repeat attribute found + return null; + } } public class InheritsTestsClassMetadata diff --git a/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs b/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs new file mode 100644 index 0000000000..7cbb86884e --- /dev/null +++ b/TUnit.Core.SourceGenerator/Helpers/FileNameHelper.cs @@ -0,0 +1,121 @@ +using System.Text; +using Microsoft.CodeAnalysis; + +namespace TUnit.Core.SourceGenerator.Helpers; + +/// +/// Helper for generating deterministic, sanitized filenames for generated source files. +/// +internal static class FileNameHelper +{ + /// + /// Generates a deterministic filename for a test class. + /// Format: {Namespace}_{ClassName}_{GenericArgs}.g.cs + /// + /// The type symbol for the test class + /// A deterministic filename like "MyNamespace_MyClass_T.g.cs" + public static string GetDeterministicFileName(INamedTypeSymbol typeSymbol) + { + var sb = new StringBuilder(); + + // Add namespace + if (!typeSymbol.ContainingNamespace.IsGlobalNamespace) + { + sb.Append(SanitizeForFileName(typeSymbol.ContainingNamespace.ToDisplayString())); + sb.Append('_'); + } + + // Add class name + sb.Append(SanitizeForFileName(typeSymbol.Name)); + + // Add generic type arguments if any + if (typeSymbol.TypeArguments.Length > 0) + { + sb.Append('_'); + for (int i = 0; i < typeSymbol.TypeArguments.Length; i++) + { + if (i > 0) sb.Append('_'); + sb.Append(SanitizeForFileName(typeSymbol.TypeArguments[i].Name)); + } + } + + sb.Append(".g.cs"); + return sb.ToString(); + } + + /// + /// Generates a deterministic filename for a test method. + /// Format: {Namespace}_{ClassName}_{MethodName}__{ParameterTypes}.g.cs + /// + /// The type symbol for the test class + /// The method symbol for the test method + /// A deterministic filename like "MyNamespace_MyClass_MyMethod__Int32_String.g.cs" + public static string GetDeterministicFileNameForMethod(INamedTypeSymbol typeSymbol, IMethodSymbol methodSymbol) + { + var sb = new StringBuilder(); + + // Add namespace + if (!typeSymbol.ContainingNamespace.IsGlobalNamespace) + { + sb.Append(SanitizeForFileName(typeSymbol.ContainingNamespace.ToDisplayString())); + sb.Append('_'); + } + + // Add class name (with generic parameters if any) + sb.Append(SanitizeForFileName(typeSymbol.Name)); + if (typeSymbol.TypeArguments.Length > 0) + { + sb.Append('_'); + for (int i = 0; i < typeSymbol.TypeArguments.Length; i++) + { + if (i > 0) sb.Append('_'); + sb.Append(SanitizeForFileName(typeSymbol.TypeArguments[i].Name)); + } + } + sb.Append('_'); + + // Add method name + sb.Append(SanitizeForFileName(methodSymbol.Name)); + + // Add parameters with double underscore separator + if (methodSymbol.Parameters.Length > 0) + { + sb.Append("__"); + for (int i = 0; i < methodSymbol.Parameters.Length; i++) + { + if (i > 0) sb.Append('_'); + sb.Append(SanitizeForFileName(methodSymbol.Parameters[i].Type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat))); + } + } + + sb.Append(".g.cs"); + return sb.ToString(); + } + + /// + /// Sanitizes a string to be safe for use in a filename. + /// Replaces invalid characters with underscores. + /// + private static string SanitizeForFileName(string input) + { + var sb = new StringBuilder(input.Length); + + foreach (var c in input) + { + // Replace invalid filename characters and special type characters with underscore + if (c == '<' || c == '>' || c == ':' || c == '"' || c == '/' || c == '\\' || + c == '|' || c == '?' || c == '*' || c == '.' || c == ',' || c == ' ' || + c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}') + { + sb.Append('_'); + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } + +} diff --git a/TUnit.Core.SourceGenerator/Helpers/GenericTypeInference.cs b/TUnit.Core.SourceGenerator/Helpers/GenericTypeInference.cs index 52cfbbd9ce..6acba46801 100644 --- a/TUnit.Core.SourceGenerator/Helpers/GenericTypeInference.cs +++ b/TUnit.Core.SourceGenerator/Helpers/GenericTypeInference.cs @@ -128,7 +128,6 @@ internal static class GenericTypeInference { var parameter = method.Parameters[i]; - // Check if this parameter uses a type parameter if (parameter.Type is ITypeParameterSymbol typeParam) { // Get the corresponding argument value from the attribute diff --git a/TUnit.Core.SourceGenerator/Helpers/InterfaceCache.cs b/TUnit.Core.SourceGenerator/Helpers/InterfaceCache.cs index 0064250efa..30f6f5cf71 100644 --- a/TUnit.Core.SourceGenerator/Helpers/InterfaceCache.cs +++ b/TUnit.Core.SourceGenerator/Helpers/InterfaceCache.cs @@ -47,14 +47,12 @@ public static bool IsAsyncEnumerable(ITypeSymbol type) { return _implementsCache.GetOrAdd((type, "System.Collections.Generic.IAsyncEnumerable"), key => { - // Check if the type itself is an IAsyncEnumerable if (key.Type is INamedTypeSymbol { IsGenericType: true } namedType && namedType.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.IAsyncEnumerable") { return true; } - // Check if the type implements IAsyncEnumerable return key.Type.AllInterfaces.Any(i => i.IsGenericType && i.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.IAsyncEnumerable"); diff --git a/TUnit.Core.SourceGenerator/Models/TestClassMetadata.cs b/TUnit.Core.SourceGenerator/Models/TestClassMetadata.cs new file mode 100644 index 0000000000..cff6f1f3ec --- /dev/null +++ b/TUnit.Core.SourceGenerator/Models/TestClassMetadata.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace TUnit.Core.SourceGenerator.Models; + +/// +/// Contains metadata about a test class and all its test methods. +/// This is used to group tests by class for more efficient file generation. +/// +public class TestClassMetadata : IEquatable +{ + public required INamedTypeSymbol TypeSymbol { get; init; } + public required ImmutableArray TestMethods { get; init; } + + public bool Equals(TestClassMetadata? other) + { + if (ReferenceEquals(null, other)) + return false; + if (ReferenceEquals(this, other)) + return true; + + // Check if the type symbol is the same + if (!SymbolEqualityComparer.Default.Equals(TypeSymbol, other.TypeSymbol)) + return false; + + // Check if test methods array length is the same + if (TestMethods.Length != other.TestMethods.Length) + return false; + + // Check each test method + for (int i = 0; i < TestMethods.Length; i++) + { + if (!TestMethods[i].Equals(other.TestMethods[i])) + return false; + } + + return true; + } + + public override bool Equals(object? obj) + { + return Equals(obj as TestClassMetadata); + } + + public override int GetHashCode() + { + unchecked + { + var hashCode = SymbolEqualityComparer.Default.GetHashCode(TypeSymbol); + + // Include test methods in hash + foreach (var testMethod in TestMethods) + { + hashCode = (hashCode * 397) ^ testMethod.GetHashCode(); + } + + return hashCode; + } + } +} diff --git a/TUnit.Core.SourceGenerator/Models/TestDefinitionContext.cs b/TUnit.Core.SourceGenerator/Models/TestDefinitionContext.cs index e97be27235..18542df551 100644 --- a/TUnit.Core.SourceGenerator/Models/TestDefinitionContext.cs +++ b/TUnit.Core.SourceGenerator/Models/TestDefinitionContext.cs @@ -39,8 +39,13 @@ public static IEnumerable CreateContexts(TestMetadataGene var testIndex = 0; - // If no attributes, create tests based on repeat count - if (!classDataAttrs.Any() && !methodDataAttrs.Any()) + // Convert to arrays once upfront for better performance (avoid repeated .Any() calls and enumeration) + var classDataArray = classDataAttrs.Count > 0 ? classDataAttrs.ToArray() : []; + var methodDataArray = methodDataAttrs.Count > 0 ? methodDataAttrs.ToArray() : []; + var hasClassData = classDataArray.Length > 0; + var hasMethodData = methodDataArray.Length > 0; + + if (!hasClassData && !hasMethodData) { for (var repeatIndex = 0; repeatIndex < repeatCount; repeatIndex++) { @@ -56,17 +61,17 @@ public static IEnumerable CreateContexts(TestMetadataGene yield break; } - // If we have class data but no method data - if (classDataAttrs.Any() && !methodDataAttrs.Any()) + if (hasClassData && !hasMethodData) { - foreach (var classAttr in classDataAttrs) + // Use array indexing instead of foreach for slightly better performance + for (var i = 0; i < classDataArray.Length; i++) { for (var repeatIndex = 0; repeatIndex < repeatCount; repeatIndex++) { yield return new TestDefinitionContext { GenerationContext = generationContext, - ClassDataAttribute = classAttr, + ClassDataAttribute = classDataArray[i], MethodDataAttribute = null, TestIndex = testIndex++, RepeatIndex = repeatIndex @@ -74,10 +79,10 @@ public static IEnumerable CreateContexts(TestMetadataGene } } } - // If we have method data but no class data - else if (!classDataAttrs.Any() && methodDataAttrs.Any()) + else if (!hasClassData && hasMethodData) { - foreach (var methodAttr in methodDataAttrs) + // Use array indexing instead of foreach for slightly better performance + for (var i = 0; i < methodDataArray.Length; i++) { for (var repeatIndex = 0; repeatIndex < repeatCount; repeatIndex++) { @@ -85,27 +90,28 @@ public static IEnumerable CreateContexts(TestMetadataGene { GenerationContext = generationContext, ClassDataAttribute = null, - MethodDataAttribute = methodAttr, + MethodDataAttribute = methodDataArray[i], TestIndex = testIndex++, RepeatIndex = repeatIndex }; } } } - // If we have both class and method data - create cartesian product + // If we have both class and method data - create cartesian product with array indexing else { - foreach (var classAttr in classDataAttrs) + // Use array indexing for cartesian product for better performance + for (var i = 0; i < classDataArray.Length; i++) { - foreach (var methodAttr in methodDataAttrs) + for (var j = 0; j < methodDataArray.Length; j++) { for (var repeatIndex = 0; repeatIndex < repeatCount; repeatIndex++) { yield return new TestDefinitionContext { GenerationContext = generationContext, - ClassDataAttribute = classAttr, - MethodDataAttribute = methodAttr, + ClassDataAttribute = classDataArray[i], + MethodDataAttribute = methodDataArray[j], TestIndex = testIndex++, RepeatIndex = repeatIndex }; diff --git a/TUnit.Core.SourceGenerator/Models/TestMetadataGenerationContext.cs b/TUnit.Core.SourceGenerator/Models/TestMetadataGenerationContext.cs index 45041f01e5..8732001c98 100644 --- a/TUnit.Core.SourceGenerator/Models/TestMetadataGenerationContext.cs +++ b/TUnit.Core.SourceGenerator/Models/TestMetadataGenerationContext.cs @@ -121,7 +121,6 @@ private static bool DetermineIfStaticTestDefinition(TestMethodMetadata testInfo) { foreach (var attr in param.GetAttributes()) { - // Check if it's a data source attribute that requires runtime resolution if (IsRuntimeDataSourceAttribute(attr, testInfo.TypeSymbol)) { return false; diff --git a/TUnit.Core.SourceGenerator/Utilities/MetadataGenerationHelper.cs b/TUnit.Core.SourceGenerator/Utilities/MetadataGenerationHelper.cs index e55fdb5a26..786d91f382 100644 --- a/TUnit.Core.SourceGenerator/Utilities/MetadataGenerationHelper.cs +++ b/TUnit.Core.SourceGenerator/Utilities/MetadataGenerationHelper.cs @@ -126,7 +126,7 @@ public static string GenerateMethodMetadata(IMethodSymbol methodSymbol, string c private static void WriteClassMetadataGetOrAdd(ICodeWriter writer, INamedTypeSymbol typeSymbol, string? parentExpression = null) { var qualifiedName = $"{typeSymbol.ContainingAssembly.Name}:{typeSymbol.GloballyQualified()}"; - writer.AppendLine($"global::TUnit.Core.ClassMetadata.GetOrAdd(\"{qualifiedName}\", () => "); + writer.AppendLine($"global::TUnit.Core.ClassMetadata.GetOrAdd(\"{qualifiedName}\", static () => "); writer.AppendLine("{"); // Manually increment indent level without calling EnsureNewLine @@ -199,7 +199,7 @@ public static string GenerateClassMetadataGetOrAdd(INamedTypeSymbol typeSymbol, { var qualifiedName = $"{typeSymbol.ContainingAssembly.Name}:{typeSymbol.GloballyQualified()}"; var writer = new CodeWriter("", includeHeader: false).SetIndentLevel(currentIndentLevel); - writer.AppendLine($"global::TUnit.Core.ClassMetadata.GetOrAdd(\"{qualifiedName}\", () => "); + writer.AppendLine($"global::TUnit.Core.ClassMetadata.GetOrAdd(\"{qualifiedName}\", static () => "); writer.AppendLine("{"); writer.Indent(); @@ -257,7 +257,7 @@ public static string GenerateClassMetadataGetOrAdd(INamedTypeSymbol typeSymbol, /// public static string GenerateAssemblyMetadataGetOrAdd(IAssemblySymbol assembly) { - return $"global::TUnit.Core.AssemblyMetadata.GetOrAdd(\"{assembly.Name}\", () => new global::TUnit.Core.AssemblyMetadata {{ Name = \"{assembly.Name}\" }})"; + return $"global::TUnit.Core.AssemblyMetadata.GetOrAdd(\"{assembly.Name}\", static () => new global::TUnit.Core.AssemblyMetadata {{ Name = \"{assembly.Name}\" }})"; } /// diff --git a/TUnit.Core/AbstractDynamicTest.cs b/TUnit.Core/AbstractDynamicTest.cs index afa495adcb..e086176bc6 100644 --- a/TUnit.Core/AbstractDynamicTest.cs +++ b/TUnit.Core/AbstractDynamicTest.cs @@ -36,15 +36,17 @@ public class DynamicDiscoveryResult : DiscoveryResult | DynamicallyAccessedMemberTypes.NonPublicFields)] public Type? TestClassType { get; set; } - /// - /// The file path where the dynamic test was created - /// public string? CreatorFilePath { get; set; } - /// - /// The line number where the dynamic test was created - /// public int? CreatorLineNumber { get; set; } + + public string? ParentTestId { get; set; } + + public Enums.TestRelationship? Relationship { get; set; } + + public Dictionary? Properties { get; set; } + + public string? DisplayName { get; set; } } public abstract class AbstractDynamicTest diff --git a/TUnit.Core/AbstractExecutableTest.cs b/TUnit.Core/AbstractExecutableTest.cs index 7a81eb40fb..a668961b3a 100644 --- a/TUnit.Core/AbstractExecutableTest.cs +++ b/TUnit.Core/AbstractExecutableTest.cs @@ -18,6 +18,11 @@ public abstract class AbstractExecutableTest public abstract Task InvokeTestAsync(object instance, CancellationToken cancellationToken); + // Cache fields for filtering performance + internal string? CachedFilterPath { get; set; } + // Using object to avoid type dependency on Microsoft.Testing.Platform.Extensions.Messages.PropertyBag + internal object? CachedPropertyBag { get; set; } + public required TestContext Context { get; diff --git a/TUnit.Core/AsyncConvert.cs b/TUnit.Core/AsyncConvert.cs index bb660a847b..4f63c36718 100644 --- a/TUnit.Core/AsyncConvert.cs +++ b/TUnit.Core/AsyncConvert.cs @@ -124,7 +124,7 @@ private static ValueTask StartAsFSharpTask(object invoke, Type type) { var startAsTaskOpenGenericMethod = (_fSharpAsyncType ??= type.Assembly.GetType("Microsoft.FSharp.Control.FSharpAsync"))! .GetRuntimeMethods() - .FirstOrDefault(m => m.Name == "StartAsTask"); + .FirstOrDefault(static m => m.Name == "StartAsTask"); if (startAsTaskOpenGenericMethod is null) { diff --git a/TUnit.Core/AsyncEvent.cs b/TUnit.Core/AsyncEvent.cs index 918504ebdc..9fbaf3fd22 100644 --- a/TUnit.Core/AsyncEvent.cs +++ b/TUnit.Core/AsyncEvent.cs @@ -1,35 +1,14 @@ -using TUnit.Core.Interfaces; +using TUnit.Core.Interfaces; namespace TUnit.Core; public class AsyncEvent { - public int Order - { - get; - set - { - field = value; - - if (InvocationList.Count > 0) - { - InvocationList[^1].Order = field; - } - } - } = int.MaxValue / 2; - - internal List InvocationList { get; } = []; - - private static readonly Lock _newEventLock = new(); - private readonly Lock _locker = new(); + private List? _handlers; public class Invocation(Func factory, int order) : IEventReceiver { - public int Order - { - get; - internal set; - } = order; + public int Order { get; } = order; public async ValueTask InvokeAsync(object sender, TEventArgs eventArgs) { @@ -37,42 +16,70 @@ public async ValueTask InvokeAsync(object sender, TEventArgs eventArgs) } } - public static AsyncEvent operator +( - AsyncEvent? e, Func callback - ) + public void Add(Func callback, int order = int.MaxValue / 2) { if (callback == null) { - throw new NullReferenceException("callback is null"); + throw new ArgumentNullException(nameof(callback)); } - lock (_newEventLock) - { - e ??= new AsyncEvent(); - } + var invocation = new Invocation(callback, order); + var insertIndex = FindInsertionIndex(order); + (_handlers ??= []).Insert(insertIndex, invocation); + } - lock (e._locker) + public void AddAt(Func callback, int index, int order = int.MaxValue / 2) + { + if (callback == null) { - e.InvocationList.Add(new Invocation(callback, e.Order)); - e.Order = int.MaxValue / 2; + throw new ArgumentNullException(nameof(callback)); } - return e; + var invocation = new Invocation(callback, order); + var handlers = _handlers ??= []; + var clampedIndex = index < 0 ? 0 : (index > handlers.Count ? handlers.Count : index); + handlers.Insert(clampedIndex, invocation); } - public AsyncEvent InsertAtFront(Func callback) + public IReadOnlyList InvocationList { - if (callback == null) + get { - throw new NullReferenceException("callback is null"); - } + if (_handlers == null) + { + return []; + } + + return _handlers; - lock (_locker) - { - InvocationList.Insert(0, new Invocation(callback, Order)); - Order = int.MaxValue / 2; } + } + public AsyncEvent InsertAtFront(Func callback) + { + AddAt(callback, 0); return this; } + + public static AsyncEvent operator +( + AsyncEvent? e, Func callback) + { + e ??= new AsyncEvent(); + e.Add(callback); + return e; + } + + private int FindInsertionIndex(int order) + { + int left = 0, right = (_handlers ??= []).Count; + while (left < right) + { + var mid = left + (right - left) / 2; + if (_handlers[mid].Order <= order) + left = mid + 1; + else + right = mid; + } + return left; + } } diff --git a/TUnit.Core/Attributes/DynamicTestBuilderAttribute.cs b/TUnit.Core/Attributes/DynamicTestBuilderAttribute.cs index be7580df9c..5592b90cad 100644 --- a/TUnit.Core/Attributes/DynamicTestBuilderAttribute.cs +++ b/TUnit.Core/Attributes/DynamicTestBuilderAttribute.cs @@ -3,5 +3,4 @@ namespace TUnit.Core; -[Experimental("TUnitWIP0001")] public class DynamicTestBuilderAttribute([CallerFilePath] string file = "", [CallerLineNumber] int line = 0) : BaseTestAttribute(file, line); diff --git a/TUnit.Core/Attributes/TestData/MatrixDataSourceAttribute.cs b/TUnit.Core/Attributes/TestData/MatrixDataSourceAttribute.cs index 1d975a8dbc..d47e351941 100644 --- a/TUnit.Core/Attributes/TestData/MatrixDataSourceAttribute.cs +++ b/TUnit.Core/Attributes/TestData/MatrixDataSourceAttribute.cs @@ -36,18 +36,19 @@ public sealed class MatrixDataSourceAttribute : UntypedDataSourceGeneratorAttrib foreach (var row in GetMatrixValues(parameterInformation.Select(p => GetAllArguments(dataGeneratorMetadata, p)))) { - if (exclusions.Any(e => IsExcluded(e, row))) + var rowArray = row.ToArray(); + + if (exclusions.Any(e => IsExcluded(e, rowArray))) { continue; } - yield return () => row.ToArray(); + yield return () => rowArray; } } - private bool IsExcluded(object?[] exclusion, IEnumerable row) + private bool IsExcluded(object?[] exclusion, object?[] rowArray) { - var rowArray = row.ToArray(); if (exclusion.Length != rowArray.Length) { return false; diff --git a/TUnit.Core/Contexts/DiscoveredTestContext.cs b/TUnit.Core/Contexts/DiscoveredTestContext.cs index 1013e6f928..4326d1a165 100644 --- a/TUnit.Core/Contexts/DiscoveredTestContext.cs +++ b/TUnit.Core/Contexts/DiscoveredTestContext.cs @@ -68,16 +68,6 @@ public void AddParallelConstraint(IParallelConstraint constraint) { TestContext.AddParallelConstraint(constraint); } - - /// - /// Sets the parallel constraint, replacing any existing constraints. - /// Maintained for backward compatibility. - /// - [Obsolete("Use AddParallelConstraint to support multiple constraints. This method replaces all existing constraints.")] - public void SetParallelConstraint(IParallelConstraint constraint) - { - TestContext.ParallelConstraint = constraint; - } public void AddArgumentDisplayFormatter(ArgumentDisplayFormatter formatter) { diff --git a/TUnit.Core/Contexts/TestRegisteredContext.cs b/TUnit.Core/Contexts/TestRegisteredContext.cs index 49fbbbdc24..7b3786ff9d 100644 --- a/TUnit.Core/Contexts/TestRegisteredContext.cs +++ b/TUnit.Core/Contexts/TestRegisteredContext.cs @@ -34,6 +34,15 @@ public void SetTestExecutor(ITestExecutor executor) DiscoveredTest.TestExecutor = executor; } + /// + /// Sets a custom hook executor that will be used for all test-level hooks (Before/After Test). + /// This allows you to wrap hook execution in custom logic (e.g., running on a specific thread). + /// + public void SetHookExecutor(IHookExecutor executor) + { + TestContext.CustomHookExecutor = executor; + } + /// /// Sets the parallel limiter for the test /// diff --git a/TUnit.Core/Data/ThreadSafeDictionary.cs b/TUnit.Core/Data/ThreadSafeDictionary.cs index 96ea003d88..66e2aaa494 100644 --- a/TUnit.Core/Data/ThreadSafeDictionary.cs +++ b/TUnit.Core/Data/ThreadSafeDictionary.cs @@ -14,7 +14,7 @@ public class ThreadSafeDictionary Keys => _innerDictionary.Keys; - public IEnumerable Values => _innerDictionary.Values.Select(lazy => lazy.Value); + public IEnumerable Values => _innerDictionary.Values.Select(static lazy => lazy.Value); public TValue GetOrAdd(TKey key, Func func) { diff --git a/TUnit.Core/DataGeneratorMetadataCreator.cs b/TUnit.Core/DataGeneratorMetadataCreator.cs index 1d86ee4f87..4dc62c5af6 100644 --- a/TUnit.Core/DataGeneratorMetadataCreator.cs +++ b/TUnit.Core/DataGeneratorMetadataCreator.cs @@ -22,7 +22,7 @@ public static DataGeneratorMetadata CreateDataGeneratorMetadata( // Filter out CancellationToken if it's the last parameter (handled by the engine) if (generatorType == DataGeneratorType.TestParameters && parametersToGenerate.Length > 0) { - var lastParam = parametersToGenerate[parametersToGenerate.Length - 1]; + var lastParam = parametersToGenerate[^1]; if (lastParam.Type == typeof(CancellationToken)) { var newArray = new ParameterMetadata[parametersToGenerate.Length - 1]; @@ -244,7 +244,7 @@ private static ParameterMetadata[] FilterOutCancellationToken(ParameterMetadata[ { if (parameters.Length > 0) { - var lastParam = parameters[parameters.Length - 1]; + var lastParam = parameters[^1]; if (lastParam.Type == typeof(CancellationToken)) { var newArray = new ParameterMetadata[parameters.Length - 1]; diff --git a/TUnit.Core/Enums/TestRelationship.cs b/TUnit.Core/Enums/TestRelationship.cs new file mode 100644 index 0000000000..e545f2af6f --- /dev/null +++ b/TUnit.Core/Enums/TestRelationship.cs @@ -0,0 +1,31 @@ +namespace TUnit.Core.Enums; + +/// +/// Defines the relationship between a test and its parent test, if any. +/// Used for tracking test hierarchies and informing the test runner about the category of relationship. +/// +public enum TestRelationship +{ + /// + /// This test is independent and has no parent. + /// + None, + + /// + /// An identical re-run of a test, typically following a failure. + /// + Retry, + + /// + /// A test case generated as part of an initial set to explore a solution space. + /// For example, the initial random inputs for a property-based test. + /// + Generated, + + /// + /// A test case derived during the execution of a parent test, often in response to its outcome. + /// This is the appropriate category for property-based testing shrink attempts, mutation testing variants, + /// and other analytical test variations created at runtime based on parent test results. + /// + Derived +} diff --git a/TUnit.Core/Extensions/TestContextExtensions.cs b/TUnit.Core/Extensions/TestContextExtensions.cs index 4361cf0f50..11f1b4b038 100644 --- a/TUnit.Core/Extensions/TestContextExtensions.cs +++ b/TUnit.Core/Extensions/TestContextExtensions.cs @@ -45,4 +45,28 @@ public static string GetClassTypeName(this TestContext context) { await context.GetService()!.AddDynamicTest(context, dynamicTest);; } + + /// + /// Creates a new test variant based on the current test's template. + /// The new test is queued for execution and will appear as a distinct test in the test explorer. + /// This is the primary mechanism for implementing property-based test shrinking and retry logic. + /// + /// The current test context + /// Method arguments for the variant (null to reuse current arguments) + /// Key-value pairs for user-defined metadata (e.g., attempt count, custom data) + /// The relationship category of this variant to its parent test (defaults to Derived) + /// Optional user-facing display name for the variant (e.g., "Shrink Attempt", "Mutant") + /// A task that completes when the variant has been queued + #if NET6_0_OR_GREATER + [RequiresUnreferencedCode("Creating test variants requires runtime compilation and reflection")] + #endif + public static async Task CreateTestVariant( + this TestContext context, + object?[]? arguments = null, + Dictionary? properties = null, + Enums.TestRelationship relationship = Enums.TestRelationship.Derived, + string? displayName = null) + { + await context.GetService()!.CreateTestVariant(context, arguments, properties, relationship, displayName); + } } diff --git a/TUnit.Core/Helpers/ArgumentFormatter.cs b/TUnit.Core/Helpers/ArgumentFormatter.cs index bcf81189d8..a0d8ac4ba0 100644 --- a/TUnit.Core/Helpers/ArgumentFormatter.cs +++ b/TUnit.Core/Helpers/ArgumentFormatter.cs @@ -25,16 +25,26 @@ public static string GetConstantValue(TestContext testContext, object? o) public static string FormatArguments(IEnumerable arguments) { - var list = arguments as IList ?? arguments.ToList(); - if (list.Count == 0) - return string.Empty; - - var formatted = new string[list.Count]; - for (int i = 0; i < list.Count; i++) + if (arguments is IList list) { - formatted[i] = FormatDefault(list[i]); + if (list.Count == 0) + return string.Empty; + + var formatted = new string[list.Count]; + for (int i = 0; i < list.Count; i++) + { + formatted[i] = FormatDefault(list[i]); + } + return string.Join(", ", formatted); } - return string.Join(", ", formatted); + + var elements = new List(); + foreach (var arg in arguments) + { + elements.Add(FormatDefault(arg)); + } + + return elements.Count == 0 ? string.Empty : string.Join(", ", elements); } private static string FormatDefault(object? o) @@ -56,7 +66,16 @@ private static string FormatDefault(object? o) return FormatEnumerable(enumerable); } - var toString = o.ToString()!; + string toString; + try + { + toString = o.ToString()!; + } + catch + { + // If ToString() throws, fall back to type name + return type.Name; + } if (o is Enum) { @@ -100,15 +119,23 @@ private static string FormatEnumerable(IEnumerable enumerable) var elements = new List(maxElements + 1); var count = 0; - foreach (var element in enumerable) + try { - if (count >= maxElements) + foreach (var element in enumerable) { - elements.Add("..."); - break; + if (count >= maxElements) + { + elements.Add("..."); + break; + } + elements.Add(FormatDefault(element)); + count++; } - elements.Add(FormatDefault(element)); - count++; + } + catch + { + // If GetEnumerator() or MoveNext() throws, fall back to type name + return enumerable.GetType().Name; } return string.Join(", ", elements); diff --git a/TUnit.Core/Helpers/AttributeDictionaryHelper.cs b/TUnit.Core/Helpers/AttributeDictionaryHelper.cs new file mode 100644 index 0000000000..c0824199f9 --- /dev/null +++ b/TUnit.Core/Helpers/AttributeDictionaryHelper.cs @@ -0,0 +1,46 @@ +using System.Collections.ObjectModel; + +namespace TUnit.Core.Helpers; + +/// +/// Helper methods for working with attribute dictionaries. +/// +public static class AttributeDictionaryHelper +{ + private static readonly IReadOnlyDictionary> EmptyDictionary = + new ReadOnlyDictionary>(new Dictionary>()); + + /// + /// Converts an array of attributes to a read-only dictionary grouped by type. + /// + public static IReadOnlyDictionary> ToAttributeDictionary(this Attribute[] attributes) + { + if (attributes.Length == 0) + { + return EmptyDictionary; + } + + var result = new Dictionary>(); + + foreach (var attr in attributes) + { + var type = attr.GetType(); + if (!result.TryGetValue(type, out var list)) + { + var newList = new List { attr }; + result[type] = newList; + } + else + { + ((List)list).Add(attr); + } + } + + return new ReadOnlyDictionary>(result); + } + + /// + /// Gets an empty read-only attribute dictionary. + /// + public static IReadOnlyDictionary> Empty => EmptyDictionary; +} diff --git a/TUnit.Core/Helpers/StringBuilderPool.cs b/TUnit.Core/Helpers/StringBuilderPool.cs new file mode 100644 index 0000000000..5974ba198a --- /dev/null +++ b/TUnit.Core/Helpers/StringBuilderPool.cs @@ -0,0 +1,40 @@ +using System.Collections.Concurrent; +using System.Text; + +namespace TUnit.Core.Helpers; + +/// +/// Provides a pool of StringBuilder instances to reduce allocations in hot paths. +/// +internal static class StringBuilderPool +{ + private const int MaxCapacity = 1024; + private static readonly ConcurrentBag Pool = []; + + /// + /// Gets a StringBuilder from the pool or creates a new one. + /// + public static StringBuilder Get() + { + if (Pool.TryTake(out var builder)) + { + return builder; + } + + return new StringBuilder(); + } + + /// + /// Returns a StringBuilder to the pool after clearing its contents. + /// + public static void Return(StringBuilder builder) + { + if (builder.Capacity > MaxCapacity) + { + return; + } + + builder.Clear(); + Pool.Add(builder); + } +} diff --git a/TUnit.Core/Hooks/AfterTestHookMethod.cs b/TUnit.Core/Hooks/AfterTestHookMethod.cs index 510ffa81bf..90ac145667 100644 --- a/TUnit.Core/Hooks/AfterTestHookMethod.cs +++ b/TUnit.Core/Hooks/AfterTestHookMethod.cs @@ -4,6 +4,16 @@ public record AfterTestHookMethod : StaticHookMethod { public override ValueTask ExecuteAsync(TestContext context, CancellationToken cancellationToken) { + // Check if a custom hook executor has been set (e.g., via SetHookExecutor()) + // This ensures static hooks respect the custom executor even in AOT/trimmed builds + if (context.CustomHookExecutor != null) + { + return context.CustomHookExecutor.ExecuteAfterTestHook(MethodInfo, context, + () => Body!.Invoke(context, cancellationToken) + ); + } + + // Use the default executor specified at hook registration time return HookExecutor.ExecuteAfterTestHook(MethodInfo, context, () => Body!.Invoke(context, cancellationToken) ); diff --git a/TUnit.Core/Hooks/BeforeTestHookMethod.cs b/TUnit.Core/Hooks/BeforeTestHookMethod.cs index eea40c6cc1..867af57b7c 100644 --- a/TUnit.Core/Hooks/BeforeTestHookMethod.cs +++ b/TUnit.Core/Hooks/BeforeTestHookMethod.cs @@ -4,6 +4,16 @@ public record BeforeTestHookMethod : StaticHookMethod { public override ValueTask ExecuteAsync(TestContext context, CancellationToken cancellationToken) { + // Check if a custom hook executor has been set (e.g., via SetHookExecutor()) + // This ensures static hooks respect the custom executor even in AOT/trimmed builds + if (context.CustomHookExecutor != null) + { + return context.CustomHookExecutor.ExecuteBeforeTestHook(MethodInfo, context, + () => Body!.Invoke(context, cancellationToken) + ); + } + + // Use the default executor specified at hook registration time return HookExecutor.ExecuteBeforeTestHook(MethodInfo, context, () => Body!.Invoke(context, cancellationToken) ); diff --git a/TUnit.Core/Interfaces/ITestRegistry.cs b/TUnit.Core/Interfaces/ITestRegistry.cs index 9dbfcd5da0..931ada871e 100644 --- a/TUnit.Core/Interfaces/ITestRegistry.cs +++ b/TUnit.Core/Interfaces/ITestRegistry.cs @@ -26,4 +26,25 @@ public interface ITestRegistry | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] T>(TestContext context, DynamicTest dynamicTest) where T : class; + + /// + /// Creates a new test variant based on the current test's template. + /// The new test is queued for execution and will appear as a distinct test in the test explorer. + /// This is the primary mechanism for implementing property-based test shrinking and retry logic. + /// + /// The current test context to base the variant on + /// Method arguments for the variant (null to reuse current arguments) + /// Key-value pairs for user-defined metadata (e.g., attempt count, custom data) + /// The relationship category of this variant to its parent test + /// Optional user-facing display name for the variant (e.g., "Shrink Attempt", "Mutant") + /// A task that completes when the variant has been queued + #if NET6_0_OR_GREATER + [RequiresUnreferencedCode("Creating test variants requires runtime compilation and reflection which are not supported in native AOT scenarios.")] + #endif + Task CreateTestVariant( + TestContext currentContext, + object?[]? arguments, + Dictionary? properties, + Enums.TestRelationship relationship, + string? displayName); } diff --git a/TUnit.Core/TUnit.Core.csproj b/TUnit.Core/TUnit.Core.csproj index 6df09d2573..56f619768d 100644 --- a/TUnit.Core/TUnit.Core.csproj +++ b/TUnit.Core/TUnit.Core.csproj @@ -63,6 +63,7 @@ + diff --git a/TUnit.Core/TestContext.cs b/TUnit.Core/TestContext.cs index e585327cb0..4259e7d077 100644 --- a/TUnit.Core/TestContext.cs +++ b/TUnit.Core/TestContext.cs @@ -37,9 +37,9 @@ public TestContext(string testName, IServiceProvider serviceProvider, ClassHookC internal static readonly Dictionary> InternalParametersDictionary = new(); - private readonly StringWriter _outputWriter = new(); + private StringWriter? _outputWriter; - private readonly StringWriter _errorWriter = new(); + private StringWriter? _errorWriter; public static new TestContext? Current { @@ -103,6 +103,12 @@ public static string WorkingDirectory public Type? DisplayNameFormatter { get; set; } + /// + /// Custom hook executor that overrides the default hook executor for all test-level hooks. + /// Set via TestRegisteredContext.SetHookExecutor() during test registration. + /// + public IHookExecutor? CustomHookExecutor { get; set; } + public Func>? RetryFunc { get; set; } // New: Support multiple parallel constraints @@ -114,25 +120,6 @@ public static string WorkingDirectory /// public IReadOnlyList ParallelConstraints => _parallelConstraints; - /// - /// Gets or sets the primary parallel constraint for backward compatibility. - /// When setting, this replaces all existing constraints. - /// When getting, returns the first constraint or null if none exist. - /// - [Obsolete("Use ParallelConstraints collection instead. This property is maintained for backward compatibility.")] - public IParallelConstraint? ParallelConstraint - { - get => _parallelConstraints.FirstOrDefault(); - set - { - _parallelConstraints.Clear(); - if (value != null) - { - _parallelConstraints.Add(value); - } - } - } - /// /// Adds a parallel constraint to this test context. /// Multiple constraints can be combined to create complex parallelization rules. @@ -147,6 +134,18 @@ public void AddParallelConstraint(IParallelConstraint constraint) public Priority ExecutionPriority { get; set; } = Priority.Normal; + /// + /// The test ID of the parent test, if this test is a variant or child of another test. + /// Used for tracking test hierarchies in property-based testing shrinking and retry scenarios. + /// + public string? ParentTestId { get; set; } + + /// + /// Defines the relationship between this test and its parent test (if ParentTestId is set). + /// Used by test explorers to display hierarchical relationships. + /// + public TestRelationship Relationship { get; set; } = TestRelationship.None; + /// /// Will be null until initialized by TestOrchestrator /// @@ -169,17 +168,19 @@ internal IServiceProvider ServiceProvider public void WriteLine(string message) { + _outputWriter ??= new StringWriter(); _outputWriter.WriteLine(message); } public void WriteError(string message) { + _errorWriter ??= new StringWriter(); _errorWriter.WriteLine(message); } - public string GetOutput() => _outputWriter.ToString(); + public string GetOutput() => _outputWriter?.ToString() ?? string.Empty; - public new string GetErrorOutput() => _errorWriter.ToString(); + public new string GetErrorOutput() => _errorWriter?.ToString() ?? string.Empty; public T? GetService() where T : class { @@ -201,6 +202,8 @@ internal override void SetAsyncLocalContext() internal IClassConstructor? ClassConstructor => _testBuilderContext.ClassConstructor; + internal object[]? CachedEligibleEventObjects { get; set; } + public string GetDisplayName() { if(!string.IsNullOrEmpty(CustomDisplayName)) @@ -219,21 +222,39 @@ public string GetDisplayName() return TestName; } - var formattedArgs = new string[TestDetails.TestMethodArguments.Length]; - for (var i = 0; i < TestDetails.TestMethodArguments.Length; i++) + var argsLength = TestDetails.TestMethodArguments.Length; + var sb = StringBuilderPool.Get(); + try { - formattedArgs[i] = ArgumentFormatter.Format(TestDetails.TestMethodArguments[i], ArgumentDisplayFormatters); - } - var arguments = string.Join(", ", formattedArgs); + sb.Append(TestName); + sb.Append('('); - if (string.IsNullOrEmpty(arguments)) + for (var i = 0; i < argsLength; i++) + { + if (i > 0) + { + sb.Append(", "); + } + sb.Append(ArgumentFormatter.Format(TestDetails.TestMethodArguments[i], ArgumentDisplayFormatters)); + } + + sb.Append(')'); + _cachedDisplayName = sb.ToString(); + return _cachedDisplayName; + } + finally { - _cachedDisplayName = TestName; - return TestName; + StringBuilderPool.Return(sb); } + } - _cachedDisplayName = $"{TestName}({arguments})"; - return _cachedDisplayName; + /// + /// Clears the cached display name, forcing it to be recomputed on next access. + /// This is called after discovery event receivers run to ensure custom argument formatters are applied. + /// + internal void InvalidateDisplayNameCache() + { + _cachedDisplayName = null; } public Dictionary ObjectBag => _testBuilderContext.ObjectBag; @@ -293,33 +314,6 @@ public void OverrideResult(TestState state, string reason) InternalExecutableTest.State = state; } - /// - /// Reregisters a test with new arguments. This method is currently non-functional as the underlying - /// ITestFinder interface has been removed. This functionality may be reimplemented in a future version. - /// - /// - /// Previously used for dynamically modifying test arguments at runtime. Consider using data source - /// attributes for parameterized tests instead. - /// - [Obsolete("This method is non-functional after the removal of ITestFinder. It will be removed in a future version.")] - public async Task ReregisterTestWithArguments(object?[]? methodArguments = null, Dictionary? objectBag = null) - { - if (methodArguments != null) - { - TestDetails.TestMethodArguments = methodArguments; - } - - if (objectBag != null) - { - foreach (var kvp in objectBag) - { - ObjectBag[kvp.Key] = kvp.Value; - } - } - - // This method is currently non-functional - see Obsolete attribute above - await Task.CompletedTask; - } public List Dependencies { get; } = [ @@ -356,7 +350,6 @@ public List GetTests(string testName) // Use the current test's class type by default var classType = TestDetails.ClassType; - // Call GetTestsByNameAndParameters with empty parameter lists to get all tests with this name var tests = testFinder.GetTestsByNameAndParameters( testName, [ @@ -382,7 +375,6 @@ public List GetTests(string testName, Type classType) { var testFinder = ServiceProvider.GetService()!; - // Call GetTestsByNameAndParameters with empty parameter lists to get all tests with this name return testFinder.GetTestsByNameAndParameters( testName, [ diff --git a/TUnit.Core/TestDetails.cs b/TUnit.Core/TestDetails.cs index 801ba823ef..e1dbed6705 100644 --- a/TUnit.Core/TestDetails.cs +++ b/TUnit.Core/TestDetails.cs @@ -29,15 +29,56 @@ public class TestDetails public Dictionary> CustomProperties { get; } = new(); public Type[]? TestClassParameterTypes { get; set; } - public required IReadOnlyList Attributes { get; init; } + public required IReadOnlyDictionary> AttributesByType { get; init; } + + private readonly Lazy> _cachedAllAttributes; + + public TestDetails() + { + _cachedAllAttributes = new Lazy>(() => + { + var allAttrs = new List(); + foreach (var attrList in AttributesByType?.Values ?? []) + { + allAttrs.AddRange(attrList); + } + return allAttrs; + }); + } + + /// + /// Checks if the test has an attribute of the specified type. + /// + /// The attribute type to check for. + /// True if the test has at least one attribute of the specified type; otherwise, false. + public bool HasAttribute() where T : Attribute + => AttributesByType.ContainsKey(typeof(T)); + + /// + /// Gets all attributes of the specified type. + /// + /// The attribute type to retrieve. + /// An enumerable of attributes of the specified type. + public IEnumerable GetAttributes() where T : Attribute + => AttributesByType.TryGetValue(typeof(T), out var attrs) + ? attrs.OfType() + : []; + + /// + /// Gets all attributes as a flattened collection. + /// Cached after first access for performance. + /// + /// All attributes associated with this test. + public IReadOnlyList GetAllAttributes() => _cachedAllAttributes.Value; + public object?[] ClassMetadataArguments => TestClassArguments; - + /// /// Resolved generic type arguments for the test method. /// Will be Type.EmptyTypes if the method is not generic. /// public Type[] MethodGenericArguments { get; set; } = Type.EmptyTypes; - + /// /// Resolved generic type arguments for the test class. /// Will be Type.EmptyTypes if the class is not generic. diff --git a/TUnit.Core/TestMetadata.cs b/TUnit.Core/TestMetadata.cs index 9757ae0fb9..49cb6279ed 100644 --- a/TUnit.Core/TestMetadata.cs +++ b/TUnit.Core/TestMetadata.cs @@ -49,6 +49,13 @@ public abstract class TestMetadata public required Func AttributeFactory { get; init; } + /// + /// Pre-extracted repeat count from RepeatAttribute. + /// Null if no repeat attribute is present (defaults to 0 at usage site). + /// Pre-extracting this avoids instantiating all attributes just to read the repeat count. + /// + public int? RepeatCount { get; init; } + public PropertyInjectionData[] PropertyInjections { get; init; } = []; /// diff --git a/TUnit.Core/TestMetadata`1.cs b/TUnit.Core/TestMetadata`1.cs index e62943aaa0..c29cc86c20 100644 --- a/TUnit.Core/TestMetadata`1.cs +++ b/TUnit.Core/TestMetadata`1.cs @@ -52,7 +52,7 @@ public class TestMetadata< /// Strongly typed test invoker with CancellationToken support. /// Used by source generation mode. /// - public Func? InvokeTypedTest { get; init; } + public Func? InvokeTypedTest { get; init; } @@ -97,7 +97,7 @@ public override Func invokeTest = async (instance, args, testContext, cancellationToken) => { - await typedMetadata.InvokeTypedTest!((T)instance, args, cancellationToken); + await typedMetadata.InvokeTypedTest!((T)instance, args, cancellationToken).ConfigureAwait(false); }; return new ExecutableTest(createInstance, invokeTest) diff --git a/TUnit.Engine.Tests/DynamicTests.cs b/TUnit.Engine.Tests/DynamicTests.cs index 669372faa5..2260ea9a3d 100644 --- a/TUnit.Engine.Tests/DynamicTests.cs +++ b/TUnit.Engine.Tests/DynamicTests.cs @@ -12,8 +12,8 @@ await RunTestsWithFilter( "/*/*DynamicTests/*/*", [ result => result.ResultSummary.Outcome.ShouldBe("Completed"), - result => result.ResultSummary.Counters.Total.ShouldBeGreaterThanOrEqualTo(48), - result => result.ResultSummary.Counters.Passed.ShouldBeGreaterThanOrEqualTo(48), + result => result.ResultSummary.Counters.Total.ShouldBeGreaterThanOrEqualTo(13), + result => result.ResultSummary.Counters.Passed.ShouldBeGreaterThanOrEqualTo(13), result => result.ResultSummary.Counters.Failed.ShouldBe(0), result => result.ResultSummary.Counters.NotExecuted.ShouldBe(0) ]); diff --git a/TUnit.Engine.Tests/ExplicitTests.cs b/TUnit.Engine.Tests/ExplicitTests.cs index 497cd90c54..4010602baa 100644 --- a/TUnit.Engine.Tests/ExplicitTests.cs +++ b/TUnit.Engine.Tests/ExplicitTests.cs @@ -68,6 +68,4 @@ await RunTestsWithFilter( ]); } - - -} \ No newline at end of file +} diff --git a/TUnit.Engine/Building/Interfaces/ITestBuilder.cs b/TUnit.Engine/Building/Interfaces/ITestBuilder.cs index e2066eadff..c50bda428e 100644 --- a/TUnit.Engine/Building/Interfaces/ITestBuilder.cs +++ b/TUnit.Engine/Building/Interfaces/ITestBuilder.cs @@ -22,11 +22,12 @@ internal interface ITestBuilder /// This is the main method that replaces the old DataSourceExpander approach. /// /// The test metadata with DataCombinationGenerator + /// Context for optimizing test building (e.g., pre-filtering during execution) /// Collection of executable tests for all data combinations #if NET6_0_OR_GREATER [RequiresUnreferencedCode("Test building in reflection mode uses generic type resolution which requires unreferenced code")] #endif - Task> BuildTestsFromMetadataAsync(TestMetadata metadata); + Task> BuildTestsFromMetadataAsync(TestMetadata metadata, TestBuildingContext buildingContext); /// /// Streaming version that yields tests as they're built without buffering diff --git a/TUnit.Engine/Building/TestBuilder.cs b/TUnit.Engine/Building/TestBuilder.cs index 133dff646a..f5594e870d 100644 --- a/TUnit.Engine/Building/TestBuilder.cs +++ b/TUnit.Engine/Building/TestBuilder.cs @@ -1,4 +1,6 @@ using System.Diagnostics.CodeAnalysis; +using Microsoft.Testing.Platform.Extensions.Messages; +using Microsoft.Testing.Platform.Requests; using TUnit.Core; using TUnit.Core.Enums; using TUnit.Core.Exceptions; @@ -6,6 +8,7 @@ using TUnit.Core.Interfaces; using TUnit.Core.Services; using TUnit.Engine.Building.Interfaces; +using TUnit.Engine.Extensions; using TUnit.Engine.Helpers; using TUnit.Engine.Services; using TUnit.Engine.Utilities; @@ -20,6 +23,7 @@ internal sealed class TestBuilder : ITestBuilder private readonly PropertyInjectionService _propertyInjectionService; private readonly DataSourceInitializer _dataSourceInitializer; private readonly Discovery.IHookDiscoveryService _hookDiscoveryService; + private readonly TestArgumentRegistrationService _testArgumentRegistrationService; public TestBuilder( string sessionId, @@ -27,7 +31,8 @@ public TestBuilder( IContextProvider contextProvider, PropertyInjectionService propertyInjectionService, DataSourceInitializer dataSourceInitializer, - Discovery.IHookDiscoveryService hookDiscoveryService) + Discovery.IHookDiscoveryService hookDiscoveryService, + TestArgumentRegistrationService testArgumentRegistrationService) { _sessionId = sessionId; _hookDiscoveryService = hookDiscoveryService; @@ -35,6 +40,7 @@ public TestBuilder( _contextProvider = contextProvider; _propertyInjectionService = propertyInjectionService; _dataSourceInitializer = dataSourceInitializer; + _testArgumentRegistrationService = testArgumentRegistrationService; } /// @@ -110,8 +116,18 @@ private async Task CreateInstance(TestMetadata metadata, Type[] resolved #if NET6_0_OR_GREATER [RequiresUnreferencedCode("Test building in reflection mode uses generic type resolution which requires unreferenced code")] #endif - public async Task> BuildTestsFromMetadataAsync(TestMetadata metadata) + public async Task> BuildTestsFromMetadataAsync(TestMetadata metadata, TestBuildingContext buildingContext) { + // OPTIMIZATION: Pre-filter in execution mode to skip building tests that cannot match the filter + if (buildingContext.IsForExecution && buildingContext.Filter != null) + { + if (!CouldTestMatchFilter(buildingContext.Filter, metadata)) + { + // This test class cannot match the filter - skip all expensive work! + return []; + } + } + var tests = new List(); try @@ -122,18 +138,18 @@ public async Task> BuildTestsFromMetadataAsy // Build tests from each concrete instantiation foreach (var concreteMetadata in genericMetadata.ConcreteInstantiations.Values) { - var concreteTests = await BuildTestsFromMetadataAsync(concreteMetadata); + var concreteTests = await BuildTestsFromMetadataAsync(concreteMetadata, buildingContext); tests.AddRange(concreteTests); } return tests; } + // Use pre-extracted repeat count from metadata (avoids instantiating attributes) + var repeatCount = metadata.RepeatCount ?? 0; + // Create and initialize attributes ONCE var attributes = await InitializeAttributesAsync(metadata.AttributeFactory.Invoke()); - var filteredAttributes = ScopedAttributeFilter.FilterScopedAttributes(attributes); - var repeatAttr = filteredAttributes.OfType().FirstOrDefault(); - var repeatCount = repeatAttr?.Times ?? 0; if (metadata.ClassDataSources.Any(ds => ds is IAccessesInstanceData)) { @@ -764,8 +780,8 @@ public async Task BuildTestAsync(TestMetadata metadata, // Arguments will be tracked by TestArgumentTrackingService during TestRegistered event // This ensures proper reference counting for shared instances - await InvokeDiscoveryEventReceiversAsync(context); - + // Create the test object BEFORE invoking event receivers + // This ensures context.InternalExecutableTest is set for error handling in registration var creationContext = new ExecutableTestCreationContext { TestId = testId, @@ -778,7 +794,32 @@ public async Task BuildTestAsync(TestMetadata metadata, ResolvedClassGenericArguments = testData.ResolvedClassGenericArguments }; - return metadata.CreateExecutableTestFactory(creationContext, metadata); + var test = metadata.CreateExecutableTestFactory(creationContext, metadata); + + // Set InternalExecutableTest so it's available during registration for error handling + context.InternalExecutableTest = test; + + // Invoke test registered event receivers BEFORE discovery event receivers + // This is critical for allowing attributes to set custom hook executors + try + { + await InvokeTestRegisteredEventReceiversAsync(context); + } + catch (Exception ex) + { + // Property registration or other registration logic failed + // Mark the test as failed immediately, as the old code did + test.SetResult(TestState.Failed, ex); + } + + await InvokeDiscoveryEventReceiversAsync(context); + + // Clear the cached display name after discovery events + // This ensures that ArgumentDisplayFormatterAttribute and similar attributes + // have a chance to register their formatters before the display name is finalized + context.InvalidateDisplayNameCache(); + + return test; } /// @@ -789,16 +830,15 @@ public async Task BuildTestAsync(TestMetadata metadata, private static string? GetBasicSkipReason(TestMetadata metadata, Attribute[]? cachedAttributes = null) { var attributes = cachedAttributes ?? metadata.AttributeFactory(); - var skipAttributes = attributes.OfType().ToList(); + var skipAttributes = attributes.OfType(); - if (skipAttributes.Count == 0) - { - return null; // No skip attributes - } + SkipAttribute? firstSkipAttribute = null; // Check if all skip attributes are basic (non-derived) SkipAttribute instances foreach (var skipAttribute in skipAttributes) { + firstSkipAttribute ??= skipAttribute; + var attributeType = skipAttribute.GetType(); if (attributeType != typeof(SkipAttribute)) { @@ -808,8 +848,8 @@ public async Task BuildTestAsync(TestMetadata metadata, } // All skip attributes are basic SkipAttribute instances - // Return the first reason (they all should skip) - return skipAttributes[0].Reason; + // Return the first reason (they all should skip), or null if no skip attributes + return firstSkipAttribute?.Reason; } @@ -836,7 +876,7 @@ private async ValueTask CreateTestContextAsync(string testId, TestM TestLineNumber = metadata.LineNumber, ReturnType = metadata.MethodMetadata.ReturnType ?? typeof(void), MethodMetadata = metadata.MethodMetadata, - Attributes = attributes, + AttributesByType = attributes.ToAttributeDictionary(), MethodGenericArguments = testData.ResolvedMethodGenericArguments, ClassGenericArguments = testData.ResolvedClassGenericArguments, Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout (can be overridden by TimeoutAttribute) @@ -854,6 +894,37 @@ private async ValueTask CreateTestContextAsync(string testId, TestM return context; } +#if NET6_0_OR_GREATER + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Type comes from runtime objects that cannot be annotated")] +#endif + private async Task InvokeTestRegisteredEventReceiversAsync(TestContext context) + { + var discoveredTest = new DiscoveredTest + { + TestContext = context + }; + + var registeredContext = new TestRegisteredContext(context) + { + DiscoveredTest = discoveredTest + }; + + context.InternalDiscoveredTest = discoveredTest; + + // First, invoke the global test argument registration service to register shared instances + await _testArgumentRegistrationService.OnTestRegistered(registeredContext); + + var eventObjects = context.GetEligibleEventObjects(); + + foreach (var receiver in eventObjects.OfType()) + { + await receiver.OnTestRegistered(registeredContext); + } + } + +#if NET6_0_OR_GREATER + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Scoped attribute filtering uses Type.GetInterfaces and reflection")] +#endif private async Task InvokeDiscoveryEventReceiversAsync(TestContext context) { var discoveredContext = new DiscoveredTestContext( @@ -877,8 +948,6 @@ private async Task CreateFailedTestForDataGenerationErro var testDetails = await CreateFailedTestDetails(metadata, testId); var context = CreateFailedTestContext(metadata, testDetails); - await InvokeDiscoveryEventReceiversAsync(context); - return new FailedExecutableTest(exception) { TestId = testId, @@ -904,7 +973,7 @@ private async Task CreateFailedTestDetails(TestMetadata metadata, s TestLineNumber = metadata.LineNumber, ReturnType = typeof(Task), MethodMetadata = metadata.MethodMetadata, - Attributes = await InitializeAttributesAsync(metadata.AttributeFactory.Invoke()), + AttributesByType = (await InitializeAttributesAsync(metadata.AttributeFactory.Invoke())).ToAttributeDictionary(), Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout (can be overridden by TimeoutAttribute) }; } @@ -1208,11 +1277,11 @@ public async IAsyncEnumerable BuildTestsStreamingAsync( yield break; } - // Extract repeat count from attributes + // Use pre-extracted repeat count from metadata (avoids instantiating attributes) + var repeatCount = metadata.RepeatCount ?? 0; + + // Initialize attributes var attributes = await InitializeAttributesAsync(metadata.AttributeFactory.Invoke()); - var filteredAttributes = ScopedAttributeFilter.FilterScopedAttributes(attributes); - var repeatAttr = filteredAttributes.OfType().FirstOrDefault(); - var repeatCount = repeatAttr?.Times ?? 0; // Create base context with ClassConstructor if present var baseContext = new TestBuilderContext @@ -1448,7 +1517,7 @@ public async IAsyncEnumerable BuildTestsStreamingAsync( } // Create instance factory - var attributes = contextAccessor.Current.InitializedAttributes ?? Array.Empty(); + var attributes = contextAccessor.Current.InitializedAttributes ?? []; var basicSkipReason = GetBasicSkipReason(metadata, attributes); Func> instanceFactory; @@ -1506,4 +1575,111 @@ public async IAsyncEnumerable BuildTestsStreamingAsync( return await CreateFailedTestForDataGenerationError(metadata, ex); } } + + /// + /// Determines if a test could potentially match the filter without building the full test object. + /// This is a conservative check - returns true unless we can definitively rule out the test. + /// + private bool CouldTestMatchFilter(ITestExecutionFilter filter, TestMetadata metadata) + { +#pragma warning disable TPEXP + return filter switch + { + null => true, + NopFilter => true, + TreeNodeFilter treeFilter => CouldMatchTreeNodeFilter(treeFilter, metadata), + TestNodeUidListFilter uidFilter => CouldMatchUidFilter(uidFilter, metadata), + _ => true // Unknown filter type - be conservative + }; +#pragma warning restore TPEXP + } + + /// + /// Checks if a test could match a TestNodeUidListFilter by checking if any UID contains + /// the namespace, class name, and method name. + /// + private static bool CouldMatchUidFilter(TestNodeUidListFilter filter, TestMetadata metadata) + { + var classMetadata = metadata.MethodMetadata.Class; + var namespaceName = classMetadata.Namespace ?? ""; + var className = metadata.TestClassType.Name; + var methodName = metadata.TestMethodName; + + // Check if any UID in the filter contains all three components + foreach (var uid in filter.TestNodeUids) + { + var uidValue = uid.Value; + if (uidValue.Contains(namespaceName) && + uidValue.Contains(className) && + uidValue.Contains(methodName)) + { + return true; + } + } + + return false; + } + + /// + /// Checks if a test could match a TreeNodeFilter by building the test path and checking the filter. + /// +#pragma warning disable TPEXP + private bool CouldMatchTreeNodeFilter(TreeNodeFilter filter, TestMetadata metadata) + { + var filterString = filter.Filter; + + // No filter means match all + if (string.IsNullOrEmpty(filterString)) + { + return true; + } + + // If the filter contains property conditions, strip them for path-only matching + // Property conditions will be evaluated in the second pass after tests are fully built + TreeNodeFilter pathOnlyFilter; + if (filterString.Contains('[')) + { + // Strip all property conditions: [key=value] + // Use regex to remove all [...] blocks + var strippedFilterString = System.Text.RegularExpressions.Regex.Replace(filterString, @"\[([^\]]*)\]", ""); + + // Create a new TreeNodeFilter with the stripped filter string using reflection + pathOnlyFilter = CreateTreeNodeFilterViaReflection(strippedFilterString); + } + else + { + pathOnlyFilter = filter; + } + + var path = BuildPathFromMetadata(metadata); + var emptyPropertyBag = new PropertyBag(); + return pathOnlyFilter.MatchesFilter(path, emptyPropertyBag); + } + + /// + /// Creates a TreeNodeFilter instance via reflection since it doesn't have a public constructor. + /// + private static TreeNodeFilter CreateTreeNodeFilterViaReflection(string filterString) + { + var constructor = typeof(TreeNodeFilter).GetConstructors( + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0]; + + return (TreeNodeFilter)constructor.Invoke([filterString]); + } +#pragma warning restore TPEXP + + /// + /// Builds the test path from metadata, matching the format used by TestFilterService. + /// Path format: /AssemblyName/Namespace/ClassName/MethodName + /// + private static string BuildPathFromMetadata(TestMetadata metadata) + { + var classMetadata = metadata.MethodMetadata.Class; + var assemblyName = classMetadata.Assembly.Name ?? metadata.TestClassType.Assembly.GetName().Name ?? "*"; + var namespaceName = classMetadata.Namespace ?? "*"; + var className = classMetadata.Name; + var methodName = metadata.TestMethodName; + + return $"/{assemblyName}/{namespaceName}/{className}/{methodName}"; + } } diff --git a/TUnit.Engine/Building/TestBuilderPipeline.cs b/TUnit.Engine/Building/TestBuilderPipeline.cs index 1ccb75146d..021e0357e5 100644 --- a/TUnit.Engine/Building/TestBuilderPipeline.cs +++ b/TUnit.Engine/Building/TestBuilderPipeline.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using EnumerableAsyncProcessor.Extensions; using TUnit.Core; +using TUnit.Core.Helpers; using TUnit.Core.Interfaces; using TUnit.Core.Services; using TUnit.Engine.Building.Interfaces; @@ -61,7 +62,9 @@ public async Task> BuildTestsAsync(string te { var collectedMetadata = await _dataCollector.CollectTestsAsync(testSessionId).ConfigureAwait(false); - return await BuildTestsFromMetadataAsync(collectedMetadata).ConfigureAwait(false); + // For this method (non-streaming), we're not in execution mode so no filter optimization + var buildingContext = new TestBuildingContext(IsForExecution: false, Filter: null); + return await BuildTestsFromMetadataAsync(collectedMetadata, buildingContext).ConfigureAwait(false); } /// @@ -71,6 +74,7 @@ public async Task> BuildTestsAsync(string te [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "Reflection mode is not used in AOT scenarios")] public async Task> BuildTestsStreamingAsync( string testSessionId, + TestBuildingContext buildingContext, CancellationToken cancellationToken = default) { // Get metadata streaming if supported @@ -78,7 +82,7 @@ public async Task> BuildTestsStreamingAsync( var collectedMetadata = await _dataCollector.CollectTestsAsync(testSessionId).ConfigureAwait(false); return await collectedMetadata - .SelectManyAsync(BuildTestsFromSingleMetadataAsync, cancellationToken: cancellationToken) + .SelectManyAsync(metadata => BuildTestsFromSingleMetadataAsync(metadata, buildingContext), cancellationToken: cancellationToken) .ProcessInParallel(cancellationToken: cancellationToken); } @@ -93,7 +97,7 @@ private async IAsyncEnumerable ToAsyncEnumerable(IEnumerable> BuildTestsFromMetadataAsync(IEnumerable testMetadata) + public async Task> BuildTestsFromMetadataAsync(IEnumerable testMetadata, TestBuildingContext buildingContext) { var testGroups = await testMetadata.SelectAsync(async metadata => { @@ -105,7 +109,7 @@ public async Task> BuildTestsFromMetadataAsy return await GenerateDynamicTests(metadata).ConfigureAwait(false); } - return await _testBuilder.BuildTestsFromMetadataAsync(metadata).ConfigureAwait(false); + return await _testBuilder.BuildTestsFromMetadataAsync(metadata, buildingContext).ConfigureAwait(false); } catch (Exception ex) { @@ -120,13 +124,8 @@ public async Task> BuildTestsFromMetadataAsy private async Task GenerateDynamicTests(TestMetadata metadata) { - // Get attributes first - var attributes = metadata.AttributeFactory() ?? []; - - // Extract repeat count from attributes - var filteredAttributes = ScopedAttributeFilter.FilterScopedAttributes(attributes); - var repeatAttr = filteredAttributes.OfType().FirstOrDefault(); - var repeatCount = repeatAttr?.Times ?? 0; + // Use pre-extracted repeat count from metadata (avoids instantiating attributes) + var repeatCount = metadata.RepeatCount ?? 0; return await Enumerable.Range(0, repeatCount + 1) .SelectAsync(async repeatIndex => @@ -170,7 +169,7 @@ private async Task GenerateDynamicTests(TestMetadata m TestLineNumber = metadata.LineNumber, ReturnType = typeof(Task), MethodMetadata = metadata.MethodMetadata, - Attributes = attributes, + AttributesByType = attributes.ToAttributeDictionary(), Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout (can be overridden by TimeoutAttribute) // Don't set RetryLimit here - let discovery event receivers set it }; @@ -210,7 +209,7 @@ private async Task GenerateDynamicTests(TestMetadata m #if NET6_0_OR_GREATER [RequiresUnreferencedCode("Test building in reflection mode uses generic type resolution which requires unreferenced code")] #endif - private async IAsyncEnumerable BuildTestsFromSingleMetadataAsync(TestMetadata metadata) + private async IAsyncEnumerable BuildTestsFromSingleMetadataAsync(TestMetadata metadata, TestBuildingContext buildingContext) { TestMetadata resolvedMetadata; Exception? resolutionError = null; @@ -243,13 +242,11 @@ private async IAsyncEnumerable BuildTestsFromSingleMetad [ ]; - // Get attributes first - var attributes = resolvedMetadata.AttributeFactory?.Invoke() ?? []; + // Use pre-extracted repeat count from metadata (avoids instantiating attributes) + var repeatCount = resolvedMetadata.RepeatCount ?? 0; - // Extract repeat count from attributes - var filteredAttributes = ScopedAttributeFilter.FilterScopedAttributes(attributes); - var repeatAttr = filteredAttributes.OfType().FirstOrDefault(); - var repeatCount = repeatAttr?.Times ?? 0; + // Get attributes for test details + var attributes = resolvedMetadata.AttributeFactory?.Invoke() ?? []; // Dynamic tests need to honor attributes like RepeatCount, RetryCount, etc. // We'll create multiple test instances based on RepeatCount @@ -290,7 +287,7 @@ private async IAsyncEnumerable BuildTestsFromSingleMetad TestLineNumber = resolvedMetadata.LineNumber, ReturnType = typeof(Task), MethodMetadata = resolvedMetadata.MethodMetadata, - Attributes = attributes, + AttributesByType = attributes.ToAttributeDictionary(), Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout (can be overridden by TimeoutAttribute) // Don't set Timeout and RetryLimit here - let discovery event receivers set them }; @@ -324,7 +321,7 @@ private async IAsyncEnumerable BuildTestsFromSingleMetad else { // Normal test metadata goes through the standard test builder - var testsFromMetadata = await _testBuilder.BuildTestsFromMetadataAsync(resolvedMetadata).ConfigureAwait(false); + var testsFromMetadata = await _testBuilder.BuildTestsFromMetadataAsync(resolvedMetadata, buildingContext).ConfigureAwait(false); testsToYield = new List(testsFromMetadata); } } @@ -364,7 +361,7 @@ private AbstractExecutableTest CreateFailedTestForDataGenerationError(TestMetada TestLineNumber = metadata.LineNumber, ReturnType = typeof(Task), MethodMetadata = metadata.MethodMetadata, - Attributes = [], + AttributesByType = AttributeDictionaryHelper.Empty, Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout }; @@ -416,7 +413,7 @@ private AbstractExecutableTest CreateFailedTestForGenericResolutionError(TestMet TestLineNumber = metadata.LineNumber, ReturnType = typeof(Task), MethodMetadata = metadata.MethodMetadata, - Attributes = [], + AttributesByType = AttributeDictionaryHelper.Empty, Timeout = TimeSpan.FromMinutes(30) // Default 30-minute timeout }; diff --git a/TUnit.Engine/Building/TestBuildingContext.cs b/TUnit.Engine/Building/TestBuildingContext.cs new file mode 100644 index 0000000000..b48669f9af --- /dev/null +++ b/TUnit.Engine/Building/TestBuildingContext.cs @@ -0,0 +1,19 @@ +using Microsoft.Testing.Platform.Requests; + +namespace TUnit.Engine.Building; + +/// +/// Context information for building tests, used to optimize test discovery and execution. +/// +internal record TestBuildingContext( + /// + /// Indicates whether tests are being built for execution (true) or discovery/display (false). + /// When true, optimizations like early filtering can be applied. + /// + bool IsForExecution, + + /// + /// The filter to apply during test building. Only relevant when IsForExecution is true. + /// + ITestExecutionFilter? Filter +); diff --git a/TUnit.Engine/Capabilities/StopExecutionCapability.cs b/TUnit.Engine/Capabilities/StopExecutionCapability.cs index 31c328d400..5aafe6c172 100644 --- a/TUnit.Engine/Capabilities/StopExecutionCapability.cs +++ b/TUnit.Engine/Capabilities/StopExecutionCapability.cs @@ -15,7 +15,7 @@ public async Task StopTestExecutionAsync(CancellationToken cancellationToken) if (OnStopRequested != null) { - foreach (var invocation in OnStopRequested.InvocationList.OrderBy(x => x.Order)) + foreach (var invocation in OnStopRequested.InvocationList) { await invocation.InvokeAsync(this, EventArgs.Empty); } diff --git a/TUnit.Engine/ConcurrentHashSet.cs b/TUnit.Engine/ConcurrentHashSet.cs index 85df4becb8..a45c787962 100644 --- a/TUnit.Engine/ConcurrentHashSet.cs +++ b/TUnit.Engine/ConcurrentHashSet.cs @@ -1,122 +1,34 @@ -namespace TUnit.Engine; +using System.Collections.Concurrent; -internal class ConcurrentHashSet -{ - private readonly ReaderWriterLockSlim _lock = new(LockRecursionPolicy.SupportsRecursion); - private readonly HashSet _hashSet = []; +namespace TUnit.Engine; - #region Implementation of ICollection ...ish +/// +/// Thread-safe hash set implementation using ConcurrentDictionary for better performance. +/// Provides lock-free reads and fine-grained locking for writes. +/// +internal class ConcurrentHashSet where T : notnull +{ + private readonly ConcurrentDictionary _dictionary = new(); public bool Add(T item) { - _lock.EnterWriteLock(); - - try - { - return _hashSet.Add(item); - } - finally - { - if (_lock.IsWriteLockHeld) - { - _lock.ExitWriteLock(); - } - } + return _dictionary.TryAdd(item, 0); } public void Clear() { - _lock.EnterWriteLock(); - - try - { - _hashSet.Clear(); - } - finally - { - if (_lock.IsWriteLockHeld) - { - _lock.ExitWriteLock(); - } - } + _dictionary.Clear(); } public bool Contains(T item) { - _lock.EnterReadLock(); - - try - { - return _hashSet.Contains(item); - } - finally - { - if (_lock.IsReadLockHeld) - { - _lock.ExitReadLock(); - } - } + return _dictionary.ContainsKey(item); } public bool Remove(T item) { - _lock.EnterWriteLock(); - - try - { - return _hashSet.Remove(item); - } - finally - { - if (_lock.IsWriteLockHeld) - { - _lock.ExitWriteLock(); - } - } - } - - public int Count - { - get - { - _lock.EnterReadLock(); - - try - { - return _hashSet.Count; - } - finally - { - if (_lock.IsReadLockHeld) - { - _lock.ExitReadLock(); - } - } - } - } - - #endregion - - #region Dispose - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - _lock.Dispose(); - } - } - - ~ConcurrentHashSet() - { - Dispose(false); + return _dictionary.TryRemove(item, out _); } - #endregion + public int Count => _dictionary.Count; } diff --git a/TUnit.Engine/Discovery/ReflectionHookDiscoveryService.cs b/TUnit.Engine/Discovery/ReflectionHookDiscoveryService.cs index 2048aa8187..cc3954b121 100644 --- a/TUnit.Engine/Discovery/ReflectionHookDiscoveryService.cs +++ b/TUnit.Engine/Discovery/ReflectionHookDiscoveryService.cs @@ -21,6 +21,8 @@ internal sealed class ReflectionHookDiscoveryService private static readonly ConcurrentDictionary _scannedAssemblies = new(); private static readonly ConcurrentDictionary _registeredMethods = new(); private static readonly ConcurrentDictionary _methodKeyCache = new(); + // Cache attribute lookups to avoid repeated reflection calls in hot paths + private static readonly ConcurrentDictionary _attributeCache = new(); private static int _registrationIndex = 0; private static int _discoveryRunCount = 0; @@ -44,6 +46,21 @@ private static string GetMethodKey(MethodInfo method) }); } + /// + /// Get cached hook attributes for a method to avoid repeated GetCustomAttribute calls + /// + private static (BeforeAttribute?, AfterAttribute?, BeforeEveryAttribute?, AfterEveryAttribute?) GetCachedAttributes(MethodInfo method) + { + return _attributeCache.GetOrAdd(method, m => + { + var beforeAttr = m.GetCustomAttribute(); + var afterAttr = m.GetCustomAttribute(); + var beforeEveryAttr = m.GetCustomAttribute(); + var afterEveryAttr = m.GetCustomAttribute(); + return (beforeAttr, afterAttr, beforeEveryAttr, afterEveryAttr); + }); + } + private static void ClearSourceGeneratedHooks() { // Clear all hook collections to avoid duplicates when both @@ -94,9 +111,10 @@ public static void DiscoverInstanceHooksForType(Type closedGenericType) var current = closedGenericType; while (current != null && current != typeof(object)) { - inheritanceChain.Insert(0, current); // Insert at front to get base-to-derived order + inheritanceChain.Add(current); // Add to end current = current.BaseType; } + inheritanceChain.Reverse(); // Reverse once to get base-to-derived order (O(n) vs O(n²)) // Discover hooks in each type in the inheritance chain, from base to derived foreach (var typeInChain in inheritanceChain) @@ -104,11 +122,8 @@ public static void DiscoverInstanceHooksForType(Type closedGenericType) var methods = typeInChain.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .OrderBy(m => { - // Get the minimum order from all hook attributes on this method - var beforeAttr = m.GetCustomAttribute(); - var afterAttr = m.GetCustomAttribute(); - var beforeEveryAttr = m.GetCustomAttribute(); - var afterEveryAttr = m.GetCustomAttribute(); + // Get the minimum order from cached hook attributes + var (beforeAttr, afterAttr, beforeEveryAttr, afterEveryAttr) = GetCachedAttributes(m); var orders = new List(); if (beforeAttr != null) orders.Add(beforeAttr.Order); @@ -278,9 +293,10 @@ private static void DiscoverHooksInType([DynamicallyAccessedMembers(DynamicallyA Type? current = type; while (current != null && current != typeof(object)) { - inheritanceChain.Insert(0, current); // Insert at front to get base-to-derived order + inheritanceChain.Add(current); // Add to end current = current.BaseType; } + inheritanceChain.Reverse(); // Reverse once to get base-to-derived order (O(n) vs O(n²)) // Discover hooks in each type in the inheritance chain, from base to derived foreach (var typeInChain in inheritanceChain) @@ -289,11 +305,8 @@ private static void DiscoverHooksInType([DynamicallyAccessedMembers(DynamicallyA var methods = typeInChain.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly) .OrderBy(m => { - // Get the minimum order from all hook attributes on this method - var beforeAttr = m.GetCustomAttribute(); - var afterAttr = m.GetCustomAttribute(); - var beforeEveryAttr = m.GetCustomAttribute(); - var afterEveryAttr = m.GetCustomAttribute(); + // Get the minimum order from cached hook attributes + var (beforeAttr, afterAttr, beforeEveryAttr, afterEveryAttr) = GetCachedAttributes(m); var orders = new List(); if (beforeAttr != null) orders.Add(beforeAttr.Order); @@ -692,7 +705,7 @@ private static void RegisterInstanceBeforeHook( return; } - var bag = Sources.BeforeTestHooks.GetOrAdd(type, static _ => new ConcurrentBag()); + var bag = Sources.BeforeTestHooks.GetOrAdd(type, static _ => []); var hook = new InstanceHookMethod { InitClassType = type, @@ -717,7 +730,7 @@ private static void RegisterInstanceAfterHook( return; } - var bag = Sources.AfterTestHooks.GetOrAdd(type, static _ => new ConcurrentBag()); + var bag = Sources.AfterTestHooks.GetOrAdd(type, static _ => []); var hook = new InstanceHookMethod { InitClassType = type, @@ -736,7 +749,7 @@ private static void RegisterBeforeClassHook( MethodInfo method, int order) { - var bag = Sources.BeforeClassHooks.GetOrAdd(type, static _ => new ConcurrentBag()); + var bag = Sources.BeforeClassHooks.GetOrAdd(type, static _ => []); var hook = new BeforeClassHookMethod { MethodInfo = CreateMethodMetadata(type, method), @@ -756,7 +769,7 @@ private static void RegisterAfterClassHook( MethodInfo method, int order) { - var bag = Sources.AfterClassHooks.GetOrAdd(type, static _ => new ConcurrentBag()); + var bag = Sources.AfterClassHooks.GetOrAdd(type, static _ => []); var hook = new AfterClassHookMethod { MethodInfo = CreateMethodMetadata(type, method), @@ -777,7 +790,7 @@ private static void RegisterBeforeAssemblyHook( MethodInfo method, int order) { - var bag = Sources.BeforeAssemblyHooks.GetOrAdd(assembly, static _ => new ConcurrentBag()); + var bag = Sources.BeforeAssemblyHooks.GetOrAdd(assembly, static _ => []); var hook = new BeforeAssemblyHookMethod { MethodInfo = CreateMethodMetadata(type, method), @@ -798,7 +811,7 @@ private static void RegisterAfterAssemblyHook( MethodInfo method, int order) { - var bag = Sources.AfterAssemblyHooks.GetOrAdd(assembly, static _ => new ConcurrentBag()); + var bag = Sources.AfterAssemblyHooks.GetOrAdd(assembly, static _ => []); var hook = new AfterAssemblyHookMethod { MethodInfo = CreateMethodMetadata(type, method), diff --git a/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index dce151c07d..e0e541f163 100644 --- a/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -345,7 +345,7 @@ private static async Task> DiscoverTestsInAssembly(Assembly a } catch (ReflectionTypeLoadException reflectionTypeLoadException) { - return reflectionTypeLoadException.Types.Where(x => x != null).ToArray()!; + return reflectionTypeLoadException.Types.Where(static x => x != null).ToArray()!; } catch (Exception) { @@ -358,7 +358,7 @@ private static async Task> DiscoverTestsInAssembly(Assembly a return discoveredTests; } - var filteredTypes = types.Where(t => t.IsClass && !IsCompilerGenerated(t)); + var filteredTypes = types.Where(static t => t.IsClass && !IsCompilerGenerated(t)); foreach (var type in filteredTypes) { @@ -487,7 +487,7 @@ private static async IAsyncEnumerable DiscoverTestsInAssemblyStrea yield break; } - var filteredTypes = types.Where(t => t.IsClass && !IsCompilerGenerated(t)); + var filteredTypes = types.Where(static t => t.IsClass && !IsCompilerGenerated(t)); foreach (var type in filteredTypes) { @@ -519,14 +519,14 @@ private static async IAsyncEnumerable DiscoverTestsInAssemblyStrea { // Get all test methods including inherited ones testMethods = GetAllTestMethods(type) - .Where(m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract) + .Where(static m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract) .ToArray(); } else { // Only get declared test methods testMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly) - .Where(m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract) + .Where(static m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract) .ToArray(); } } @@ -753,7 +753,7 @@ private static async IAsyncEnumerable DiscoverGenericTestsStreamin $"Failed to create concrete type for {genericTypeDefinition.FullName ?? genericTypeDefinition.Name}. " + $"Error: {ex.Message}. " + $"Generic parameter count: {genericTypeDefinition.GetGenericArguments().Length}, " + - $"Type arguments: {string.Join(", ", typeArguments?.Select(t => t.Name) ?? [ + $"Type arguments: {string.Join(", ", typeArguments?.Select(static t => t.Name) ?? [ ])}", ex), $"[GENERIC TYPE CREATION FAILED] {genericTypeDefinition.Name}") { @@ -896,6 +896,8 @@ private static Task BuildTestMetadata( GenericMethodInfo = ReflectionGenericTypeResolver.ExtractGenericMethodInfo(testMethod), GenericMethodTypeArguments = testMethod.IsGenericMethodDefinition ? null : testMethod.GetGenericArguments(), AttributeFactory = () => ReflectionAttributeExtractor.GetAllAttributes(testClass, testMethod), + RepeatCount = testMethod.GetCustomAttribute()?.Times + ?? testClass.GetCustomAttribute()?.Times, PropertyInjections = PropertySourceRegistry.DiscoverInjectableProperties(testClass), InheritanceDepth = inheritanceDepth }); @@ -971,7 +973,7 @@ private static string GenerateTestName(Type testClass, MethodInfo testMethod) return (_, _) => Activator.CreateInstance(testClass)!; } - var constructedTypeCtor = constructedTypeConstructors.FirstOrDefault(c => c.GetParameters().Length == 0) ?? constructedTypeConstructors.First(); + var constructedTypeCtor = constructedTypeConstructors.FirstOrDefault(static c => c.GetParameters().Length == 0) ?? constructedTypeConstructors.First(); var constructedTypeFactory = CreateReflectionInstanceFactory(constructedTypeCtor); // Return a factory that ignores type arguments since the type is already closed @@ -985,7 +987,7 @@ private static string GenerateTestName(Type testClass, MethodInfo testMethod) return (_, _) => Activator.CreateInstance(testClass)!; } - var ctor = constructors.FirstOrDefault(c => c.GetParameters().Length == 0) ?? constructors.First(); + var ctor = constructors.FirstOrDefault(static c => c.GetParameters().Length == 0) ?? constructors.First(); var factory = CreateReflectionInstanceFactory(ctor); return (_, args) => factory(args); @@ -1056,7 +1058,7 @@ private static TestMetadata CreateFailedTestMetadataForAssembly(Assembly assembl LineNumber = 0, MethodMetadata = CreateDummyMethodMetadata(testClass, "AssemblyScanFailed"), - AttributeFactory = () => + AttributeFactory = static () => [ ], DataSources = @@ -1839,7 +1841,7 @@ private async IAsyncEnumerable ExecuteDynamicTestBuilderStreamingA builderMethod.Invoke(instance, [context]); // Retrieve the discovered tests - foreach (var discoveryResult in context.Tests.SelectMany(t => t.GetTests())) + foreach (var discoveryResult in context.Tests.SelectMany(static t => t.GetTests())) { cancellationToken.ThrowIfCancellationRequested(); @@ -1924,7 +1926,7 @@ private Task CreateMetadataFromDynamicDiscoveryResult(DynamicDisco TestName = testName, TestClassType = result.TestClassType, TestMethodName = methodInfo.Name, - Dependencies = result.Attributes.OfType().Select(a => a.ToTestDependency()).ToArray(), + Dependencies = result.Attributes.OfType().Select(static a => a.ToTestDependency()).ToArray(), DataSources = [], // Dynamic tests don't use data sources in the same way ClassDataSources = [], PropertyDataSources = [], @@ -2037,7 +2039,7 @@ private static TestMetadata CreateFailedTestMetadataForDynamicSource(IDynamicTes FilePath = "Unknown", LineNumber = 0, MethodMetadata = CreateDummyMethodMetadata(source.GetType(), "CollectDynamicTests"), - AttributeFactory = () => [], + AttributeFactory = static () => [], DataSources = [], ClassDataSources = [], PropertyDataSources = [] diff --git a/TUnit.Engine/Discovery/ReflectionTestMetadata.cs b/TUnit.Engine/Discovery/ReflectionTestMetadata.cs index d52c6fcba9..4866d23e2e 100644 --- a/TUnit.Engine/Discovery/ReflectionTestMetadata.cs +++ b/TUnit.Engine/Discovery/ReflectionTestMetadata.cs @@ -52,7 +52,7 @@ async Task CreateInstance(TestContext testContext) // Otherwise fall back to creating instance normally // Try to create instance with ClassConstructor attribute - var attributes = testContext.TestDetails.Attributes; + var attributes = testContext.TestDetails.GetAllAttributes(); var classConstructorInstance = await ClassConstructorHelper.TryCreateInstanceWithClassConstructor( attributes, TestClassType, @@ -81,11 +81,16 @@ async Task CreateInstance(TestContext testContext) // Create test invoker with CancellationToken support // Determine if the test method has a CancellationToken parameter - var parameterTypes = MethodMetadata.Parameters.Select(static p => p.Type).ToArray(); - var hasCancellationToken = parameterTypes.Any(t => t == typeof(CancellationToken)); - var cancellationTokenIndex = hasCancellationToken - ? Array.IndexOf(parameterTypes, typeof(CancellationToken)) - : -1; + var cancellationTokenIndex = -1; + for (var i = 0; i < MethodMetadata.Parameters.Length; i++) + { + if (MethodMetadata.Parameters[i].Type == typeof(CancellationToken)) + { + cancellationTokenIndex = i; + break; + } + } + var hasCancellationToken = cancellationTokenIndex != -1; Func invokeTest = async (instance, args, testContext, cancellationToken) => { diff --git a/TUnit.Engine/Events/EventReceiverCache.cs b/TUnit.Engine/Events/EventReceiverCache.cs index 5b3bce2c4c..c8ff1ccac0 100644 --- a/TUnit.Engine/Events/EventReceiverCache.cs +++ b/TUnit.Engine/Events/EventReceiverCache.cs @@ -12,14 +12,14 @@ internal sealed class EventReceiverCache { public Type ReceiverType { get; init; } public Type TestClassType { get; init; } - + public bool Equals(CacheKey other) => - ReceiverType == other.ReceiverType && + ReceiverType == other.ReceiverType && TestClassType == other.TestClassType; - + public override bool Equals(object? obj) => obj is CacheKey other && Equals(other); - + public override int GetHashCode() { #if NETSTANDARD2_0 @@ -35,9 +35,10 @@ public override int GetHashCode() #endif } } - - private readonly ConcurrentDictionary _cache = new(); - + + // Use object to store typed caches (avoids boxing on retrieval) + private readonly ConcurrentDictionary _typedCaches = new(); + /// /// Get cached receivers or compute and cache them /// @@ -45,31 +46,13 @@ public T[] GetApplicableReceivers( Type testClassType, Func factory) where T : class, IEventReceiver { - var key = new CacheKey - { - ReceiverType = typeof(T), - TestClassType = testClassType - }; - - var cached = _cache.GetOrAdd(key, _ => - { - var receivers = factory(testClassType); - // Pre-size array and avoid LINQ Cast + ToArray - var array = new object[receivers.Length]; - for (var i = 0; i < receivers.Length; i++) - { - array[i] = receivers[i]; - } - return array; - }); - - // Cast back to specific type - var result = new T[cached.Length]; - for (var i = 0; i < cached.Length; i++) - { - result[i] = (T)cached[i]; - } - return result; + // Get or create typed cache for this receiver type + var typedCache = (ConcurrentDictionary)_typedCaches.GetOrAdd( + typeof(T), + static _ => new ConcurrentDictionary()); + + // Use typed cache - no boxing/unboxing needed + return typedCache.GetOrAdd(testClassType, factory); } /// @@ -77,22 +60,25 @@ public T[] GetApplicableReceivers( /// public void Clear() { - _cache.Clear(); + _typedCaches.Clear(); } - + /// /// Get cache statistics /// public (int EntryCount, long EstimatedSize) GetStatistics() { - var entryCount = _cache.Count; - var estimatedSize = entryCount * (16 + 8); // Rough estimate: key size + reference - - foreach (var kvp in _cache) + var entryCount = _typedCaches.Values.Sum(cache => { - estimatedSize += kvp.Value.Length * 8; // References - } - + if (cache is System.Collections.ICollection collection) + { + return collection.Count; + } + return 0; + }); + + var estimatedSize = entryCount * (16 + 8); // Rough estimate: key size + reference + return (entryCount, estimatedSize); } } \ No newline at end of file diff --git a/TUnit.Engine/Events/EventReceiverRegistry.cs b/TUnit.Engine/Events/EventReceiverRegistry.cs index 87f4e8df18..d7bfd127db 100644 --- a/TUnit.Engine/Events/EventReceiverRegistry.cs +++ b/TUnit.Engine/Events/EventReceiverRegistry.cs @@ -26,6 +26,7 @@ private enum EventTypes private volatile EventTypes _registeredEvents = EventTypes.None; private readonly Dictionary _receiversByType = new(); + private readonly Dictionary _cachedTypedReceivers = new(); private readonly ReaderWriterLockSlim _lock = new(); /// @@ -66,7 +67,7 @@ public void RegisterReceiver(object receiver) private void RegisterReceiverInternal(object receiver) { UpdateEventFlags(receiver); - + // Register for each interface type the object implements // We use a simpler approach that doesn't require reflection RegisterIfImplements(receiver); @@ -79,6 +80,8 @@ private void RegisterReceiverInternal(object receiver) RegisterIfImplements(receiver); RegisterIfImplements(receiver); RegisterIfImplements(receiver); + + _cachedTypedReceivers.Clear(); } private void RegisterIfImplements(object receiver) where T : class @@ -136,30 +139,67 @@ private void RegisterIfImplements(object receiver) where T : class [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool HasAnyReceivers() => _registeredEvents != EventTypes.None; - /// - /// Get receivers of specific type (for invocation) - /// public T[] GetReceiversOfType() where T : class { + var typeKey = typeof(T); + _lock.EnterReadLock(); try { - if (_receiversByType.TryGetValue(typeof(T), out var receivers)) + if (_cachedTypedReceivers.TryGetValue(typeKey, out var cached)) + { + return (T[])cached; + } + } + finally + { + _lock.ExitReadLock(); + } + + _lock.EnterUpgradeableReadLock(); + try + { + if (_cachedTypedReceivers.TryGetValue(typeKey, out var cached)) + { + return (T[])cached; + } + + if (_receiversByType.TryGetValue(typeKey, out var receivers)) { - // Cast array to specific type var typedArray = new T[receivers.Length]; for (var i = 0; i < receivers.Length; i++) { typedArray[i] = (T)receivers[i]; } + + _lock.EnterWriteLock(); + try + { + _cachedTypedReceivers[typeKey] = typedArray; + } + finally + { + _lock.ExitWriteLock(); + } + return typedArray; } - return [ - ]; + + T[] emptyArray = []; + _lock.EnterWriteLock(); + try + { + _cachedTypedReceivers[typeKey] = emptyArray; + } + finally + { + _lock.ExitWriteLock(); + } + return emptyArray; } finally { - _lock.ExitReadLock(); + _lock.ExitUpgradeableReadLock(); } } diff --git a/TUnit.Engine/Extensions/JsonExtensions.cs b/TUnit.Engine/Extensions/JsonExtensions.cs index aae632e86b..791aa05b9a 100644 --- a/TUnit.Engine/Extensions/JsonExtensions.cs +++ b/TUnit.Engine/Extensions/JsonExtensions.cs @@ -7,27 +7,45 @@ internal static class JsonExtensions { public static TestSessionJson ToJsonModel(this TestSessionContext context) { + var assemblies = new TestAssemblyJson[context.Assemblies.Count]; + for (var i = 0; i < context.Assemblies.Count; i++) + { + assemblies[i] = context.Assemblies[i].ToJsonModel(); + } + return new TestSessionJson { - Assemblies = context.Assemblies.Select(static x => x.ToJsonModel()).ToArray() + Assemblies = assemblies }; } public static TestAssemblyJson ToJsonModel(this AssemblyHookContext context) { + var classes = new TestClassJson[context.TestClasses.Count]; + for (var i = 0; i < context.TestClasses.Count; i++) + { + classes[i] = context.TestClasses[i].ToJsonModel(); + } + return new TestAssemblyJson { AssemblyName = context.Assembly.GetName().FullName, - Classes = context.TestClasses.Select(static x => x.ToJsonModel()).ToArray() + Classes = classes }; } public static TestClassJson ToJsonModel(this ClassHookContext context) { + var tests = new TestJson[context.Tests.Count]; + for (var i = 0; i < context.Tests.Count; i++) + { + tests[i] = context.Tests[i].ToJsonModel(); + } + return new TestClassJson { Type = context.ClassType.FullName, - Tests = context.Tests.Select(static x => x.ToJsonModel()).ToArray() + Tests = tests }; } @@ -39,6 +57,28 @@ public static TestJson ToJsonModel(this TestContext context) throw new InvalidOperationException("TestDetails is null"); } + Type[]? classParameterTypes = testDetails.TestClassParameterTypes; + string[] classParamTypeNames; + if (classParameterTypes != null) + { + classParamTypeNames = new string[classParameterTypes.Length]; + for (var i = 0; i < classParameterTypes.Length; i++) + { + classParamTypeNames[i] = classParameterTypes[i].FullName ?? "Unknown"; + } + } + else + { + classParamTypeNames = []; + } + + var methodParameters = testDetails.MethodMetadata.Parameters; + var methodParamTypeNames = new string[methodParameters.Length]; + for (var i = 0; i < methodParameters.Length; i++) + { + methodParamTypeNames[i] = methodParameters[i].Type.FullName ?? "Unknown"; + } + return new TestJson { Categories = testDetails.Categories, @@ -58,8 +98,8 @@ public static TestJson ToJsonModel(this TestContext context) TestFilePath = testDetails.TestFilePath, TestLineNumber = testDetails.TestLineNumber, TestMethodArguments = testDetails.TestMethodArguments, - TestClassParameterTypes = testDetails.TestClassParameterTypes?.Select(static x => x.FullName ?? "Unknown").ToArray() ?? [], - TestMethodParameterTypes = testDetails.MethodMetadata.Parameters.Select(static p => p.Type.FullName ?? "Unknown").ToArray(), + TestClassParameterTypes = classParamTypeNames, + TestMethodParameterTypes = methodParamTypeNames, }; } diff --git a/TUnit.Engine/Extensions/TestContextExtensions.cs b/TUnit.Engine/Extensions/TestContextExtensions.cs index aa9b10edc8..c7fe2d3dcb 100644 --- a/TUnit.Engine/Extensions/TestContextExtensions.cs +++ b/TUnit.Engine/Extensions/TestContextExtensions.cs @@ -10,13 +10,22 @@ internal static class TestContextExtensions testContext.Events, ..testContext.TestDetails.TestClassArguments, testContext.TestDetails.ClassInstance, - ..testContext.TestDetails.Attributes, + ..testContext.TestDetails.GetAllAttributes(), ..testContext.TestDetails.TestMethodArguments, ..testContext.TestDetails.TestClassInjectedPropertyArguments.Select(x => x.Value), ]; public static IEnumerable GetEligibleEventObjects(this TestContext testContext) { - return GetInternal(testContext).OfType(); + // Return cached result if available + if (testContext.CachedEligibleEventObjects != null) + { + return testContext.CachedEligibleEventObjects; + } + + // Materialize and cache the result + var result = GetInternal(testContext).OfType().ToArray(); + testContext.CachedEligibleEventObjects = result; + return result; } } diff --git a/TUnit.Engine/Framework/TUnitServiceProvider.cs b/TUnit.Engine/Framework/TUnitServiceProvider.cs index a266526c39..9aa33afb52 100644 --- a/TUnit.Engine/Framework/TUnitServiceProvider.cs +++ b/TUnit.Engine/Framework/TUnitServiceProvider.cs @@ -149,6 +149,7 @@ public TUnitServiceProvider(IExtension extension, var testStateManager = Register(new TestStateManager()); var testContextRestorer = Register(new TestContextRestorer()); var testMethodInvoker = Register(new TestMethodInvoker()); + var hashSetPool = Register(new HashSetPool()); // Use the mode already determined earlier ITestDataCollector dataCollector; @@ -166,7 +167,7 @@ public TUnitServiceProvider(IExtension extension, } var testBuilder = Register( - new TestBuilder(TestSessionId, EventReceiverOrchestrator, ContextProvider, PropertyInjectionService, DataSourceInitializer, hookDiscoveryService)); + new TestBuilder(TestSessionId, EventReceiverOrchestrator, ContextProvider, PropertyInjectionService, DataSourceInitializer, hookDiscoveryService, testArgumentRegistrationService)); TestBuilderPipeline = Register( new TestBuilderPipeline( @@ -193,7 +194,8 @@ public TUnitServiceProvider(IExtension extension, testInitializer, objectTracker, Logger, - EventReceiverOrchestrator)); + EventReceiverOrchestrator, + hashSetPool)); // Create the HookOrchestratingTestExecutorAdapter // Note: We'll need to update this to handle dynamic dependencies properly @@ -221,6 +223,8 @@ public TUnitServiceProvider(IExtension extension, var staticPropertyHandler = Register(new StaticPropertyHandler(Logger, objectTracker, trackableObjectGraphProvider, disposer)); + var dynamicTestQueue = Register(new DynamicTestQueue(MessageBus)); + var testScheduler = Register(new TestScheduler( Logger, testGroupingService, @@ -232,7 +236,8 @@ public TUnitServiceProvider(IExtension extension, circularDependencyDetector, constraintKeyScheduler, hookExecutor, - staticPropertyHandler)); + staticPropertyHandler, + dynamicTestQueue)); TestSessionCoordinator = Register(new TestSessionCoordinator(EventReceiverOrchestrator, Logger, @@ -243,7 +248,7 @@ public TUnitServiceProvider(IExtension extension, MessageBus, staticPropertyInitializer)); - Register(new TestRegistry(TestBuilderPipeline, testCoordinator, TestSessionId, CancellationToken.Token)); + Register(new TestRegistry(TestBuilderPipeline, testCoordinator, dynamicTestQueue, TestSessionId, CancellationToken.Token)); InitializeConsoleInterceptors(); } diff --git a/TUnit.Engine/Helpers/AssemblyReferenceCache.cs b/TUnit.Engine/Helpers/AssemblyReferenceCache.cs index b03b944abb..9241c6d890 100644 --- a/TUnit.Engine/Helpers/AssemblyReferenceCache.cs +++ b/TUnit.Engine/Helpers/AssemblyReferenceCache.cs @@ -14,7 +14,7 @@ internal static class AssemblyReferenceCache #endif public static AssemblyName[] GetReferencedAssemblies(Assembly assembly) { - return _assemblyCache.GetOrAdd(assembly, a => a.GetReferencedAssemblies()); + return _assemblyCache.GetOrAdd(assembly, static a => a.GetReferencedAssemblies()); } #if NET6_0_OR_GREATER @@ -22,6 +22,6 @@ public static AssemblyName[] GetReferencedAssemblies(Assembly assembly) #endif public static Type[] GetInterfaces(Type type) { - return _interfaceCache.GetOrAdd(type, t => t.GetInterfaces()); + return _interfaceCache.GetOrAdd(type, static t => t.GetInterfaces()); } } diff --git a/TUnit.Engine/Helpers/HookTimeoutHelper.cs b/TUnit.Engine/Helpers/HookTimeoutHelper.cs index 7205caaf05..155b6c34a1 100644 --- a/TUnit.Engine/Helpers/HookTimeoutHelper.cs +++ b/TUnit.Engine/Helpers/HookTimeoutHelper.cs @@ -1,4 +1,6 @@ +using TUnit.Core; using TUnit.Core.Hooks; +using TUnit.Core.Interfaces; namespace TUnit.Engine.Helpers; @@ -15,11 +17,14 @@ public static Func CreateTimeoutHookAction( T context, CancellationToken cancellationToken) { + // CENTRAL POINT: At execution time, check if we should use a custom hook executor + // This happens AFTER OnTestRegistered, so CustomHookExecutor will be set if the user called SetHookExecutor var timeout = hook.Timeout; + if (timeout == null) { - // No timeout specified, execute normally - return async () => await hook.ExecuteAsync(context, cancellationToken); + // No timeout specified, execute with potential custom executor + return async () => await ExecuteHookWithPotentialCustomExecutor(hook, context, cancellationToken); } return async () => @@ -30,7 +35,7 @@ public static Func CreateTimeoutHookAction( try { - await hook.ExecuteAsync(context, cts.Token); + await ExecuteHookWithPotentialCustomExecutor(hook, context, cts.Token); } catch (OperationCanceledException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested) { @@ -39,6 +44,40 @@ public static Func CreateTimeoutHookAction( }; } + /// + /// Executes a hook, using a custom executor if one is set on the TestContext + /// + private static ValueTask ExecuteHookWithPotentialCustomExecutor(StaticHookMethod hook, T context, CancellationToken cancellationToken) + { + // Check if this is a TestContext with a custom hook executor + if (context is TestContext testContext && testContext.CustomHookExecutor != null) + { + // BYPASS the hook's default executor and call the custom executor directly with the hook's body + var customExecutor = testContext.CustomHookExecutor; + + // Determine which executor method to call based on hook type + if (hook is BeforeTestHookMethod || hook is InstanceHookMethod) + { + return customExecutor.ExecuteBeforeTestHook( + hook.MethodInfo, + testContext, + () => hook.Body!.Invoke(context, cancellationToken) + ); + } + else if (hook is AfterTestHookMethod) + { + return customExecutor.ExecuteAfterTestHook( + hook.MethodInfo, + testContext, + () => hook.Body!.Invoke(context, cancellationToken) + ); + } + } + + // No custom executor, use the hook's default executor + return hook.ExecuteAsync(context, cancellationToken); + } + /// /// Creates a timeout-aware action wrapper for a hook delegate /// @@ -74,6 +113,8 @@ public static Func CreateTimeoutHookAction( /// /// Creates a timeout-aware action wrapper for a hook delegate that returns ValueTask + /// This overload is used for instance hooks (InstanceHookMethod) + /// Custom executor handling for instance hooks is done in HookCollectionService.CreateInstanceHookDelegateAsync /// public static Func CreateTimeoutHookAction( Func hookDelegate, diff --git a/TUnit.Engine/Interfaces/IDynamicTestQueue.cs b/TUnit.Engine/Interfaces/IDynamicTestQueue.cs new file mode 100644 index 0000000000..56c8f4498d --- /dev/null +++ b/TUnit.Engine/Interfaces/IDynamicTestQueue.cs @@ -0,0 +1,40 @@ +using TUnit.Core; + +namespace TUnit.Engine.Interfaces; + +/// +/// Thread-safe queue for managing dynamically created tests during execution. +/// Ensures tests created at runtime (via CreateTestVariant or AddDynamicTest) are properly scheduled. +/// Handles discovery notification internally to keep all dynamic test logic in one place. +/// +internal interface IDynamicTestQueue +{ + /// + /// Enqueues a test for execution and notifies the message bus. Thread-safe. + /// + /// The test to enqueue + /// Task that completes when the test is enqueued and discovery is notified + Task EnqueueAsync(AbstractExecutableTest test); + + /// + /// Attempts to dequeue the next test. Thread-safe. + /// + /// The dequeued test, or null if queue is empty + /// True if a test was dequeued, false if queue is empty + bool TryDequeue(out AbstractExecutableTest? test); + + /// + /// Gets the number of pending tests in the queue. + /// + int PendingCount { get; } + + /// + /// Indicates whether the queue has been completed and no more tests will be added. + /// + bool IsCompleted { get; } + + /// + /// Marks the queue as complete, indicating no more tests will be added. + /// + void Complete(); +} diff --git a/TUnit.Engine/Scheduling/TestScheduler.cs b/TUnit.Engine/Scheduling/TestScheduler.cs index 4fe130f97a..5fca724fd1 100644 --- a/TUnit.Engine/Scheduling/TestScheduler.cs +++ b/TUnit.Engine/Scheduling/TestScheduler.cs @@ -1,8 +1,10 @@ +using System.Buffers; using Microsoft.Testing.Platform.CommandLine; using TUnit.Core; using TUnit.Core.Exceptions; using TUnit.Core.Logging; using TUnit.Engine.CommandLineProviders; +using TUnit.Engine.Interfaces; using TUnit.Engine.Logging; using TUnit.Engine.Models; using TUnit.Engine.Services; @@ -22,6 +24,7 @@ internal sealed class TestScheduler : ITestScheduler private readonly IConstraintKeyScheduler _constraintKeyScheduler; private readonly HookExecutor _hookExecutor; private readonly StaticPropertyHandler _staticPropertyHandler; + private readonly IDynamicTestQueue _dynamicTestQueue; private readonly int _maxParallelism; private readonly SemaphoreSlim? _maxParallelismSemaphore; @@ -36,7 +39,8 @@ public TestScheduler( CircularDependencyDetector circularDependencyDetector, IConstraintKeyScheduler constraintKeyScheduler, HookExecutor hookExecutor, - StaticPropertyHandler staticPropertyHandler) + StaticPropertyHandler staticPropertyHandler, + IDynamicTestQueue dynamicTestQueue) { _logger = logger; _groupingService = groupingService; @@ -48,6 +52,7 @@ public TestScheduler( _constraintKeyScheduler = constraintKeyScheduler; _hookExecutor = hookExecutor; _staticPropertyHandler = staticPropertyHandler; + _dynamicTestQueue = dynamicTestQueue; _maxParallelism = GetMaxParallelism(logger, commandLineOptions); @@ -83,12 +88,11 @@ public async Task ScheduleAndExecuteAsync( foreach (var (test, dependencyChain) in circularDependencies) { // Format the error message to match the expected format - var simpleNames = dependencyChain.Select(t => + var simpleNames = new List(dependencyChain.Count); + foreach (var t in dependencyChain) { - var className = t.Metadata.TestClassType.Name; - var testName = t.Metadata.TestMethodName; - return $"{className}.{testName}"; - }).ToList(); + simpleNames.Add($"{t.Metadata.TestClassType.Name}.{t.Metadata.TestMethodName}"); + } var errorMessage = $"DependsOn Conflict: {string.Join(" > ", simpleNames)}"; var exception = new CircularDependencyException(errorMessage); @@ -104,8 +108,17 @@ public async Task ScheduleAndExecuteAsync( } } - var executableTests = testList.Where(t => !testsInCircularDependencies.Contains(t)).ToArray(); - if (executableTests.Length == 0) + var executableTests = new List(testList.Count); + foreach (var test in testList) + { + if (!testsInCircularDependencies.Contains(test)) + { + executableTests.Add(test); + } + } + + var executableTestsArray = executableTests.ToArray(); + if (executableTestsArray.Length == 0) { await _logger.LogDebugAsync("No executable tests found after removing circular dependencies").ConfigureAwait(false); return true; @@ -118,7 +131,7 @@ public async Task ScheduleAndExecuteAsync( _staticPropertyHandler.TrackStaticProperties(); // Group tests by their parallel constraints - var groupedTests = await _groupingService.GroupTestsByConstraintsAsync(executableTests).ConfigureAwait(false); + var groupedTests = await _groupingService.GroupTestsByConstraintsAsync(executableTestsArray).ConfigureAwait(false); // Execute tests according to their grouping await ExecuteGroupedTestsAsync(groupedTests, cancellationToken).ConfigureAwait(false); @@ -146,6 +159,9 @@ private async Task ExecuteGroupedTestsAsync( GroupedTests groupedTests, CancellationToken cancellationToken) { + // Start dynamic test queue processing in background + var dynamicTestProcessingTask = ProcessDynamicTestQueueAsync(cancellationToken); + if (groupedTests.Parallel.Length > 0) { await _logger.LogDebugAsync($"Starting {groupedTests.Parallel.Length} parallel tests").ConfigureAwait(false); @@ -154,9 +170,15 @@ private async Task ExecuteGroupedTestsAsync( foreach (var group in groupedTests.ParallelGroups) { - var orderedTests = group.Value.OrderBy(t => t.Key).SelectMany(x => x.Value).ToArray(); - await _logger.LogDebugAsync($"Starting parallel group '{group.Key}' with {orderedTests.Length} orders").ConfigureAwait(false); - await ExecuteTestsAsync(orderedTests, cancellationToken).ConfigureAwait(false); + var orderedTests = new List(); + foreach (var kvp in group.Value.OrderBy(t => t.Key)) + { + orderedTests.AddRange(kvp.Value); + } + var orderedTestsArray = orderedTests.ToArray(); + + await _logger.LogDebugAsync($"Starting parallel group '{group.Key}' with {orderedTestsArray.Length} orders").ConfigureAwait(false); + await ExecuteTestsAsync(orderedTestsArray, cancellationToken).ConfigureAwait(false); } foreach (var kvp in groupedTests.ConstrainedParallelGroups) @@ -190,6 +212,59 @@ private async Task ExecuteGroupedTestsAsync( await _logger.LogDebugAsync($"Starting {groupedTests.NotInParallel.Length} global NotInParallel tests").ConfigureAwait(false); await ExecuteSequentiallyAsync(groupedTests.NotInParallel, cancellationToken).ConfigureAwait(false); } + + // Mark the queue as complete and wait for remaining dynamic tests to finish + _dynamicTestQueue.Complete(); + await dynamicTestProcessingTask.ConfigureAwait(false); + } + + #if NET6_0_OR_GREATER + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Test execution involves reflection for hooks and initialization")] + #endif + private async Task ProcessDynamicTestQueueAsync(CancellationToken cancellationToken) + { + var dynamicTests = new List(); + + while (!_dynamicTestQueue.IsCompleted || _dynamicTestQueue.PendingCount > 0) + { + // Dequeue all currently pending tests + while (_dynamicTestQueue.TryDequeue(out var test)) + { + if (test != null) + { + dynamicTests.Add(test); + } + } + + // Execute the batch of dynamic tests if any were found + if (dynamicTests.Count > 0) + { + await _logger.LogDebugAsync($"Executing {dynamicTests.Count} dynamic test(s)").ConfigureAwait(false); + + // Group and execute just like regular tests + var dynamicTestsArray = dynamicTests.ToArray(); + var groupedDynamicTests = await _groupingService.GroupTestsByConstraintsAsync(dynamicTestsArray).ConfigureAwait(false); + + // Execute the grouped dynamic tests (recursive call handles sub-dynamics) + if (groupedDynamicTests.Parallel.Length > 0) + { + await ExecuteTestsAsync(groupedDynamicTests.Parallel, cancellationToken).ConfigureAwait(false); + } + + if (groupedDynamicTests.NotInParallel.Length > 0) + { + await ExecuteSequentiallyAsync(groupedDynamicTests.NotInParallel, cancellationToken).ConfigureAwait(false); + } + + dynamicTests.Clear(); + } + + // If queue is not complete, wait a short time before checking again + if (!_dynamicTestQueue.IsCompleted) + { + await Task.Delay(50, cancellationToken).ConfigureAwait(false); + } + } } #if NET6_0_OR_GREATER @@ -205,11 +280,21 @@ private async Task ExecuteTestsAsync( } else { - var tasks = tests.Select(test => - test.ExecutionTask ??= Task.Run(() => ExecuteSingleTestAsync(test, cancellationToken), CancellationToken.None) - ); + var tasks = ArrayPool.Shared.Rent(tests.Length); + try + { + for (var i = 0; i < tests.Length; i++) + { + var test = tests[i]; + tasks[i] = test.ExecutionTask ??= Task.Run(() => ExecuteSingleTestAsync(test, cancellationToken), CancellationToken.None); + } - await WaitForTasksWithFailFastHandling(tasks, cancellationToken).ConfigureAwait(false); + await WaitForTasksWithFailFastHandling(new ArraySegment(tasks, 0, tests.Length), cancellationToken).ConfigureAwait(false); + } + finally + { + ArrayPool.Shared.Return(tasks); + } } } @@ -260,36 +345,48 @@ private async Task ExecuteWithGlobalLimitAsync( AbstractExecutableTest[] tests, CancellationToken cancellationToken) { - var tasks = tests.Select(async test => + var tasks = ArrayPool.Shared.Rent(tests.Length); + try { - SemaphoreSlim? parallelLimiterSemaphore = null; - - if (test.Context.ParallelLimiter != null) - { - parallelLimiterSemaphore = _parallelLimitLockProvider.GetLock(test.Context.ParallelLimiter); - await parallelLimiterSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - } - - try + for (var i = 0; i < tests.Length; i++) { - await _maxParallelismSemaphore!.WaitAsync(cancellationToken).ConfigureAwait(false); - try + var test = tests[i]; + tasks[i] = Task.Run(async () => { - test.ExecutionTask ??= _testRunner.ExecuteTestAsync(test, cancellationToken); - await test.ExecutionTask.ConfigureAwait(false); - } - finally - { - _maxParallelismSemaphore.Release(); - } + SemaphoreSlim? parallelLimiterSemaphore = null; + + if (test.Context.ParallelLimiter != null) + { + parallelLimiterSemaphore = _parallelLimitLockProvider.GetLock(test.Context.ParallelLimiter); + await parallelLimiterSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + try + { + await _maxParallelismSemaphore!.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + test.ExecutionTask ??= _testRunner.ExecuteTestAsync(test, cancellationToken); + await test.ExecutionTask.ConfigureAwait(false); + } + finally + { + _maxParallelismSemaphore.Release(); + } + } + finally + { + parallelLimiterSemaphore?.Release(); + } + }, CancellationToken.None); } - finally - { - parallelLimiterSemaphore?.Release(); - } - }); - await WaitForTasksWithFailFastHandling(tasks, cancellationToken).ConfigureAwait(false); + await WaitForTasksWithFailFastHandling(new ArraySegment(tasks, 0, tests.Length), cancellationToken).ConfigureAwait(false); + } + finally + { + ArrayPool.Shared.Return(tasks); + } } private async Task WaitForTasksWithFailFastHandling(IEnumerable tasks, CancellationToken cancellationToken) @@ -316,14 +413,46 @@ private async Task WaitForTasksWithFailFastHandling(IEnumerable tasks, Can private static int GetMaxParallelism(ILogger logger, ICommandLineOptions commandLineOptions) { - if (!commandLineOptions.TryGetOptionArgumentList( + // Check command line argument first (highest priority) + if (commandLineOptions.TryGetOptionArgumentList( MaximumParallelTestsCommandProvider.MaximumParallelTests, - out var args) || args.Length <= 0 || !int.TryParse(args[0], out var maxParallelTests) || maxParallelTests <= 0) + out var args) && args.Length > 0 && int.TryParse(args[0], out var maxParallelTests)) + { + if (maxParallelTests == 0) + { + // 0 means unlimited (backwards compat for advanced users) + logger.LogDebug("Maximum parallel tests: unlimited (from command line)"); + return int.MaxValue; + } + + if (maxParallelTests > 0) + { + logger.LogDebug($"Maximum parallel tests limit set to {maxParallelTests} (from command line)"); + return maxParallelTests; + } + } + + // Check environment variable (second priority) + if (Environment.GetEnvironmentVariable("TUNIT_MAX_PARALLEL_TESTS") is string envVar + && int.TryParse(envVar, out var envLimit)) { - return int.MaxValue; + if (envLimit == 0) + { + logger.LogDebug("Maximum parallel tests: unlimited (from TUNIT_MAX_PARALLEL_TESTS environment variable)"); + return int.MaxValue; + } + + if (envLimit > 0) + { + logger.LogDebug($"Maximum parallel tests limit set to {envLimit} (from TUNIT_MAX_PARALLEL_TESTS environment variable)"); + return envLimit; + } } - logger.LogDebug($"Maximum parallel tests limit set to {maxParallelTests}"); - return maxParallelTests; + // Default: 4x CPU cores (balances CPU-bound and I/O-bound tests) + // This prevents resource exhaustion (DB connections, memory, etc.) while allowing I/O overlap + var defaultLimit = Environment.ProcessorCount * 4; + logger.LogDebug($"Maximum parallel tests limit defaulting to {defaultLimit} ({Environment.ProcessorCount} processors * 4)"); + return defaultLimit; } } diff --git a/TUnit.Engine/Services/BeforeHookTaskCache.cs b/TUnit.Engine/Services/BeforeHookTaskCache.cs index bc22427393..3b76326dac 100644 --- a/TUnit.Engine/Services/BeforeHookTaskCache.cs +++ b/TUnit.Engine/Services/BeforeHookTaskCache.cs @@ -17,33 +17,34 @@ internal sealed class BeforeHookTaskCache private Task? _beforeTestSessionTask; private readonly object _testSessionLock = new(); - public Task GetOrCreateBeforeTestSessionTask(Func taskFactory) + public ValueTask GetOrCreateBeforeTestSessionTask(Func taskFactory) { if (_beforeTestSessionTask != null) { - return _beforeTestSessionTask; + return new ValueTask(_beforeTestSessionTask); } lock (_testSessionLock) { - // Double-check after acquiring lock if (_beforeTestSessionTask == null) { - _beforeTestSessionTask = taskFactory(); + _beforeTestSessionTask = taskFactory().AsTask(); } - return _beforeTestSessionTask; + return new ValueTask(_beforeTestSessionTask); } } - public Task GetOrCreateBeforeAssemblyTask(Assembly assembly, Func taskFactory) + public ValueTask GetOrCreateBeforeAssemblyTask(Assembly assembly, Func taskFactory) { - return _beforeAssemblyTasks.GetOrAdd(assembly, taskFactory); + var task = _beforeAssemblyTasks.GetOrAdd(assembly, a => taskFactory(a).AsTask()); + return new ValueTask(task); } - public Task GetOrCreateBeforeClassTask( + public ValueTask GetOrCreateBeforeClassTask( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] - Type testClass, Func taskFactory) + Type testClass, Func taskFactory) { - return _beforeClassTasks.GetOrAdd(testClass, taskFactory); + var task = _beforeClassTasks.GetOrAdd(testClass, t => taskFactory(t).AsTask()); + return new ValueTask(task); } } diff --git a/TUnit.Engine/Services/CircularDependencyDetector.cs b/TUnit.Engine/Services/CircularDependencyDetector.cs index 70bd5cf353..8a597997f4 100644 --- a/TUnit.Engine/Services/CircularDependencyDetector.cs +++ b/TUnit.Engine/Services/CircularDependencyDetector.cs @@ -16,7 +16,7 @@ internal sealed class CircularDependencyDetector public List<(AbstractExecutableTest Test, List DependencyChain)> DetectCircularDependencies( IEnumerable tests) { - var testList = tests.ToList(); + var testList = tests as IList ?? tests.ToList(); var circularDependencies = new List<(AbstractExecutableTest Test, List DependencyChain)>(); var visitedStates = new Dictionary(capacity: testList.Count); @@ -27,7 +27,8 @@ internal sealed class CircularDependencyDetector continue; } - var path = new List(); + // Typical cycle depth is small (2-5 tests), pre-size to 4 + var path = new List(4); if (HasCycleDfs(test, testList, visitedStates, path)) { // Found a cycle - add all tests in the cycle to circular dependencies @@ -47,9 +48,9 @@ private enum VisitState } private bool HasCycleDfs( - AbstractExecutableTest test, - List allTests, - Dictionary visitedStates, + AbstractExecutableTest test, + IList allTests, + Dictionary visitedStates, List currentPath) { if (visitedStates.TryGetValue(test.TestId, out var state)) diff --git a/TUnit.Engine/Services/DynamicTestQueue.cs b/TUnit.Engine/Services/DynamicTestQueue.cs new file mode 100644 index 0000000000..8536119942 --- /dev/null +++ b/TUnit.Engine/Services/DynamicTestQueue.cs @@ -0,0 +1,65 @@ +using System.Threading.Channels; +using TUnit.Core; +using TUnit.Engine.Interfaces; + +namespace TUnit.Engine.Services; + +/// +/// Thread-safe queue implementation for managing dynamically created tests using System.Threading.Channels. +/// Provides efficient async support for queuing tests created at runtime. +/// Handles discovery notification internally to keep all dynamic test logic in one place. +/// +internal sealed class DynamicTestQueue : IDynamicTestQueue +{ + private readonly Channel _channel; + private readonly ITUnitMessageBus _messageBus; + private int _pendingCount; + private bool _isCompleted; + + public DynamicTestQueue(ITUnitMessageBus messageBus) + { + _messageBus = messageBus ?? throw new ArgumentNullException(nameof(messageBus)); + + // Unbounded channel for maximum flexibility + // Tests can be added at any time during execution + _channel = Channel.CreateUnbounded(new UnboundedChannelOptions + { + SingleReader = false, // Multiple test runners may dequeue + SingleWriter = false // Multiple sources may enqueue (AddDynamicTest, CreateTestVariant) + }); + } + + public async Task EnqueueAsync(AbstractExecutableTest test) + { + Interlocked.Increment(ref _pendingCount); + + if (!_channel.Writer.TryWrite(test)) + { + Interlocked.Decrement(ref _pendingCount); + throw new InvalidOperationException("Failed to enqueue test to dynamic test queue."); + } + + await _messageBus.Discovered(test.Context); + } + + public bool TryDequeue(out AbstractExecutableTest? test) + { + if (_channel.Reader.TryRead(out test)) + { + Interlocked.Decrement(ref _pendingCount); + return true; + } + + test = null; + return false; + } + + public int PendingCount => _pendingCount; + + public bool IsCompleted => _isCompleted; + + public void Complete() + { + _isCompleted = true; + } +} diff --git a/TUnit.Engine/Services/EventReceiverOrchestrator.cs b/TUnit.Engine/Services/EventReceiverOrchestrator.cs index 68696795ce..c09da0b98a 100644 --- a/TUnit.Engine/Services/EventReceiverOrchestrator.cs +++ b/TUnit.Engine/Services/EventReceiverOrchestrator.cs @@ -12,7 +12,6 @@ namespace TUnit.Engine.Services; -/// Optimized event receiver orchestrator with fast-path checks, batching, and lifecycle tracking internal sealed class EventReceiverOrchestrator : IDisposable { private readonly EventReceiverRegistry _registry = new(); @@ -43,23 +42,20 @@ public EventReceiverOrchestrator(TUnitFrameworkLogger logger, TrackableObjectGra public void RegisterReceivers(TestContext context, CancellationToken cancellationToken) { - var eligibleObjects = context.GetEligibleEventObjects().ToArray(); - var objectsToRegister = new List(); - foreach (var obj in eligibleObjects) + foreach (var obj in context.GetEligibleEventObjects()) { if (_initializedObjects.Add(obj)) // Add returns false if already present { // For First event receivers, only register one instance per type - var objType = obj.GetType(); bool isFirstEventReceiver = obj is IFirstTestInTestSessionEventReceiver || obj is IFirstTestInAssemblyEventReceiver || obj is IFirstTestInClassEventReceiver; if (isFirstEventReceiver) { - if (_registeredFirstEventReceiverTypes.Add(objType)) + if (_registeredFirstEventReceiverTypes.Add(obj.GetType())) { // First instance of this type, register it objectsToRegister.Add(obj); @@ -97,24 +93,14 @@ public async ValueTask InvokeTestStartEventReceiversAsync(TestContext context, C private async ValueTask InvokeTestStartEventReceiversCore(TestContext context, CancellationToken cancellationToken) { - // Filter scoped attributes - FilterScopedAttributes will materialize the collection var filteredReceivers = ScopedAttributeFilter.FilterScopedAttributes( context.GetEligibleEventObjects() .OfType() .OrderBy(static r => r.Order)); - // Batch invocation for multiple receivers - if (filteredReceivers.Count > 3) - { - await InvokeBatchedAsync(filteredReceivers.ToArray(), r => r.OnTestStart(context), cancellationToken); - } - else + foreach (var receiver in filteredReceivers) { - // Sequential for small counts - foreach (var receiver in filteredReceivers) - { - await receiver.OnTestStart(context); - } + await receiver.OnTestStart(context); } } @@ -178,9 +164,7 @@ private async ValueTask InvokeTestSkippedEventReceiversCore(TestContext context, public async ValueTask InvokeTestDiscoveryEventReceiversAsync(TestContext context, DiscoveredTestContext discoveredContext, CancellationToken cancellationToken) { var eventReceivers = context.GetEligibleEventObjects() - .OfType() - .OrderBy(static r => r.Order) - .ToList(); + .OfType(); // Filter scoped attributes to ensure only the highest priority one of each type is invoked var filteredReceivers = ScopedAttributeFilter.FilterScopedAttributes(eventReceivers); @@ -214,20 +198,19 @@ public async ValueTask InvokeHookRegistrationEventReceiversAsync(HookRegisteredC // First/Last event methods with fast-path checks [MethodImpl(MethodImplOptions.AggressiveInlining)] - public async ValueTask InvokeFirstTestInSessionEventReceiversAsync( + public ValueTask InvokeFirstTestInSessionEventReceiversAsync( TestContext context, TestSessionContext sessionContext, CancellationToken cancellationToken) { if (!_registry.HasFirstTestInSessionReceivers()) { - return; + return default; } - // Use GetOrAdd to ensure exactly one task is created per session and all tests await it var task = _firstTestInSessionTasks.GetOrAdd("session", _ => InvokeFirstTestInSessionEventReceiversCoreAsync(context, sessionContext, cancellationToken)); - await task; + return new ValueTask(task); } private async Task InvokeFirstTestInSessionEventReceiversCoreAsync( @@ -244,21 +227,20 @@ private async Task InvokeFirstTestInSessionEventReceiversCoreAsync( } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public async ValueTask InvokeFirstTestInAssemblyEventReceiversAsync( + public ValueTask InvokeFirstTestInAssemblyEventReceiversAsync( TestContext context, AssemblyHookContext assemblyContext, CancellationToken cancellationToken) { if (!_registry.HasFirstTestInAssemblyReceivers()) { - return; + return default; } var assemblyName = assemblyContext.Assembly.GetName().FullName ?? ""; - // Use GetOrAdd to ensure exactly one task is created per assembly and all tests await it var task = _firstTestInAssemblyTasks.GetOrAdd(assemblyName, _ => InvokeFirstTestInAssemblyEventReceiversCoreAsync(context, assemblyContext, cancellationToken)); - await task; + return new ValueTask(task); } private async Task InvokeFirstTestInAssemblyEventReceiversCoreAsync( @@ -275,21 +257,20 @@ private async Task InvokeFirstTestInAssemblyEventReceiversCoreAsync( } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public async ValueTask InvokeFirstTestInClassEventReceiversAsync( + public ValueTask InvokeFirstTestInClassEventReceiversAsync( TestContext context, ClassHookContext classContext, CancellationToken cancellationToken) { if (!_registry.HasFirstTestInClassReceivers()) { - return; + return default; } var classType = classContext.ClassType; - // Use GetOrAdd to ensure exactly one task is created per class and all tests await it var task = _firstTestInClassTasks.GetOrAdd(classType, _ => InvokeFirstTestInClassEventReceiversCoreAsync(context, classContext, cancellationToken)); - await task; + return new ValueTask(task); } private async Task InvokeFirstTestInClassEventReceiversCoreAsync( @@ -430,7 +411,7 @@ private async ValueTask InvokeLastTestInClassEventReceiversCore( /// public void InitializeTestCounts(IEnumerable allTestContexts) { - var contexts = allTestContexts.ToList(); + var contexts = allTestContexts as IList ?? allTestContexts.ToList(); _sessionTestCount = contexts.Count; // Clear first-event tracking to ensure clean state for each test execution @@ -441,51 +422,16 @@ public void InitializeTestCounts(IEnumerable allTestContexts) foreach (var group in contexts.GroupBy(c => c.ClassContext.AssemblyContext.Assembly.GetName().FullName)) { var counter = _assemblyTestCounts.GetOrAdd(group.Key, static _ => new Counter()); - - for (var i = 0; i < group.Count(); i++) - { - counter.Increment(); - } + counter.Add(group.Count()); } foreach (var group in contexts.GroupBy(c => c.ClassContext.ClassType)) { var counter = _classTestCounts.GetOrAdd(group.Key, static _ => new Counter()); - - for (var i = 0; i < group.Count(); i++) - { - counter.Increment(); - } + counter.Add(group.Count()); } } - /// - /// Batch multiple receiver invocations - /// - private async ValueTask InvokeBatchedAsync( - T[] receivers, - Func invoker, - CancellationToken cancellationToken) where T : IEventReceiver - { - // Parallelize for larger counts - var tasks = new Task[receivers.Length]; - for (var i = 0; i < receivers.Length; i++) - { - var receiver = receivers[i]; - tasks[i] = InvokeReceiverAsync(receiver, invoker, cancellationToken); - } - - await Task.WhenAll(tasks); - } - - private async Task InvokeReceiverAsync( - T receiver, - Func invoker, - CancellationToken cancellationToken) where T : IEventReceiver - { - await invoker(receiver); - } - public void Dispose() { _registry.Dispose(); diff --git a/TUnit.Engine/Services/HookCollectionService.cs b/TUnit.Engine/Services/HookCollectionService.cs index 902f7ed057..eec9d45b23 100644 --- a/TUnit.Engine/Services/HookCollectionService.cs +++ b/TUnit.Engine/Services/HookCollectionService.cs @@ -17,6 +17,9 @@ internal sealed class HookCollectionService : IHookCollectionService private readonly ConcurrentDictionary>> _beforeAssemblyHooksCache = new(); private readonly ConcurrentDictionary>> _afterAssemblyHooksCache = new(); + // Cache for GetGenericTypeDefinition() calls to avoid repeated reflection + private static readonly ConcurrentDictionary _genericTypeDefinitionCache = new(); + // Pre-computed global hooks (computed once at initialization) private IReadOnlyList>? _beforeEveryTestHooks; private IReadOnlyList>? _afterEveryTestHooks; @@ -37,6 +40,11 @@ public HookCollectionService(EventReceiverOrchestrator eventReceiverOrchestrator _eventReceiverOrchestrator = eventReceiverOrchestrator; } + private static Type GetCachedGenericTypeDefinition(Type type) + { + return _genericTypeDefinitionCache.GetOrAdd(type, t => t.GetGenericTypeDefinition()); + } + public async ValueTask InitializeAsync() { // Pre-compute all global hooks that don't depend on specific types/assemblies @@ -54,7 +62,7 @@ public async ValueTask InitializeAsync() private async Task>> BuildGlobalBeforeEveryTestHooksAsync() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.BeforeEveryTestHooks.Count); foreach (var hook in Sources.BeforeEveryTestHooks) { @@ -71,7 +79,7 @@ private async Task>> Bu private async Task>> BuildGlobalAfterEveryTestHooksAsync() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.AfterEveryTestHooks.Count); foreach (var hook in Sources.AfterEveryTestHooks) { @@ -88,7 +96,7 @@ private async Task>> Bu private IReadOnlyList> BuildGlobalBeforeTestSessionHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.BeforeTestSessionHooks.Count); foreach (var hook in Sources.BeforeTestSessionHooks) { @@ -105,7 +113,7 @@ private IReadOnlyList> BuildGl private IReadOnlyList> BuildGlobalAfterTestSessionHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.AfterTestSessionHooks.Count); foreach (var hook in Sources.AfterTestSessionHooks) { @@ -122,7 +130,7 @@ private IReadOnlyList> BuildGl private IReadOnlyList> BuildGlobalBeforeTestDiscoveryHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.BeforeTestDiscoveryHooks.Count); foreach (var hook in Sources.BeforeTestDiscoveryHooks) { @@ -139,7 +147,7 @@ private IReadOnlyList> private IReadOnlyList> BuildGlobalAfterTestDiscoveryHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.AfterTestDiscoveryHooks.Count); foreach (var hook in Sources.AfterTestDiscoveryHooks) { @@ -156,7 +164,7 @@ private IReadOnlyList> Build private IReadOnlyList> BuildGlobalBeforeEveryClassHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.BeforeEveryClassHooks.Count); foreach (var hook in Sources.BeforeEveryClassHooks) { @@ -173,7 +181,7 @@ private IReadOnlyList> BuildGlob private IReadOnlyList> BuildGlobalAfterEveryClassHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.AfterEveryClassHooks.Count); foreach (var hook in Sources.AfterEveryClassHooks) { @@ -190,7 +198,7 @@ private IReadOnlyList> BuildGlob private IReadOnlyList> BuildGlobalBeforeEveryAssemblyHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.BeforeEveryAssemblyHooks.Count); foreach (var hook in Sources.BeforeEveryAssemblyHooks) { @@ -207,7 +215,7 @@ private IReadOnlyList> BuildG private IReadOnlyList> BuildGlobalAfterEveryAssemblyHooks() { - var allHooks = new List<(int order, int registrationIndex, Func hook)>(); + var allHooks = new List<(int order, int registrationIndex, Func hook)>(Sources.AfterEveryAssemblyHooks.Count); foreach (var hook in Sources.AfterEveryAssemblyHooks) { @@ -305,7 +313,7 @@ private async Task>> Bu // Also check the open generic type definition for generic types if (currentType is { IsGenericType: true, IsGenericTypeDefinition: false }) { - var openGenericType = currentType.GetGenericTypeDefinition(); + var openGenericType = GetCachedGenericTypeDefinition(currentType); if (Sources.BeforeTestHooks.TryGetValue(openGenericType, out var openTypeHooks)) { foreach (var hook in openTypeHooks) @@ -372,7 +380,7 @@ private async Task>> Bu // Also check the open generic type definition for generic types if (currentType is { IsGenericType: true, IsGenericTypeDefinition: false }) { - var openGenericType = currentType.GetGenericTypeDefinition(); + var openGenericType = GetCachedGenericTypeDefinition(currentType); if (Sources.AfterTestHooks.TryGetValue(openGenericType, out var openTypeHooks)) { foreach (var hook in openTypeHooks) @@ -438,7 +446,7 @@ public ValueTask>> // Also check the open generic type definition for generic types if (currentType is { IsGenericType: true, IsGenericTypeDefinition: false }) { - var openGenericType = currentType.GetGenericTypeDefinition(); + var openGenericType = GetCachedGenericTypeDefinition(currentType); if (Sources.BeforeClassHooks.TryGetValue(openGenericType, out var openTypeHooks)) { foreach (var hook in openTypeHooks) @@ -495,7 +503,7 @@ public ValueTask>> // Also check the open generic type definition for generic types if (currentType is { IsGenericType: true, IsGenericTypeDefinition: false }) { - var openGenericType = currentType.GetGenericTypeDefinition(); + var openGenericType = GetCachedGenericTypeDefinition(currentType); if (Sources.AfterClassHooks.TryGetValue(openGenericType, out var openTypeHooks)) { foreach (var hook in openTypeHooks) @@ -530,15 +538,17 @@ public ValueTask { - var allHooks = new List<(int order, Func hook)>(); + if (!Sources.BeforeAssemblyHooks.TryGetValue(asm, out var assemblyHooks)) + { + return []; + } + + var allHooks = new List<(int order, Func hook)>(assemblyHooks.Count); - if (Sources.BeforeAssemblyHooks.TryGetValue(asm, out var assemblyHooks)) + foreach (var hook in assemblyHooks) { - foreach (var hook in assemblyHooks) - { - var hookFunc = CreateAssemblyHookDelegate(hook); - allHooks.Add((hook.Order, hookFunc)); - } + var hookFunc = CreateAssemblyHookDelegate(hook); + allHooks.Add((hook.Order, hookFunc)); } return allHooks @@ -554,15 +564,17 @@ public ValueTask { - var allHooks = new List<(int order, Func hook)>(); + if (!Sources.AfterAssemblyHooks.TryGetValue(asm, out var assemblyHooks)) + { + return []; + } - if (Sources.AfterAssemblyHooks.TryGetValue(asm, out var assemblyHooks)) + var allHooks = new List<(int order, Func hook)>(assemblyHooks.Count); + + foreach (var hook in assemblyHooks) { - foreach (var hook in assemblyHooks) - { - var hookFunc = CreateAssemblyHookDelegate(hook); - allHooks.Add((hook.Order, hookFunc)); - } + var hookFunc = CreateAssemblyHookDelegate(hook); + allHooks.Add((hook.Order, hookFunc)); } return allHooks @@ -621,14 +633,41 @@ private async Task> CreateInstanceHoo return async (context, cancellationToken) => { - var timeoutAction = HookTimeoutHelper.CreateTimeoutHookAction( - (ctx, ct) => hook.ExecuteAsync(ctx, ct), - context, - hook.Timeout, - hook.Name, - cancellationToken); + // Check at EXECUTION time if a custom executor should be used + if (context.CustomHookExecutor != null) + { + // BYPASS the hook's default executor and call the custom executor directly + var customExecutor = context.CustomHookExecutor; - await timeoutAction(); + // Skip skipped test instances + if (context.TestDetails.ClassInstance is SkippedTestInstance) + { + return; + } + + if (context.TestDetails.ClassInstance is PlaceholderInstance) + { + throw new InvalidOperationException($"Cannot execute instance hook {hook.Name} because the test instance has not been created yet. This is likely a framework bug."); + } + + await customExecutor.ExecuteBeforeTestHook( + hook.MethodInfo, + context, + () => hook.Body!.Invoke(context.TestDetails.ClassInstance, context, cancellationToken) + ); + } + else + { + // No custom executor, use normal execution path + var timeoutAction = HookTimeoutHelper.CreateTimeoutHookAction( + (ctx, ct) => hook.ExecuteAsync(ctx, ct), + context, + hook.Timeout, + hook.Name, + cancellationToken); + + await timeoutAction(); + } }; } diff --git a/TUnit.Engine/Services/HookExecutor.cs b/TUnit.Engine/Services/HookExecutor.cs index a30eb270ef..b189f1ee01 100644 --- a/TUnit.Engine/Services/HookExecutor.cs +++ b/TUnit.Engine/Services/HookExecutor.cs @@ -28,10 +28,15 @@ public HookExecutor( _eventReceiverOrchestrator = eventReceiverOrchestrator; } - public async Task ExecuteBeforeTestSessionHooksAsync(CancellationToken cancellationToken) + public async ValueTask ExecuteBeforeTestSessionHooksAsync(CancellationToken cancellationToken) { var hooks = await _hookCollectionService.CollectBeforeTestSessionHooksAsync().ConfigureAwait(false); + if (hooks.Count == 0) + { + return; + } + foreach (var hook in hooks) { try @@ -48,10 +53,16 @@ public async Task ExecuteBeforeTestSessionHooksAsync(CancellationToken cancellat } } - public async Task> ExecuteAfterTestSessionHooksAsync(CancellationToken cancellationToken) + public async ValueTask> ExecuteAfterTestSessionHooksAsync(CancellationToken cancellationToken) { var exceptions = new List(); var hooks = await _hookCollectionService.CollectAfterTestSessionHooksAsync().ConfigureAwait(false); + + if (hooks.Count == 0) + { + return exceptions; + } + foreach (var hook in hooks) { try @@ -70,9 +81,15 @@ public async Task> ExecuteAfterTestSessionHooksAsync(Cancellatio return exceptions; } - public async Task ExecuteBeforeAssemblyHooksAsync(Assembly assembly, CancellationToken cancellationToken) + public async ValueTask ExecuteBeforeAssemblyHooksAsync(Assembly assembly, CancellationToken cancellationToken) { var hooks = await _hookCollectionService.CollectBeforeAssemblyHooksAsync(assembly).ConfigureAwait(false); + + if (hooks.Count == 0) + { + return; + } + foreach (var hook in hooks) { try @@ -88,10 +105,16 @@ public async Task ExecuteBeforeAssemblyHooksAsync(Assembly assembly, Cancellatio } } - public async Task> ExecuteAfterAssemblyHooksAsync(Assembly assembly, CancellationToken cancellationToken) + public async ValueTask> ExecuteAfterAssemblyHooksAsync(Assembly assembly, CancellationToken cancellationToken) { var exceptions = new List(); var hooks = await _hookCollectionService.CollectAfterAssemblyHooksAsync(assembly).ConfigureAwait(false); + + if (hooks.Count == 0) + { + return exceptions; + } + foreach (var hook in hooks) { try @@ -111,11 +134,17 @@ public async Task> ExecuteAfterAssemblyHooksAsync(Assembly assem return exceptions; } - public async Task ExecuteBeforeClassHooksAsync( + public async ValueTask ExecuteBeforeClassHooksAsync( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type testClass, CancellationToken cancellationToken) { var hooks = await _hookCollectionService.CollectBeforeClassHooksAsync(testClass).ConfigureAwait(false); + + if (hooks.Count == 0) + { + return; + } + foreach (var hook in hooks) { try @@ -131,12 +160,18 @@ public async Task ExecuteBeforeClassHooksAsync( } } - public async Task> ExecuteAfterClassHooksAsync( + public async ValueTask> ExecuteAfterClassHooksAsync( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicMethods)] Type testClass, CancellationToken cancellationToken) { var exceptions = new List(); var hooks = await _hookCollectionService.CollectAfterClassHooksAsync(testClass).ConfigureAwait(false); + + if (hooks.Count == 0) + { + return exceptions; + } + foreach (var hook in hooks) { try @@ -156,79 +191,101 @@ public async Task> ExecuteAfterClassHooksAsync( return exceptions; } - public async Task ExecuteBeforeTestHooksAsync(AbstractExecutableTest test, CancellationToken cancellationToken) + public async ValueTask ExecuteBeforeTestHooksAsync(AbstractExecutableTest test, CancellationToken cancellationToken) { var testClassType = test.Metadata.TestClassType; // Execute BeforeEvery(Test) hooks first (global test hooks run before specific hooks) var beforeEveryTestHooks = await _hookCollectionService.CollectBeforeEveryTestHooksAsync(testClassType).ConfigureAwait(false); - foreach (var hook in beforeEveryTestHooks) + + if (beforeEveryTestHooks.Count > 0) { - try + foreach (var hook in beforeEveryTestHooks) { - test.Context.RestoreExecutionContext(); - await hook(test.Context, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) - { - throw new BeforeTestException("BeforeEveryTest hook failed", ex); + try + { + test.Context.RestoreExecutionContext(); + await hook(test.Context, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + throw new BeforeTestException("BeforeEveryTest hook failed", ex); + } } } // Execute Before(Test) hooks after BeforeEvery hooks var beforeTestHooks = await _hookCollectionService.CollectBeforeTestHooksAsync(testClassType).ConfigureAwait(false); - foreach (var hook in beforeTestHooks) + + if (beforeTestHooks.Count > 0) { - try - { - test.Context.RestoreExecutionContext(); - await hook(test.Context, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) + foreach (var hook in beforeTestHooks) { - throw new BeforeTestException("BeforeTest hook failed", ex); + try + { + test.Context.RestoreExecutionContext(); + await hook(test.Context, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + throw new BeforeTestException("BeforeTest hook failed", ex); + } } } } - public async Task ExecuteAfterTestHooksAsync(AbstractExecutableTest test, CancellationToken cancellationToken) + public async ValueTask ExecuteAfterTestHooksAsync(AbstractExecutableTest test, CancellationToken cancellationToken) { var testClassType = test.Metadata.TestClassType; // Execute After(Test) hooks first (specific hooks run before global hooks for cleanup) var afterTestHooks = await _hookCollectionService.CollectAfterTestHooksAsync(testClassType).ConfigureAwait(false); - foreach (var hook in afterTestHooks) + + if (afterTestHooks.Count > 0) { - try - { - test.Context.RestoreExecutionContext(); - await hook(test.Context, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) + foreach (var hook in afterTestHooks) { - throw new AfterTestException("AfterTest hook failed", ex); + try + { + test.Context.RestoreExecutionContext(); + await hook(test.Context, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + throw new AfterTestException("AfterTest hook failed", ex); + } } } // Execute AfterEvery(Test) hooks after After hooks (global test hooks run last for cleanup) var afterEveryTestHooks = await _hookCollectionService.CollectAfterEveryTestHooksAsync(testClassType).ConfigureAwait(false); - foreach (var hook in afterEveryTestHooks) + + if (afterEveryTestHooks.Count > 0) { - try - { - test.Context.RestoreExecutionContext(); - await hook(test.Context, cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) + foreach (var hook in afterEveryTestHooks) { - throw new AfterTestException("AfterEveryTest hook failed", ex); + try + { + test.Context.RestoreExecutionContext(); + await hook(test.Context, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + throw new AfterTestException("AfterEveryTest hook failed", ex); + } } } } - public async Task ExecuteBeforeTestDiscoveryHooksAsync(CancellationToken cancellationToken) + public async ValueTask ExecuteBeforeTestDiscoveryHooksAsync(CancellationToken cancellationToken) { var hooks = await _hookCollectionService.CollectBeforeTestDiscoveryHooksAsync().ConfigureAwait(false); + + if (hooks.Count == 0) + { + return; + } + foreach (var hook in hooks) { try @@ -243,9 +300,15 @@ public async Task ExecuteBeforeTestDiscoveryHooksAsync(CancellationToken cancell } } - public async Task ExecuteAfterTestDiscoveryHooksAsync(CancellationToken cancellationToken) + public async ValueTask ExecuteAfterTestDiscoveryHooksAsync(CancellationToken cancellationToken) { var hooks = await _hookCollectionService.CollectAfterTestDiscoveryHooksAsync().ConfigureAwait(false); + + if (hooks.Count == 0) + { + return; + } + foreach (var hook in hooks) { try diff --git a/TUnit.Engine/Services/PropertyInitializationPipeline.cs b/TUnit.Engine/Services/PropertyInitializationPipeline.cs index f819acfdb9..3c56e7e56c 100644 --- a/TUnit.Engine/Services/PropertyInitializationPipeline.cs +++ b/TUnit.Engine/Services/PropertyInitializationPipeline.cs @@ -17,15 +17,15 @@ internal sealed class PropertyInitializationPipeline public PropertyInitializationPipeline(DataSourceInitializer dataSourceInitializer, ObjectRegistrationService objectRegistrationService) { _dataSourceInitializer = dataSourceInitializer ?? throw new ArgumentNullException(nameof(dataSourceInitializer)); - _strategies = new List - { + _strategies = + [ new SourceGeneratedPropertyStrategy(dataSourceInitializer, objectRegistrationService), new ReflectionPropertyStrategy(dataSourceInitializer, objectRegistrationService), new NestedPropertyStrategy(dataSourceInitializer, objectRegistrationService) - }; + ]; - _beforeSteps = new List>(); - _afterSteps = new List>(); + _beforeSteps = []; + _afterSteps = []; } /// @@ -62,7 +62,6 @@ public async Task ExecuteAsync(PropertyInitializationContext context) { try { - // Execute before steps foreach (var step in _beforeSteps) { await step(context); @@ -88,7 +87,6 @@ public async Task ExecuteAsync(PropertyInitializationContext context) $"of type '{context.PropertyType.Name}' on '{context.Instance.GetType().Name}'"); } - // Execute after steps foreach (var step in _afterSteps) { await step(context); diff --git a/TUnit.Engine/Services/ReflectionStaticPropertyInitializer.cs b/TUnit.Engine/Services/ReflectionStaticPropertyInitializer.cs index fa1bab8b5b..204fca6798 100644 --- a/TUnit.Engine/Services/ReflectionStaticPropertyInitializer.cs +++ b/TUnit.Engine/Services/ReflectionStaticPropertyInitializer.cs @@ -25,14 +25,12 @@ public async Task InitializeAsync(CancellationToken cancellationToken) { try { - // Execute all registered global initializers from source generation while (Sources.GlobalInitializers.TryDequeue(out var initializer)) { cancellationToken.ThrowIfCancellationRequested(); await initializer(); } - // Additionally, initialize static properties discovered via reflection await StaticPropertyReflectionInitializer.InitializeAllStaticPropertiesAsync(); } catch (Exception ex) diff --git a/TUnit.Engine/Services/SourceGenStaticPropertyInitializer.cs b/TUnit.Engine/Services/SourceGenStaticPropertyInitializer.cs index eb24ffb7fd..542fdaf046 100644 --- a/TUnit.Engine/Services/SourceGenStaticPropertyInitializer.cs +++ b/TUnit.Engine/Services/SourceGenStaticPropertyInitializer.cs @@ -20,7 +20,6 @@ public async Task InitializeAsync(CancellationToken cancellationToken) { try { - // Execute all registered global initializers from source generation while (Sources.GlobalInitializers.TryDequeue(out var initializer)) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/TUnit.Engine/Services/StaticPropertyHandler.cs b/TUnit.Engine/Services/StaticPropertyHandler.cs index e46a44eda7..c860b0524a 100644 --- a/TUnit.Engine/Services/StaticPropertyHandler.cs +++ b/TUnit.Engine/Services/StaticPropertyHandler.cs @@ -46,7 +46,6 @@ public async Task InitializeStaticPropertiesAsync(CancellationToken cancellation { try { - // Call the generated initializer var value = await property.InitializerAsync(); if (value != null) diff --git a/TUnit.Engine/Services/TestArgumentRegistrationService.cs b/TUnit.Engine/Services/TestArgumentRegistrationService.cs index 5698233ef3..d92139a881 100644 --- a/TUnit.Engine/Services/TestArgumentRegistrationService.cs +++ b/TUnit.Engine/Services/TestArgumentRegistrationService.cs @@ -139,24 +139,21 @@ await _objectRegistrationService.RegisterObjectAsync( } catch (Exception ex) { - // Capture the exception for this property - mark the test as failed + // Capture the exception for this property and re-throw + // The test building process will handle marking it as failed var exceptionMessage = $"Failed to generate data for property '{metadata.PropertyName}': {ex.Message}"; var propertyException = new InvalidOperationException(exceptionMessage, ex); - - // Mark the test as failed immediately during registration - testContext.InternalExecutableTest.SetResult(TestState.Failed, propertyException); - return; // Stop processing further properties for this test + throw propertyException; } } } catch (Exception ex) { - // Capture any top-level exceptions (e.g., getting property source) + // Capture any top-level exceptions (e.g., getting property source) and re-throw + // The test building process will handle marking it as failed var exceptionMessage = $"Failed to register properties for test '{testContext.TestDetails.TestName}': {ex.Message}"; var registrationException = new InvalidOperationException(exceptionMessage, ex); - - // Mark the test as failed immediately during registration - testContext.InternalExecutableTest.SetResult(TestState.Failed, registrationException); + throw registrationException; } } } diff --git a/TUnit.Engine/Services/TestExecution/HashSetPool.cs b/TUnit.Engine/Services/TestExecution/HashSetPool.cs new file mode 100644 index 0000000000..dba17daaf6 --- /dev/null +++ b/TUnit.Engine/Services/TestExecution/HashSetPool.cs @@ -0,0 +1,55 @@ +namespace TUnit.Engine.Services.TestExecution; + +/// +/// Thread-safe object pool for HashSet instances used during test execution. +/// Single Responsibility: Managing pooled HashSet objects to reduce allocations. +/// +internal sealed class HashSetPool +{ + private readonly Dictionary _pools = new(); + private readonly object _lock = new(); + + public HashSet Rent() + { + var type = typeof(T); + + lock (_lock) + { + if (!_pools.TryGetValue(type, out var poolObj)) + { + poolObj = new Stack>(); + _pools[type] = poolObj; + } + + var pool = (Stack>)poolObj; + + if (pool.Count > 0) + { + var set = pool.Pop(); + set.Clear(); + return set; + } + } + + return []; + } + + public void Return(HashSet set) + { + var type = typeof(T); + + lock (_lock) + { + set.Clear(); + + if (!_pools.TryGetValue(type, out var poolObj)) + { + poolObj = new Stack>(); + _pools[type] = poolObj; + } + + var pool = (Stack>)poolObj; + pool.Push(set); + } + } +} diff --git a/TUnit.Engine/Services/TestExecution/TestCoordinator.cs b/TUnit.Engine/Services/TestExecution/TestCoordinator.cs index 692bcf8481..928649a003 100644 --- a/TUnit.Engine/Services/TestExecution/TestCoordinator.cs +++ b/TUnit.Engine/Services/TestExecution/TestCoordinator.cs @@ -23,6 +23,7 @@ internal sealed class TestCoordinator : ITestCoordinator private readonly ObjectTracker _objectTracker; private readonly TUnitFrameworkLogger _logger; private readonly EventReceiverOrchestrator _eventReceiverOrchestrator; + private readonly HashSetPool _hashSetPool; public TestCoordinator( TestExecutionGuard executionGuard, @@ -33,7 +34,8 @@ public TestCoordinator( TestInitializer testInitializer, ObjectTracker objectTracker, TUnitFrameworkLogger logger, - EventReceiverOrchestrator eventReceiverOrchestrator) + EventReceiverOrchestrator eventReceiverOrchestrator, + HashSetPool hashSetPool) { _executionGuard = executionGuard; _stateManager = stateManager; @@ -44,6 +46,7 @@ public TestCoordinator( _objectTracker = objectTracker; _logger = logger; _eventReceiverOrchestrator = eventReceiverOrchestrator; + _hashSetPool = hashSetPool; } public async Task ExecuteTestAsync(AbstractExecutableTest test, CancellationToken cancellationToken) @@ -68,12 +71,21 @@ private async Task ExecuteTestInternalAsync(AbstractExecutableTest test, Cancell TestContext.Current = test.Context; - var allDependencies = new HashSet(); - CollectAllDependencies(test, allDependencies, new HashSet()); + var allDependencies = _hashSetPool.Rent(); + var visited = _hashSetPool.Rent(); + try + { + CollectAllDependencies(test, allDependencies, visited); - foreach (var dependency in allDependencies) + foreach (var dependency in allDependencies) + { + test.Context.Dependencies.Add(dependency); + } + } + finally { - test.Context.Dependencies.Add(dependency); + _hashSetPool.Return(allDependencies); + _hashSetPool.Return(visited); } // Ensure TestSession hooks run before creating test instances @@ -84,16 +96,17 @@ await RetryHelper.ExecuteWithRetry(test.Context, async () => { test.Context.TestDetails.ClassInstance = await test.CreateInstanceAsync(); + // Invalidate cached eligible event objects since ClassInstance changed + test.Context.CachedEligibleEventObjects = null; + // Check if this test should be skipped (after creating instance) if (test.Context.TestDetails.ClassInstance is SkippedTestInstance || !string.IsNullOrEmpty(test.Context.SkipReason)) { await _stateManager.MarkSkippedAsync(test, test.Context.SkipReason ?? "Test was skipped"); - // Invoke skipped event receivers await _eventReceiverOrchestrator.InvokeTestSkippedEventReceiversAsync(test.Context, cancellationToken); - // Invoke test end event receivers for skipped tests await _eventReceiverOrchestrator.InvokeTestEndEventReceiversAsync(test.Context, cancellationToken); return; @@ -111,7 +124,7 @@ await RetryHelper.ExecuteWithRetry(test.Context, async () => // This ensures each retry gets a fresh instance if (test.Context.Events.OnDispose?.InvocationList != null) { - foreach (var invocation in test.Context.Events.OnDispose.InvocationList.OrderBy(x => x.Order)) + foreach (var invocation in test.Context.Events.OnDispose.InvocationList) { try { diff --git a/TUnit.Engine/Services/TestExecution/TestStateManager.cs b/TUnit.Engine/Services/TestExecution/TestStateManager.cs index 3cf458ef3e..31ad555a33 100644 --- a/TUnit.Engine/Services/TestExecution/TestStateManager.cs +++ b/TUnit.Engine/Services/TestExecution/TestStateManager.cs @@ -18,18 +18,20 @@ public Task MarkRunningAsync(AbstractExecutableTest test) public Task MarkCompletedAsync(AbstractExecutableTest test) { + var now = DateTimeOffset.UtcNow; + test.Result ??= new TestResult { State = TestState.Passed, Start = test.StartTime, - End = DateTimeOffset.UtcNow, - Duration = DateTimeOffset.UtcNow - test.StartTime.GetValueOrDefault(), + End = now, + Duration = now - test.StartTime.GetValueOrDefault(), Exception = null, ComputerName = Environment.MachineName }; test.State = test.Result.State; - test.EndTime = DateTimeOffset.UtcNow; + test.EndTime = now; return Task.CompletedTask; } @@ -63,14 +65,15 @@ public Task MarkFailedAsync(AbstractExecutableTest test, Exception exception) public Task MarkSkippedAsync(AbstractExecutableTest test, string reason) { test.State = TestState.Skipped; + var now = DateTimeOffset.UtcNow; // Ensure StartTime is set if it wasn't already if (!test.StartTime.HasValue) { - test.StartTime = DateTimeOffset.UtcNow; + test.StartTime = now; } - test.EndTime = DateTimeOffset.UtcNow; + test.EndTime = now; test.Result = new TestResult { State = TestState.Skipped, diff --git a/TUnit.Engine/Services/TestFilterService.cs b/TUnit.Engine/Services/TestFilterService.cs index 7854b9f9c1..af261cd7e9 100644 --- a/TUnit.Engine/Services/TestFilterService.cs +++ b/TUnit.Engine/Services/TestFilterService.cs @@ -23,8 +23,10 @@ public IReadOnlyCollection FilterTests(ITestExecutionFil logger.LogTrace($"Test filter is: {testExecutionFilter.GetType().Name}"); - var filteredTests = new List(); - var filteredExplicitTests = new List(); + // Pre-allocate capacity to avoid resizing during filtering + var capacity = testNodes is ICollection col ? col.Count : 16; + var filteredTests = new List(capacity); + var filteredExplicitTests = new List(capacity / 4); // Estimate ~25% explicit tests foreach (var test in testNodes) { @@ -41,9 +43,9 @@ public IReadOnlyCollection FilterTests(ITestExecutionFil } } - if (filteredTests.Count > 0 && filteredExplicitTests.Count > 0) + if (filteredTests.Count > 0) { - logger.LogTrace($"Filter matched both explicit and non-explicit tests. Excluding {filteredExplicitTests.Count} explicit tests."); + logger.LogTrace($"Filter matched {filteredTests.Count} non-explicit tests. Excluding {filteredExplicitTests.Count} explicit tests."); return filteredTests; } @@ -70,7 +72,16 @@ private async Task RegisterTest(AbstractExecutableTest test) test.Context.InternalDiscoveredTest = discoveredTest; - await testArgumentRegistrationService.OnTestRegistered(registeredContext); + try + { + await testArgumentRegistrationService.OnTestRegistered(registeredContext); + } + catch (Exception ex) + { + // Mark the test as failed and skip further event receiver processing + test.SetResult(TestState.Failed, ex); + return; + } var eventObjects = test.Context.GetEligibleEventObjects(); @@ -115,6 +126,12 @@ public bool MatchesTest(ITestExecutionFilter? testExecutionFilter, AbstractExecu private string BuildPath(AbstractExecutableTest test) { + // Return cached path if available + if (test.CachedFilterPath != null) + { + return test.CachedFilterPath; + } + var metadata = test.Metadata; var classMetadata = test.Context.TestDetails.MethodMetadata.Class; @@ -124,6 +141,8 @@ private string BuildPath(AbstractExecutableTest test) var path = $"/{assemblyName}/{namespaceName}/{classTypeName}/{metadata.TestMethodName}"; + // Cache the path for future calls + test.CachedFilterPath = path; return path; } @@ -156,7 +175,16 @@ private bool UnhandledFilter(ITestExecutionFilter testExecutionFilter) private PropertyBag BuildPropertyBag(AbstractExecutableTest test) { - var properties = new List(); + // Return cached PropertyBag if available + if (test.CachedPropertyBag is PropertyBag cachedBag) + { + return cachedBag; + } + + // Pre-calculate capacity: 2 properties per category + custom properties + var categoryCount = test.Context.TestDetails.Categories.Count; + var customPropCount = test.Context.TestDetails.CustomProperties.Sum(p => p.Value.Count); + var properties = new List(categoryCount * 2 + customPropCount); foreach (var category in test.Context.TestDetails.Categories) { @@ -164,17 +192,26 @@ private PropertyBag BuildPropertyBag(AbstractExecutableTest test) properties.Add(new TestMetadataProperty("Category", category)); } + // Replace LINQ with manual loop for better performance in hot path foreach (var propertyEntry in test.Context.TestDetails.CustomProperties) { - properties.AddRange(propertyEntry.Value.Select(value => new TestMetadataProperty(propertyEntry.Key, value))); + foreach (var value in propertyEntry.Value) + { + properties.Add(new TestMetadataProperty(propertyEntry.Key, value)); + } } - return new PropertyBag(properties); + var propertyBag = new PropertyBag(properties); + + // Cache the PropertyBag for future calls + test.CachedPropertyBag = propertyBag; + + return propertyBag; } private bool IsExplicitTest(AbstractExecutableTest test) { - if (test.Context.TestDetails.Attributes.OfType().Any()) + if (test.Context.TestDetails.HasAttribute()) { return true; } @@ -185,7 +222,9 @@ private bool IsExplicitTest(AbstractExecutableTest test) private IReadOnlyCollection FilterOutExplicitTests(IReadOnlyCollection testNodes) { - var filteredTests = new List(); + // Pre-allocate assuming most tests are not explicit + var capacity = testNodes is ICollection col ? col.Count : testNodes.Count; + var filteredTests = new List(capacity); foreach (var test in testNodes) { diff --git a/TUnit.Engine/Services/TestFinder.cs b/TUnit.Engine/Services/TestFinder.cs index bf1e782825..74a1690e14 100644 --- a/TUnit.Engine/Services/TestFinder.cs +++ b/TUnit.Engine/Services/TestFinder.cs @@ -9,6 +9,8 @@ namespace TUnit.Engine.Services; internal class TestFinder : ITestFinder { private readonly TestDiscoveryService _discoveryService; + private Dictionary>? _testsByType; + private Dictionary<(Type ClassType, string TestName), List>? _testsByTypeAndName; public TestFinder(TestDiscoveryService discoveryService) { @@ -16,54 +18,95 @@ public TestFinder(TestDiscoveryService discoveryService) } /// - /// Gets all test contexts for the specified class type + /// Builds index dictionaries from cached tests for O(1) lookups /// - public IEnumerable GetTests(Type classType) + private void EnsureIndexesBuilt() { + if (_testsByType != null) + { + return; // Already built + } + var allTests = _discoveryService.GetCachedTestContexts(); + var testsByType = new Dictionary>(); + var testsByTypeAndName = new Dictionary<(Type, string), List>(); + foreach (var test in allTests) { - if (test.TestDetails?.ClassType == classType) + if (test.TestDetails?.ClassType == null) + { + continue; + } + + var classType = test.TestDetails.ClassType; + var testName = test.TestName; + + // Index by type + if (!testsByType.TryGetValue(classType, out var testsForType)) { - yield return test; + testsForType = []; + testsByType[classType] = testsForType; } + testsForType.Add(test); + + // Index by (type, name) + var key = (classType, testName); + if (!testsByTypeAndName.TryGetValue(key, out var testsForKey)) + { + testsForKey = []; + testsByTypeAndName[key] = testsForKey; + } + testsForKey.Add(test); + } + + _testsByType = testsByType; + _testsByTypeAndName = testsByTypeAndName; + } + + /// + /// Gets all test contexts for the specified class type + /// + public IEnumerable GetTests(Type classType) + { + EnsureIndexesBuilt(); + + if (_testsByType!.TryGetValue(classType, out var tests)) + { + return tests; } + + return []; } /// /// Gets test contexts by name and parameters /// - public TestContext[] GetTestsByNameAndParameters(string testName, IEnumerable methodParameterTypes, - Type classType, IEnumerable classParameterTypes, IEnumerable classArguments) + public TestContext[] GetTestsByNameAndParameters(string testName, IEnumerable? methodParameterTypes, + Type classType, IEnumerable? classParameterTypes, IEnumerable? classArguments) { - var paramTypes = methodParameterTypes?.ToArray() ?? []; - var classParamTypes = classParameterTypes?.ToArray() ?? []; + EnsureIndexesBuilt(); - var allTests = _discoveryService.GetCachedTestContexts(); - var results = new List(); + var paramTypes = methodParameterTypes as Type[] ?? methodParameterTypes?.ToArray() ?? []; + var classParamTypes = classParameterTypes as Type[] ?? classParameterTypes?.ToArray() ?? []; - // If no parameter types are specified, match by name and class type only - if (paramTypes.Length == 0 && classParamTypes.Length == 0) + // Use the (type, name) index for O(1) lookup instead of O(n) scan + var key = (classType, testName); + if (!_testsByTypeAndName!.TryGetValue(key, out var candidateTests)) { - foreach (var test in allTests) - { - if (test.TestName == testName && test.TestDetails?.ClassType == classType) - { - results.Add(test); - } - } - return results.ToArray(); + return []; } - // Match with parameter types - foreach (var test in allTests) + // If no parameter types are specified, return all matches + if (paramTypes.Length == 0 && classParamTypes.Length == 0) { - if (test.TestName != testName || test.TestDetails?.ClassType != classType) - { - continue; - } + return candidateTests.ToArray(); + } - var testParams = test.TestDetails.MethodMetadata.Parameters.ToArray(); + // Filter by parameter types + var results = new List(candidateTests.Count); + foreach (var test in candidateTests) + { + var testParams = test.TestDetails!.MethodMetadata.Parameters; var testParamTypes = new Type[testParams.Length]; for (int i = 0; i < testParams.Length; i++) { @@ -101,10 +144,23 @@ private bool ParameterTypesMatch(Type[]? testParamTypes, Type[] expectedParamTyp return true; } - private bool ClassParametersMatch(TestContext context, Type[] classParamTypes, IEnumerable classArguments) + private bool ClassParametersMatch(TestContext context, Type[] classParamTypes, IEnumerable? classArguments) { // For now, just check parameter count - var argCount = classArguments?.Count() ?? 0; + int argCount; + if (classArguments == null) + { + argCount = 0; + } + else if (classArguments is ICollection collection) + { + argCount = collection.Count; + } + else + { + argCount = classArguments.Count(); + } + var actualArgCount = context.TestDetails?.TestClassArguments?.Length ?? 0; return argCount == actualArgCount; } diff --git a/TUnit.Engine/Services/TestGroupingService.cs b/TUnit.Engine/Services/TestGroupingService.cs index bd1473130d..21eb1c045a 100644 --- a/TUnit.Engine/Services/TestGroupingService.cs +++ b/TUnit.Engine/Services/TestGroupingService.cs @@ -227,7 +227,6 @@ private static void ProcessNotInParallelConstraint( } else { - // Add test only once with all its constraint keys keyedNotInParallelList.Add((test, className, constraint.NotInParallelConstraintKeys, testPriority)); } } @@ -261,7 +260,7 @@ private static void ProcessCombinedConstraints( { if (!constrainedGroups.TryGetValue(parallelGroup.Group, out var group)) { - group = (new List(), new List<(AbstractExecutableTest, string, IReadOnlyList, TestPriority)>()); + group = ([], []); constrainedGroups[parallelGroup.Group] = group; } diff --git a/TUnit.Engine/Services/TestIdentifierService.cs b/TUnit.Engine/Services/TestIdentifierService.cs index 84ab118e2f..102332affa 100644 --- a/TUnit.Engine/Services/TestIdentifierService.cs +++ b/TUnit.Engine/Services/TestIdentifierService.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Text; using TUnit.Core; using TUnit.Engine.Building; @@ -6,54 +7,73 @@ namespace TUnit.Engine.Services; internal static class TestIdentifierService { + private const int MaxStackAllocSize = 16; + public static string GenerateTestId(TestMetadata metadata, TestBuilder.TestData combination) { var methodMetadata = metadata.MethodMetadata; var classMetadata = methodMetadata.Class; - // Pre-size arrays to avoid LINQ chains and multiple enumerations var constructorParameters = classMetadata.Parameters; - var constructorParameterTypes = new Type[constructorParameters.Length]; - for (var i = 0; i < constructorParameters.Length; i++) - { - constructorParameterTypes[i] = constructorParameters[i].Type; - } - var methodParameters = methodMetadata.Parameters; - var methodParameterTypes = new Type[methodParameters.Length]; - for (var i = 0; i < methodParameters.Length; i++) + + // Use ArrayPool to avoid heap allocations for Type arrays + // Note: Cannot use stackalloc because Type is a managed reference type + var constructorParameterTypes = ArrayPool.Shared.Rent(constructorParameters.Length); + var methodParameterTypes = ArrayPool.Shared.Rent(methodParameters.Length); + + try { - methodParameterTypes[i] = methodParameters[i].Type; - } + // Fill arrays with actual types + for (var i = 0; i < constructorParameters.Length; i++) + { + constructorParameterTypes[i] = constructorParameters[i].Type; + } + + for (var i = 0; i < methodParameters.Length; i++) + { + methodParameterTypes[i] = methodParameters[i].Type; + } - var classTypeWithParameters = BuildTypeWithParameters(GetTypeNameWithGenerics(metadata.TestClassType), constructorParameterTypes); - var methodWithParameters = BuildTypeWithParameters(metadata.TestMethodName, methodParameterTypes); - - // Use StringBuilder for efficient string concatenation - var sb = new StringBuilder(256); // Pre-size for typical test ID length - sb.Append(methodMetadata.Class.Namespace) - .Append('.') - .Append(classTypeWithParameters) - .Append('.') - .Append(combination.ClassDataSourceAttributeIndex) - .Append('.') - .Append(combination.ClassDataLoopIndex) - .Append('.') - .Append(methodWithParameters) - .Append('.') - .Append(combination.MethodDataSourceAttributeIndex) - .Append('.') - .Append(combination.MethodDataLoopIndex) - .Append('.') - .Append(combination.RepeatIndex); - - // Add inheritance information to ensure uniqueness - if (combination.InheritanceDepth > 0) + var classTypeWithParameters = BuildTypeWithParameters( + GetTypeNameWithGenerics(metadata.TestClassType), + constructorParameterTypes.AsSpan(0, constructorParameters.Length)); + + var methodWithParameters = BuildTypeWithParameters( + metadata.TestMethodName, + methodParameterTypes.AsSpan(0, methodParameters.Length)); + + // Use StringBuilder for efficient string concatenation + var sb = new StringBuilder(256); // Pre-size for typical test ID length + sb.Append(methodMetadata.Class.Namespace) + .Append('.') + .Append(classTypeWithParameters) + .Append('.') + .Append(combination.ClassDataSourceAttributeIndex) + .Append('.') + .Append(combination.ClassDataLoopIndex) + .Append('.') + .Append(methodWithParameters) + .Append('.') + .Append(combination.MethodDataSourceAttributeIndex) + .Append('.') + .Append(combination.MethodDataLoopIndex) + .Append('.') + .Append(combination.RepeatIndex); + + // Add inheritance information to ensure uniqueness + if (combination.InheritanceDepth > 0) + { + sb.Append("_inherited").Append(combination.InheritanceDepth); + } + + return sb.ToString(); + } + finally { - sb.Append("_inherited").Append(combination.InheritanceDepth); + ArrayPool.Shared.Return(constructorParameterTypes); + ArrayPool.Shared.Return(methodParameterTypes); } - - return sb.ToString(); } public static string GenerateFailedTestId(TestMetadata metadata) @@ -67,44 +87,60 @@ public static string GenerateFailedTestId(TestMetadata metadata, TestDataCombina var methodMetadata = metadata.MethodMetadata; var classMetadata = methodMetadata.Class; - // Pre-size arrays to avoid LINQ chains and multiple enumerations var constructorParameters = classMetadata.Parameters; - var constructorParameterTypes = new Type[constructorParameters.Length]; - for (var i = 0; i < constructorParameters.Length; i++) - { - constructorParameterTypes[i] = constructorParameters[i].Type; - } - var methodParameters = methodMetadata.Parameters; - var methodParameterTypes = new Type[methodParameters.Length]; - for (var i = 0; i < methodParameters.Length; i++) + + // Use ArrayPool to avoid heap allocations for Type arrays + var constructorParameterTypes = ArrayPool.Shared.Rent(constructorParameters.Length); + var methodParameterTypes = ArrayPool.Shared.Rent(methodParameters.Length); + + try { - methodParameterTypes[i] = methodParameters[i].Type; - } + // Fill arrays with actual types + for (var i = 0; i < constructorParameters.Length; i++) + { + constructorParameterTypes[i] = constructorParameters[i].Type; + } - var classTypeWithParameters = BuildTypeWithParameters(GetTypeNameWithGenerics(metadata.TestClassType), constructorParameterTypes); - var methodWithParameters = BuildTypeWithParameters(metadata.TestMethodName, methodParameterTypes); - - // Use StringBuilder for efficient string concatenation - var sb = new StringBuilder(256); // Pre-size for typical test ID length - sb.Append(methodMetadata.Class.Namespace) - .Append('.') - .Append(classTypeWithParameters) - .Append('.') - .Append(combination.ClassDataSourceIndex) - .Append('.') - .Append(combination.ClassLoopIndex) - .Append('.') - .Append(methodWithParameters) - .Append('.') - .Append(combination.MethodDataSourceIndex) - .Append('.') - .Append(combination.MethodLoopIndex) - .Append('.') - .Append(combination.RepeatIndex) - .Append("_DataGenerationError"); + for (var i = 0; i < methodParameters.Length; i++) + { + methodParameterTypes[i] = methodParameters[i].Type; + } - return sb.ToString(); + var classTypeWithParameters = BuildTypeWithParameters( + GetTypeNameWithGenerics(metadata.TestClassType), + constructorParameterTypes.AsSpan(0, constructorParameters.Length)); + + var methodWithParameters = BuildTypeWithParameters( + metadata.TestMethodName, + methodParameterTypes.AsSpan(0, methodParameters.Length)); + + // Use StringBuilder for efficient string concatenation + var sb = new StringBuilder(256); // Pre-size for typical test ID length + sb.Append(methodMetadata.Class.Namespace) + .Append('.') + .Append(classTypeWithParameters) + .Append('.') + .Append(combination.ClassDataSourceIndex) + .Append('.') + .Append(combination.ClassLoopIndex) + .Append('.') + .Append(methodWithParameters) + .Append('.') + .Append(combination.MethodDataSourceIndex) + .Append('.') + .Append(combination.MethodLoopIndex) + .Append('.') + .Append(combination.RepeatIndex) + .Append("_DataGenerationError"); + + return sb.ToString(); + } + finally + { + ArrayPool.Shared.Return(constructorParameterTypes); + ArrayPool.Shared.Return(methodParameterTypes); + } } private static string GetTypeNameWithGenerics(Type type) @@ -148,7 +184,7 @@ private static string GetTypeNameWithGenerics(Type type) return sb.ToString(); } - private static string BuildTypeWithParameters(string typeName, Type[] parameterTypes) + private static string BuildTypeWithParameters(string typeName, ReadOnlySpan parameterTypes) { if (parameterTypes.Length == 0) { diff --git a/TUnit.Engine/Services/TestRegistry.cs b/TUnit.Engine/Services/TestRegistry.cs index 131c9feb58..98cfa207af 100644 --- a/TUnit.Engine/Services/TestRegistry.cs +++ b/TUnit.Engine/Services/TestRegistry.cs @@ -1,11 +1,13 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Linq.Expressions; using System.Reflection; using TUnit.Core; using TUnit.Core.Interfaces; using TUnit.Engine.Building; using TUnit.Engine.Interfaces; +using Expression = System.Linq.Expressions.Expression; namespace TUnit.Engine.Services; @@ -17,16 +19,19 @@ internal sealed class TestRegistry : ITestRegistry private readonly ConcurrentQueue _pendingTests = new(); private readonly TestBuilderPipeline? _testBuilderPipeline; private readonly ITestCoordinator _testCoordinator; + private readonly IDynamicTestQueue _dynamicTestQueue; private readonly CancellationToken _sessionCancellationToken; private readonly string? _sessionId; public TestRegistry(TestBuilderPipeline testBuilderPipeline, ITestCoordinator testCoordinator, + IDynamicTestQueue dynamicTestQueue, string sessionId, CancellationToken sessionCancellationToken) { _testBuilderPipeline = testBuilderPipeline; _testCoordinator = testCoordinator; + _dynamicTestQueue = dynamicTestQueue; _sessionId = sessionId; _sessionCancellationToken = sessionCancellationToken; } @@ -90,14 +95,140 @@ private async Task ProcessPendingDynamicTests() testMetadataList.Add(metadata); } - var builtTests = await _testBuilderPipeline!.BuildTestsFromMetadataAsync(testMetadataList); + // These are dynamic tests registered after discovery, so not in execution mode with a filter + var buildingContext = new Building.TestBuildingContext(IsForExecution: false, Filter: null); + var builtTests = await _testBuilderPipeline!.BuildTestsFromMetadataAsync(testMetadataList, buildingContext); foreach (var test in builtTests) { - await _testCoordinator.ExecuteTestAsync(test, _sessionCancellationToken); + await _dynamicTestQueue.EnqueueAsync(test); } } + [RequiresUnreferencedCode("Creating test variants requires reflection which is not supported in native AOT scenarios.")] + [UnconditionalSuppressMessage("Trimming", + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access", + Justification = "Dynamic test variants require reflection")] + [UnconditionalSuppressMessage("Trimming", + "IL2067:Target parameter argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call", + Justification = "Dynamic test variants require reflection")] + [UnconditionalSuppressMessage("AOT", + "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling", + Justification = "Dynamic test variants require runtime compilation")] + public async Task CreateTestVariant( + TestContext currentContext, + object?[]? arguments, + Dictionary? properties, + TUnit.Core.Enums.TestRelationship relationship, + string? displayName) + { + var testDetails = currentContext.TestDetails; + var testClassType = testDetails.ClassType; + var variantMethodArguments = arguments ?? testDetails.TestMethodArguments; + + var methodMetadata = testDetails.MethodMetadata; + var parameterTypes = methodMetadata.Parameters.Select(p => p.Type).ToArray(); + var methodInfo = methodMetadata.Type.GetMethod( + methodMetadata.Name, + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, + null, + parameterTypes, + null); + + if (methodInfo == null) + { + throw new InvalidOperationException($"Cannot create test variant: method '{methodMetadata.Name}' not found"); + } + + var genericAddDynamicTestMethod = typeof(TestRegistry) + .GetMethod(nameof(CreateTestVariantInternal), BindingFlags.NonPublic | BindingFlags.Instance) + ?.MakeGenericMethod(testClassType); + + if (genericAddDynamicTestMethod == null) + { + throw new InvalidOperationException("Failed to resolve CreateTestVariantInternal method"); + } + + await ((Task)genericAddDynamicTestMethod.Invoke(this, + [currentContext, methodInfo, variantMethodArguments, testDetails.TestClassArguments, properties, relationship, displayName])!); + } + + [RequiresUnreferencedCode("Creating test variants requires reflection which is not supported in native AOT scenarios.")] + private async Task CreateTestVariantInternal<[DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.PublicConstructors + | DynamicallyAccessedMemberTypes.NonPublicConstructors + | DynamicallyAccessedMemberTypes.PublicProperties + | DynamicallyAccessedMemberTypes.PublicMethods + | DynamicallyAccessedMemberTypes.NonPublicMethods + | DynamicallyAccessedMemberTypes.PublicFields + | DynamicallyAccessedMemberTypes.NonPublicFields)] T>( + TestContext currentContext, + MethodInfo methodInfo, + object?[] variantMethodArguments, + object?[] classArguments, + Dictionary? properties, + TUnit.Core.Enums.TestRelationship relationship, + string? displayName) where T : class + { + var parameter = Expression.Parameter(typeof(T), "instance"); + var methodParameters = methodInfo.GetParameters(); + var argumentExpressions = new Expression[methodParameters.Length]; + + for (int i = 0; i < methodParameters.Length; i++) + { + var argValue = i < variantMethodArguments.Length ? variantMethodArguments[i] : null; + argumentExpressions[i] = Expression.Constant(argValue, methodParameters[i].ParameterType); + } + + var methodCall = Expression.Call(parameter, methodInfo, argumentExpressions); + + Expression body; + if (methodInfo.ReturnType == typeof(Task)) + { + body = methodCall; + } + else if (methodInfo.ReturnType == typeof(void)) + { + body = Expression.Block(methodCall, Expression.Constant(Task.CompletedTask)); + } + else if (methodInfo.ReturnType.IsGenericType && + methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + body = Expression.Convert(methodCall, typeof(Task)); + } + else + { + body = Expression.Block(methodCall, Expression.Constant(Task.CompletedTask)); + } + + var lambda = Expression.Lambda>(body, parameter); + var attributes = new List(currentContext.TestDetails.GetAllAttributes()); + + var discoveryResult = new DynamicDiscoveryResult + { + TestClassType = typeof(T), + TestClassArguments = classArguments, + TestMethodArguments = variantMethodArguments, + TestMethod = lambda, + Attributes = attributes, + CreatorFilePath = currentContext.TestDetails.TestFilePath, + CreatorLineNumber = currentContext.TestDetails.TestLineNumber, + ParentTestId = currentContext.TestDetails.TestId, + Relationship = relationship, + Properties = properties, + DisplayName = displayName + }; + + _pendingTests.Enqueue(new PendingDynamicTest + { + DiscoveryResult = discoveryResult, + SourceContext = currentContext, + TestClassType = typeof(T) + }); + + await ProcessPendingDynamicTests(); + } + [RequiresUnreferencedCode("Dynamic test metadata creation requires reflection which is not supported in native AOT scenarios.")] private async Task CreateMetadataFromDynamicDiscoveryResult(DynamicDiscoveryResult result) { @@ -229,12 +360,30 @@ public override Func { var instance = metadata.InstanceFactory(Type.EmptyTypes, modifiedContext.ClassArguments); diff --git a/TUnit.Engine/TestDiscoveryService.cs b/TUnit.Engine/TestDiscoveryService.cs index 05de9b3332..41682fdcd8 100644 --- a/TUnit.Engine/TestDiscoveryService.cs +++ b/TUnit.Engine/TestDiscoveryService.cs @@ -55,16 +55,18 @@ public async Task DiscoverTests(string testSessionId, ITest contextProvider.BeforeTestDiscoveryContext.RestoreExecutionContext(); + // Create building context for optimization + var buildingContext = new Building.TestBuildingContext(isForExecution, filter); + // Stage 1: Stream independent tests immediately while buffering dependent tests var independentTests = new List(); var dependentTests = new List(); var allTests = new List(); - await foreach (var test in DiscoverTestsStreamAsync(testSessionId, cancellationToken).ConfigureAwait(false)) + await foreach (var test in DiscoverTestsStreamAsync(testSessionId, buildingContext, cancellationToken).ConfigureAwait(false)) { allTests.Add(test); - // Check if this test has dependencies based on metadata if (test.Metadata.Dependencies.Length > 0) { // Buffer tests with dependencies for later resolution @@ -131,6 +133,7 @@ public async Task DiscoverTests(string testSessionId, ITest /// Streams test discovery for parallel discovery and execution private async IAsyncEnumerable DiscoverTestsStreamAsync( string testSessionId, + Building.TestBuildingContext buildingContext, [EnumeratorCancellation] CancellationToken cancellationToken = default) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -138,7 +141,7 @@ private async IAsyncEnumerable DiscoverTestsStreamAsync( // Set a reasonable timeout for test discovery (5 minutes) cts.CancelAfter(TimeSpan.FromMinutes(5)); - var tests = await _testBuilderPipeline.BuildTestsStreamingAsync(testSessionId, cancellationToken).ConfigureAwait(false); + var tests = await _testBuilderPipeline.BuildTestsStreamingAsync(testSessionId, buildingContext, cancellationToken).ConfigureAwait(false); foreach (var test in tests) { @@ -164,9 +167,12 @@ public async IAsyncEnumerable DiscoverTestsFullyStreamin { await _testExecutor.ExecuteBeforeTestDiscoveryHooksAsync(cancellationToken).ConfigureAwait(false); + // Create building context - this is for discovery/streaming, not execution filtering + var buildingContext = new Building.TestBuildingContext(IsForExecution: false, Filter: null); + // Collect all tests first (like source generation mode does) var allTests = new List(); - await foreach (var test in DiscoverTestsStreamAsync(testSessionId, cancellationToken).ConfigureAwait(false)) + await foreach (var test in DiscoverTestsStreamAsync(testSessionId, buildingContext, cancellationToken).ConfigureAwait(false)) { allTests.Add(test); } @@ -212,7 +218,6 @@ public async IAsyncEnumerable DiscoverTestsFullyStreamin foreach (var test in remainingTests) { - // Check if all dependencies have been yielded var allDependenciesYielded = test.Dependencies.All(dep => yieldedTests.Contains(dep.Test.TestId)); if (allDependenciesYielded) diff --git a/TUnit.Engine/TestExecutor.cs b/TUnit.Engine/TestExecutor.cs index cba434941f..19d60c4c55 100644 --- a/TUnit.Engine/TestExecutor.cs +++ b/TUnit.Engine/TestExecutor.cs @@ -59,7 +59,6 @@ public async Task ExecuteAsync(AbstractExecutableTest executableTest, Cancellati try { - // Ensure TestSession hooks have been executed await EnsureTestSessionHooksExecutedAsync().ConfigureAwait(false); // Event receivers have their own internal coordination to run once @@ -94,7 +93,6 @@ await _eventReceiverOrchestrator.InvokeFirstTestInClassEventReceiversAsync( await _hookExecutor.ExecuteBeforeTestHooksAsync(executableTest, cancellationToken).ConfigureAwait(false); - // Invoke test start event receivers await _eventReceiverOrchestrator.InvokeTestStartEventReceiversAsync(executableTest.Context, cancellationToken).ConfigureAwait(false); executableTest.Context.RestoreExecutionContext(); @@ -128,7 +126,6 @@ await TimeoutHelper.ExecuteWithTimeoutAsync( // Run After(Test) hooks await _hookExecutor.ExecuteAfterTestHooksAsync(executableTest, cancellationToken).ConfigureAwait(false); - // Invoke test end event receivers await _eventReceiverOrchestrator.InvokeTestEndEventReceiversAsync(executableTest.Context, cancellationToken).ConfigureAwait(false); } catch @@ -155,7 +152,6 @@ await TimeoutHelper.ExecuteWithTimeoutAsync( // Run After(Test) hooks await _hookExecutor.ExecuteAfterTestHooksAsync(executableTest, cancellationToken).ConfigureAwait(false); - // Invoke test end event receivers await _eventReceiverOrchestrator.InvokeTestEndEventReceiversAsync(executableTest.Context, cancellationToken).ConfigureAwait(false); } // Note: Test instance disposal and After(Class/Assembly/Session) hooks diff --git a/TUnit.Pipeline/Modules/Abstract/TestBaseModule.cs b/TUnit.Pipeline/Modules/Abstract/TestBaseModule.cs index 772662e9b8..0943197e35 100644 --- a/TUnit.Pipeline/Modules/Abstract/TestBaseModule.cs +++ b/TUnit.Pipeline/Modules/Abstract/TestBaseModule.cs @@ -45,8 +45,6 @@ protected virtual IEnumerable TestableFrameworks private DotNetRunOptions SetDefaults(DotNetRunOptions testOptions) { - // Removed --fail-fast to allow all tests to run even if some fail - if (testOptions.EnvironmentVariables?.Any(x => x.Key == "NET_VERSION") != true) { testOptions = testOptions with diff --git a/TUnit.Pipeline/Modules/GenerateReadMeModule.cs b/TUnit.Pipeline/Modules/GenerateReadMeModule.cs index 4fa520a012..45b8f5f4fb 100644 --- a/TUnit.Pipeline/Modules/GenerateReadMeModule.cs +++ b/TUnit.Pipeline/Modules/GenerateReadMeModule.cs @@ -58,18 +58,28 @@ public class GenerateReadMeModule : Module var fileContents = new StringBuilder(); - // Grouping is by Scenario - foreach (var groupedArtifacts in artifacts.Artifacts + // Expected artifact name pattern: ubuntu_markdown_{build_time|run_time_{class}} + // Example: ubuntu_markdown_run_time_AsyncTests, ubuntu_markdown_build_time + var benchmarkArtifacts = artifacts.Artifacts + .Where(x => x.Name.StartsWith("ubuntu_markdown_")) + .ToList(); + + if (benchmarkArtifacts.Count == 0) + { + context.Logger.LogWarning("No benchmark markdown artifacts found."); + return null; + } + + // Grouping is by Scenario (e.g., "markdown_run_time_AsyncTests" or "markdown_build_time") + foreach (var groupedArtifacts in benchmarkArtifacts .OrderBy(x => x.Name) - .GroupBy(x => x.Name.Split("_", 2)[1])) + .GroupBy(x => x.Name.Substring("ubuntu_".Length))) { fileContents.AppendLine($"### Scenario: {GetScenario(groupedArtifacts.Key)}"); foreach (var artifact in groupedArtifacts.OrderBy(x => x.Name)) { - var operatingSystem = artifact.Name.Split("_")[0]; - - context.Logger.LogInformation("Processing artifact: {ArtifactName} for OS: {OperatingSystem}", artifact.Name, operatingSystem); + context.Logger.LogInformation("Processing artifact: {ArtifactName}", artifact.Name); var stream = await context.GitHub().Client.Actions.Artifacts.DownloadArtifact( context.GitHub().RepositoryInfo.Owner, @@ -86,13 +96,11 @@ public class GenerateReadMeModule : Module var contents = await markdownFile.ReadAsync(cancellationToken); - fileContents.AppendLine(); - fileContents.AppendLine($"#### {operatingSystem}"); fileContents.AppendLine(); fileContents.AppendLine(contents); fileContents.AppendLine(); - context.Logger.LogInformation("Added contents from {MarkdownFile} for OS: {OperatingSystem}", markdownFile.Name, operatingSystem); + context.Logger.LogInformation("Added contents from {MarkdownFile}", markdownFile.Name); } } @@ -118,14 +126,11 @@ private string GetScenario(string fileName) return fileName.Split("_").Last() switch { - "AssertionTests" => "Tests focused on assertion performance and validation", "AsyncTests" => "Tests running asynchronous operations and async/await patterns", - "BasicTests" => "Simple tests with basic operations and assertions", "DataDrivenTests" => "Parameterized tests with multiple test cases using data attributes", - "FixtureTests" => "Tests utilizing class fixtures and shared test context", - "ParallelTests" => "Tests executing in parallel to test framework parallelization", - "RepeatTests" => "A test that takes 50ms to execute, repeated 100 times", - "SetupTeardownTests" => "Tests with setup and teardown lifecycle methods", + "MassiveParallelTests" => "Tests executing massively parallel workloads with CPU-bound, I/O-bound, and mixed operations", + "MatrixTests" => "Tests with complex parameter combinations creating 25-125 test variations", + "ScaleTests" => "Large-scale parameterized tests with 100+ test cases testing framework scalability", _ => throw new ArgumentException($"Unknown class name: {fileName}", nameof(fileName)) }; } diff --git a/TUnit.Pipeline/Modules/RunEngineTestsModule.cs b/TUnit.Pipeline/Modules/RunEngineTestsModule.cs index b21eb0f597..162ccaf06e 100644 --- a/TUnit.Pipeline/Modules/RunEngineTestsModule.cs +++ b/TUnit.Pipeline/Modules/RunEngineTestsModule.cs @@ -38,7 +38,6 @@ public class RunEngineTestsModule : Module Arguments = [ "--hangdump", "--hangdump-filename", $"hangdump.{Environment.OSVersion.Platform}.engine-tests.dmp", "--hangdump-timeout", "30m", "--timeout", "35m", - "--fail-fast" ], EnvironmentVariables = new Dictionary { diff --git a/TUnit.Pipeline/Modules/RunPublicAPITestsModule.cs b/TUnit.Pipeline/Modules/RunPublicAPITestsModule.cs index 2e07663e63..683be1a71c 100644 --- a/TUnit.Pipeline/Modules/RunPublicAPITestsModule.cs +++ b/TUnit.Pipeline/Modules/RunPublicAPITestsModule.cs @@ -25,7 +25,6 @@ protected override Task GetTestOptions(IPipelineContext contex ["DISABLE_GITHUB_REPORTER"] = "true", ["GITHUB_ACTIONS"] = "false", }, - Arguments = ["--fail-fast"] }); } } diff --git a/TUnit.Pipeline/Modules/RunSourceGeneratorTestsModule.cs b/TUnit.Pipeline/Modules/RunSourceGeneratorTestsModule.cs index 452cbd8c98..5eb29f0e14 100644 --- a/TUnit.Pipeline/Modules/RunSourceGeneratorTestsModule.cs +++ b/TUnit.Pipeline/Modules/RunSourceGeneratorTestsModule.cs @@ -24,7 +24,6 @@ protected override Task GetTestOptions(IPipelineContext contex { ["DISABLE_GITHUB_REPORTER"] = "true", }, - Arguments = ["--", "--fail-fast"] }); } } diff --git a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet10_0.verified.txt b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet10_0.verified.txt index 8b838e794c..108a42a252 100644 --- a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet10_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet10_0.verified.txt @@ -5,6 +5,14 @@ namespace { public static void Fail(string reason) { } public static Multiple() { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : class { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : struct { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : class { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : struct { } public static . That( action, [.("action")] string? expression = null) { } public static . That(.IEnumerable value, [.("value")] string? expression = null) { } public static . That(<.> action, [.("action")] string? expression = null) { } @@ -15,7 +23,7 @@ namespace public static . That(.? value, [.("value")] string? expression = null) { } public static . That(<.> func, [.("func")] string? expression = null) { } public static . That( func, [.("func")] string? expression = null) { } - public static . That(. task, [.("task")] string? expression = null) { } + public static . That(. task, [.("task")] string? expression = null) { } public static . That(TValue? value, [.("value")] string? expression = null) { } [.(3)] public static . That(. value, [.("value")] string? expression = null) { } @@ -139,6 +147,44 @@ namespace .Assertions } } namespace . +{ + public class GroupAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchGroupAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class MatchIndexAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class RegexMatch + { + public int Index { get; } + public int Length { get; } + public string Value { get; } + public string GetGroup(int groupIndex) { } + public string GetGroup(string groupName) { } + } + public class RegexMatchCollection : .<..RegexMatch>, .<..RegexMatch>, .<..RegexMatch>, .IEnumerable + { + public int Count { get; } + public ..RegexMatch First { get; } + public ..RegexMatch this[int index] { get; } + public .<..RegexMatch> GetEnumerator() { } + } +} +namespace . { public class IsNotParsableIntoAssertion<[.(..None | ..PublicMethods | ..Interfaces)] T> : . { @@ -180,6 +226,7 @@ namespace .Attributes public AssertionFromAttribute( targetType, containingType, string methodName) { } public ? ContainingType { get; } public string? CustomName { get; set; } + public string? ExpectationMessage { get; set; } public string MethodName { get; } public bool NegateLogic { get; set; } public bool RequiresGenericTypeParameter { get; set; } @@ -200,36 +247,6 @@ namespace .Attributes public TargetType { get; } public bool TreatAsInstance { get; set; } } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future ve" + - "rsion.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute( targetType, string methodName) { } - public CreateAssertionAttribute( targetType, containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future" + - " version.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute(string methodName) { } - public CreateAssertionAttribute( containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } [(.Method, AllowMultiple=false, Inherited=false)] public sealed class GenerateAssertionAttribute : { @@ -322,6 +339,15 @@ namespace .Conditions public . InclusiveMaximum() { } public . InclusiveMinimum() { } } + [.<.BigInteger>("IsEven", CustomName="IsNotEven", ExpectationMessage="be even", NegateLogic=true)] + [.<.BigInteger>("IsEven", ExpectationMessage="be even")] + [.<.BigInteger>("IsOne", CustomName="IsNotOne", ExpectationMessage="be one", NegateLogic=true)] + [.<.BigInteger>("IsOne", ExpectationMessage="be one")] + [.<.BigInteger>("IsPowerOfTwo", CustomName="IsNotPowerOfTwo", ExpectationMessage="be a power of two", NegateLogic=true)] + [.<.BigInteger>("IsPowerOfTwo", ExpectationMessage="be a power of two")] + [.<.BigInteger>("IsZero", CustomName="IsNotZero", ExpectationMessage="be zero", NegateLogic=true)] + [.<.BigInteger>("IsZero", ExpectationMessage="be zero")] + public static class BigIntegerAssertionExtensions { } public static class BooleanAssertionExtensions { [.(ExpectationMessage="to be false")] @@ -535,6 +561,13 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.<.Cookie>("Expired", CustomName="IsNotExpired", ExpectationMessage="be expired", NegateLogic=true)] + [.<.Cookie>("Expired", ExpectationMessage="be expired")] + [.<.Cookie>("HttpOnly", CustomName="IsNotHttpOnly", ExpectationMessage="be HTTP-only", NegateLogic=true)] + [.<.Cookie>("HttpOnly", ExpectationMessage="be HTTP-only")] + [.<.Cookie>("Secure", CustomName="IsNotSecure", ExpectationMessage="be secure", NegateLogic=true)] + [.<.Cookie>("Secure", ExpectationMessage="be secure")] + public static class CookieAssertionExtensions { } [.<.CultureInfo>("IsNeutralCulture", CustomName="IsNotNeutralCulture", ExpectationMessage="be a neutral culture", NegateLogic=true)] [.<.CultureInfo>("IsNeutralCulture", ExpectationMessage="be a neutral culture")] [.<.CultureInfo>("IsReadOnly", ExpectationMessage="be read-only culture")] @@ -741,6 +774,21 @@ namespace .Conditions [.(ExpectationMessage="to be a system directory")] public static bool IsSystemDirectory(this .DirectoryInfo value) { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class DoubleAssertionExtensions { } [.("IsEqualTo", OverloadResolutionPriority=2)] public class DoubleEqualsAssertion : . { @@ -958,6 +1006,9 @@ namespace .Conditions public . GetAwaiter() { } protected override string GetExpectation() { } } + [.<.>("IsSuccessStatusCode", CustomName="IsNotSuccessStatusCode", ExpectationMessage="have a success status code", NegateLogic=true)] + [.<.>("IsSuccessStatusCode", ExpectationMessage="have a success status code")] + public static class HttpResponseMessageAssertionExtensions { } public static class HttpStatusCodeAssertionExtensions { [.(ExpectationMessage="to be a client error status code (4xx)")] @@ -1049,14 +1100,6 @@ namespace .Conditions protected override string GetExpectation() { } public . Using(. comparer) { } } - [.("IsIn")] - public class IsInAssertion : . - { - public IsInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } [.("IsNotAssignableTo")] public class IsNotAssignableToAssertion : . { @@ -1088,14 +1131,6 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("IsNotIn")] - public class IsNotInAssertion : . - { - public IsNotInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } public class IsTypeOfRuntimeAssertion : . { public IsTypeOfRuntimeAssertion(. context, expectedType) { } @@ -1202,6 +1237,9 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.(typeof(int?), "HasValue", CustomName="DoesNotHaveValue", ExpectationMessage="have a value", NegateLogic=true)] + [.(typeof(int?), "HasValue", ExpectationMessage="have a value")] + public static class NullableAssertionExtensions { } [.("IsEquatableTo")] public class NullableEquatableAssertion : . where TActual : struct, @@ -1228,6 +1266,33 @@ namespace .Conditions [.(ExpectationMessage="to be the all range")] public static bool IsAll(this value) { } } + [.<.Rune>("IsAscii", CustomName="IsNotAscii", ExpectationMessage="be ASCII", NegateLogic=true)] + [.<.Rune>("IsAscii", ExpectationMessage="be ASCII")] + [.<.Rune>("IsBmp", CustomName="IsNotBmp", ExpectationMessage="be in the Basic Multilingual Plane", NegateLogic=true)] + [.<.Rune>("IsBmp", ExpectationMessage="be in the Basic Multilingual Plane")] + [.<.Rune>(typeof(.Rune), "IsControl", CustomName="IsNotControl", ExpectationMessage="be a control character", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsControl", ExpectationMessage="be a control character")] + [.<.Rune>(typeof(.Rune), "IsDigit", CustomName="IsNotDigit", ExpectationMessage="be a digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsDigit", ExpectationMessage="be a digit")] + [.<.Rune>(typeof(.Rune), "IsLetter", CustomName="IsNotLetter", ExpectationMessage="be a letter", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetter", ExpectationMessage="be a letter")] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", CustomName="IsNotLetterOrDigit", ExpectationMessage="be a letter or digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", ExpectationMessage="be a letter or digit")] + [.<.Rune>(typeof(.Rune), "IsLower", CustomName="IsNotLower", ExpectationMessage="be lowercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLower", ExpectationMessage="be lowercase")] + [.<.Rune>(typeof(.Rune), "IsNumber", CustomName="IsNotNumber", ExpectationMessage="be a number", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsNumber", ExpectationMessage="be a number")] + [.<.Rune>(typeof(.Rune), "IsPunctuation", CustomName="IsNotPunctuation", ExpectationMessage="be punctuation", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsPunctuation", ExpectationMessage="be punctuation")] + [.<.Rune>(typeof(.Rune), "IsSeparator", CustomName="IsNotSeparator", ExpectationMessage="be a separator", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSeparator", ExpectationMessage="be a separator")] + [.<.Rune>(typeof(.Rune), "IsSymbol", CustomName="IsNotSymbol", ExpectationMessage="be a symbol", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSymbol", ExpectationMessage="be a symbol")] + [.<.Rune>(typeof(.Rune), "IsUpper", CustomName="IsNotUpper", ExpectationMessage="be uppercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsUpper", ExpectationMessage="be uppercase")] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", CustomName="IsNotWhiteSpace", ExpectationMessage="be whitespace", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", ExpectationMessage="be whitespace")] + public static class RuneAssertionExtensions { } [.("IsSameReferenceAs")] public class SameReferenceAssertion : . { @@ -1241,6 +1306,26 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class SingleAssertionExtensions { } + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + public static class SpanAssertionExtensions { } [.<.Stream>("CanRead", CustomName="CannotRead", ExpectationMessage="be readable", NegateLogic=true)] [.<.Stream>("CanRead", ExpectationMessage="be readable")] [.<.Stream>("CanSeek", CustomName="CannotSeek", ExpectationMessage="be seekable", NegateLogic=true)] @@ -1315,6 +1400,7 @@ namespace .Conditions public class StringEqualsAssertion : . { public StringEqualsAssertion(. context, string? expected) { } + public StringEqualsAssertion(. context, string? expected, comparison) { } protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } @@ -1343,12 +1429,11 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("Matches")] - public class StringMatchesAssertion : . + public class StringMatchesAssertion : .<..RegexMatchCollection> { public StringMatchesAssertion(. context, . regex) { } public StringMatchesAssertion(. context, string pattern) { } - protected override .<.> CheckAsync(. metadata) { } + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } public . WithOptions(. options) { } @@ -1568,6 +1653,15 @@ namespace .Conditions [.<>("UserEscaped", CustomName="IsNotUserEscaped", ExpectationMessage="be user-escaped", NegateLogic=true)] [.<>("UserEscaped", ExpectationMessage="be user-escaped")] public static class UriAssertionExtensions { } + [.<.>("IsCanceled", CustomName="IsNotCanceled", ExpectationMessage="be canceled", NegateLogic=true)] + [.<.>("IsCanceled", ExpectationMessage="be canceled")] + [.<.>("IsCompleted", CustomName="IsNotCompleted", ExpectationMessage="be completed", NegateLogic=true)] + [.<.>("IsCompleted", ExpectationMessage="be completed")] + [.<.>("IsCompletedSuccessfully", CustomName="IsNotCompletedSuccessfully", ExpectationMessage="be completed successfully", NegateLogic=true)] + [.<.>("IsCompletedSuccessfully", ExpectationMessage="be completed successfully")] + [.<.>("IsFaulted", CustomName="IsNotFaulted", ExpectationMessage="be faulted", NegateLogic=true)] + [.<.>("IsFaulted", ExpectationMessage="be faulted")] + public static class ValueTaskAssertionExtensions { } public static class VersionAssertionExtensions { [.(ExpectationMessage="to have a build number")] @@ -1583,6 +1677,12 @@ namespace .Conditions [.(ExpectationMessage="to not be a major version")] public static bool IsNotMajorVersion(this value) { } } + public class WaitsForAssertion : . + { + public WaitsForAssertion(. context, <., .> assertionBuilder, timeout, ? pollingInterval = default) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } [.<>("IsAlive", CustomName="IsNotAlive", ExpectationMessage="be alive", NegateLogic=true)] [.<>("IsAlive", ExpectationMessage="be alive")] [.<>("TrackResurrection", CustomName="DoesNotTrackResurrection", ExpectationMessage="track resurrection", NegateLogic=true)] @@ -1706,6 +1806,10 @@ namespace .Core public . Map( mapper) { } public . MapException() where TException : { } + [return: .(new string?[]?[] { + "Value", + "Exception"})] + public .<> ReevaluateAsync() { } } public readonly struct EvaluationMetadata { @@ -1874,10 +1978,8 @@ namespace .Extensions public static .<> IsBeforeOrEqualTo(this .<> source, expected, [.("expected")] string? expression = null) { } public static ..IsDefinedAssertion IsDefined(this . source) where TEnum : struct, { } - public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expression = null) { } [.("Uses reflection to compare members")] public static . IsEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsIn(this . source, params TValue[] collection) { } public static . IsNegative(this . source) where TValue : { } public static . IsNegative(this . source) @@ -1887,7 +1989,6 @@ namespace .Extensions where TEnum : struct, { } [.("Uses reflection to compare members")] public static . IsNotEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsNotIn(this . source, params TValue[] collection) { } public static . IsNotNull(this . source) where TValue : class { } public static . IsNotNull(this . source) @@ -1924,7 +2025,7 @@ namespace .Extensions [.(3)] public static . Member(this . source, .<>> memberSelector, <.<., TKey, TValue>, .> assertions) { } public static . Satisfies(this . source, predicate, [.("predicate")] string? expression = null) { } - public static . Satisfies(this . source, > selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } + public static . Satisfies(this . source, > selector, <., .> assertions, [.("selector")] string? selectorExpression = null) { } public static . Satisfies(this . source, selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } public static . Throws(this . source) where TException : { } @@ -1944,6 +2045,7 @@ namespace .Extensions public static . ThrowsException(this . source) where TException : { } public static . ThrowsNothing(this . source) { } + public static . WaitsFor(this . source, <., .> assertionBuilder, timeout, ? pollingInterval = default, [.("timeout")] string? timeoutExpression = null, [.("pollingInterval")] string? pollingIntervalExpression = null) { } public static ..WhenParsedIntoAssertion WhenParsedInto<[.(..None | ..PublicMethods | ..Interfaces)] T>(this . source) { } public static . WithMessage(this . source, string expectedMessage, [.("expectedMessage")] string? expression = null) where TException : { } @@ -1969,6 +2071,41 @@ namespace .Extensions public static . IsBetween(this . source, TValue minimum, TValue maximum, [.("minimum")] string? minimumExpression = null, [.("maximum")] string? maximumExpression = null) where TValue : { } } + public static class BigIntegerAssertionExtensions + { + public static . IsEven(this .<.BigInteger> source) { } + public static . IsNotEven(this .<.BigInteger> source) { } + public static . IsNotOne(this .<.BigInteger> source) { } + public static . IsNotPowerOfTwo(this .<.BigInteger> source) { } + public static . IsNotZero(this .<.BigInteger> source) { } + public static . IsOne(this .<.BigInteger> source) { } + public static . IsPowerOfTwo(this .<.BigInteger> source) { } + public static . IsZero(this .<.BigInteger> source) { } + } + public class BigIntegerIsEvenAssertion : .<.BigInteger> + { + public BigIntegerIsEvenAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsOneAssertion : .<.BigInteger> + { + public BigIntegerIsOneAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsPowerOfTwoAssertion : .<.BigInteger> + { + public BigIntegerIsPowerOfTwoAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsZeroAssertion : .<.BigInteger> + { + public BigIntegerIsZeroAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } public sealed class Bool_IsFalse_Assertion : . { public Bool_IsFalse_Assertion(. context) { } @@ -2176,6 +2313,33 @@ namespace .Extensions public static . IsInOrder(this . source) where TCollection : . { } } + public static class CookieAssertionExtensions + { + public static . Expired(this .<.Cookie> source) { } + public static . HttpOnly(this .<.Cookie> source) { } + public static . IsNotExpired(this .<.Cookie> source) { } + public static . IsNotHttpOnly(this .<.Cookie> source) { } + public static . IsNotSecure(this .<.Cookie> source) { } + public static . Secure(this .<.Cookie> source) { } + } + public class CookieExpiredAssertion : .<.Cookie> + { + public CookieExpiredAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieHttpOnlyAssertion : .<.Cookie> + { + public CookieHttpOnlyAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieSecureAssertion : .<.Cookie> + { + public CookieSecureAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } public static class CultureInfoAssertionExtensions { public static ._IsEnglish_Assertion IsEnglish(this .<.CultureInfo> source) { } @@ -2614,11 +2778,70 @@ namespace .Extensions protected override .<.> CheckAsync(.<.DirectoryInfo> metadata) { } protected override string GetExpectation() { } } + public static class DoubleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } public static class DoubleEqualsAssertionExtensions { [.(2)] public static . IsEqualTo(this . source, double expected, [.("expected")] string? expectedExpression = null) { } } + public class DoubleIsFiniteWithDoubleAssertion : . + { + public DoubleIsFiniteWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsInfinityWithDoubleAssertion : . + { + public DoubleIsInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNaNWithDoubleAssertion : . + { + public DoubleIsNaNWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNegativeInfinityWithDoubleAssertion : . + { + public DoubleIsNegativeInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNormalWithDoubleAssertion : . + { + public DoubleIsNormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsPositiveInfinityWithDoubleAssertion : . + { + public DoubleIsPositiveInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsSubnormalWithDoubleAssertion : . + { + public DoubleIsSubnormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class EncodingAssertionExtensions { public static ._IsASCII_Assertion IsASCII(this .<.Encoding> source) { } @@ -2843,6 +3066,63 @@ namespace .Extensions [.(2)] public static . IsEqualTo(this . source, float expected, [.("expected")] string? expectedExpression = null) { } } + public class FloatIsFiniteWithFloatAssertion : . + { + public FloatIsFiniteWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsInfinityWithFloatAssertion : . + { + public FloatIsInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNaNWithFloatAssertion : . + { + public FloatIsNaNWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNegativeInfinityWithFloatAssertion : . + { + public FloatIsNegativeInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNormalWithFloatAssertion : . + { + public FloatIsNormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsPositiveInfinityWithFloatAssertion : . + { + public FloatIsPositiveInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsSubnormalWithFloatAssertion : . + { + public FloatIsSubnormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public static class GenericAssertions + { + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn__Assertion IsIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_Assertion IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_IEqualityComparerT_Assertion IsIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn__Assertion IsNotIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_Assertion IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion IsNotIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + } public static class GreaterThanAssertionExtensions { public static . IsGreaterThan(this . source, TValue minimum, [.("minimum")] string? minimumExpression = null) @@ -2875,6 +3155,17 @@ namespace .Extensions public static . HasSingleItem(this . source) where TCollection : . { } } + public static class HttpResponseMessageAssertionExtensions + { + public static . IsNotSuccessStatusCode(this .<.> source) { } + public static . IsSuccessStatusCode(this .<.> source) { } + } + public class HttpResponseMessageIsSuccessStatusCodeAssertion : .<.> + { + public HttpResponseMessageIsSuccessStatusCodeAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class HttpStatusCodeAssertionExtensions { public static ._IsClientError_Assertion IsClientError(this .<.HttpStatusCode> source) { } @@ -3051,10 +3342,6 @@ namespace .Extensions public static . IsEquivalentTo(this . source, . expected, . comparer, . ordering = 0, [.("expected")] string? expectedExpression = null, [.("comparer")] string? comparerExpression = null, [.("ordering")] string? orderingExpression = null) where TCollection : . { } } - public static class IsInAssertionExtensions - { - public static . IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class IsNotAssignableToAssertionExtensions { public static . IsNotAssignableTo(this . source) { } @@ -3074,10 +3361,6 @@ namespace .Extensions public static . IsNotDefault(this . source) where TValue : class { } } - public static class IsNotInAssertionExtensions - { - public static . IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class LazyAssertionExtensions { [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] @@ -3133,6 +3416,11 @@ namespace .Extensions { public static . IsNull(this . source) { } } + public static class NullableAssertionExtensions + { + public static . DoesNotHaveValue(this . source) { } + public static . HasValue(this . source) { } + } public sealed class NullableBool_IsFalse_Assertion : . { public NullableBool_IsFalse_Assertion(. context) { } @@ -3150,6 +3438,12 @@ namespace .Extensions public static . IsEquatableTo(this . source, TExpected expected, [.("expected")] string? expectedExpression = null) where TActual : struct, { } } + public class NullableHasValueAssertion : . + { + public NullableHasValueAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class ProcessAssertionExtensions { public static . DoesNotHaveEventRaisingEnabled(this .<.Process> source) { } @@ -3213,10 +3507,148 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class RegexAssertionExtensions + { + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, string groupName, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, int groupIndex, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, string groupName, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, string groupName, <., .?> assertion) { } + public static ..MatchIndexAssertion Match(this .<..RegexMatchCollection> continuation, int index) { } + public static ..MatchAssertion Match(this .<..RegexMatchCollection> continuation, int index, <.<..RegexMatch>, .<..RegexMatch>?> assertion) { } + public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } + public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } + } + public static class RuneAssertionExtensions + { + public static . IsAscii(this .<.Rune> source) { } + public static . IsBmp(this .<.Rune> source) { } + public static . IsControl(this .<.Rune> source) { } + public static . IsDigit(this .<.Rune> source) { } + public static . IsLetter(this .<.Rune> source) { } + public static . IsLetterOrDigit(this .<.Rune> source) { } + public static . IsLower(this .<.Rune> source) { } + public static . IsNotAscii(this .<.Rune> source) { } + public static . IsNotBmp(this .<.Rune> source) { } + public static . IsNotControl(this .<.Rune> source) { } + public static . IsNotDigit(this .<.Rune> source) { } + public static . IsNotLetter(this .<.Rune> source) { } + public static . IsNotLetterOrDigit(this .<.Rune> source) { } + public static . IsNotLower(this .<.Rune> source) { } + public static . IsNotNumber(this .<.Rune> source) { } + public static . IsNotPunctuation(this .<.Rune> source) { } + public static . IsNotSeparator(this .<.Rune> source) { } + public static . IsNotSymbol(this .<.Rune> source) { } + public static . IsNotUpper(this .<.Rune> source) { } + public static . IsNotWhiteSpace(this .<.Rune> source) { } + public static . IsNumber(this .<.Rune> source) { } + public static . IsPunctuation(this .<.Rune> source) { } + public static . IsSeparator(this .<.Rune> source) { } + public static . IsSymbol(this .<.Rune> source) { } + public static . IsUpper(this .<.Rune> source) { } + public static . IsWhiteSpace(this .<.Rune> source) { } + } + public class RuneIsAsciiAssertion : .<.Rune> + { + public RuneIsAsciiAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsBmpAssertion : .<.Rune> + { + public RuneIsBmpAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsControlWithRuneAssertion : .<.Rune> + { + public RuneIsControlWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsDigitWithRuneAssertion : .<.Rune> + { + public RuneIsDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterOrDigitWithRuneAssertion : .<.Rune> + { + public RuneIsLetterOrDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterWithRuneAssertion : .<.Rune> + { + public RuneIsLetterWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLowerWithRuneAssertion : .<.Rune> + { + public RuneIsLowerWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsNumberWithRuneAssertion : .<.Rune> + { + public RuneIsNumberWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsPunctuationWithRuneAssertion : .<.Rune> + { + public RuneIsPunctuationWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSeparatorWithRuneAssertion : .<.Rune> + { + public RuneIsSeparatorWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSymbolWithRuneAssertion : .<.Rune> + { + public RuneIsSymbolWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsUpperWithRuneAssertion : .<.Rune> + { + public RuneIsUpperWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsWhiteSpaceWithRuneAssertion : .<.Rune> + { + public RuneIsWhiteSpaceWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } public static class SameReferenceAssertionExtensions { public static . IsSameReferenceAs(this . source, object? expected, [.("expected")] string? expectedExpression = null) { } } + public static class SingleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } + public static class SpanAssertionExtensions { } public static class StreamAssertionExtensions { public static . CanRead(this .<.Stream> source) { } @@ -3328,6 +3760,8 @@ namespace .Extensions { [.(2)] public static . IsEqualTo(this . source, string? expected, [.("expected")] string? expectedExpression = null) { } + [.(2)] + public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expectedExpression = null, [.("comparison")] string? comparisonExpression = null) { } } public static class StringIsEmptyAssertionExtensions { @@ -3349,11 +3783,6 @@ namespace .Extensions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - public static class StringMatchesAssertionExtensions - { - public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } - public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } - } public static class StringStartsWithAssertionExtensions { public static . StartsWith(this . source, string expected, [.("expected")] string? expectedExpression = null) { } @@ -3366,6 +3795,48 @@ namespace .Extensions public static . IsNullOrEmpty(this . source) { } public static . IsNullOrWhiteSpace(this . source) { } } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_Assertion : . + { + public T_IsIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn__Assertion : . + { + public T_IsIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_Assertion : . + { + public T_IsNotIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn__Assertion : . + { + public T_IsNotIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class TaskAssertionExtensions { public static . IsCanceled(this . source) @@ -3804,6 +4275,41 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class ValueTaskAssertionExtensions + { + public static . IsCanceled(this .<.> source) { } + public static . IsCompleted(this .<.> source) { } + public static . IsCompletedSuccessfully(this .<.> source) { } + public static . IsFaulted(this .<.> source) { } + public static . IsNotCanceled(this .<.> source) { } + public static . IsNotCompleted(this .<.> source) { } + public static . IsNotCompletedSuccessfully(this .<.> source) { } + public static . IsNotFaulted(this .<.> source) { } + } + public class ValueTaskIsCanceledAssertion : .<.> + { + public ValueTaskIsCanceledAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedAssertion : .<.> + { + public ValueTaskIsCompletedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedSuccessfullyAssertion : .<.> + { + public ValueTaskIsCompletedSuccessfullyAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsFaultedAssertion : .<.> + { + public ValueTaskIsFaultedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class VersionAssertionExtensions { public static ._HasBuildNumber_Assertion HasBuildNumber(this .<> source) { } diff --git a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet8_0.verified.txt b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet8_0.verified.txt index 05c906c479..276ac64fda 100644 --- a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet8_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet8_0.verified.txt @@ -5,6 +5,14 @@ namespace { public static void Fail(string reason) { } public static Multiple() { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : class { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : struct { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : class { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : struct { } public static . That( action, [.("action")] string? expression = null) { } public static . That(.IEnumerable value, [.("value")] string? expression = null) { } public static . That(<.> action, [.("action")] string? expression = null) { } @@ -13,7 +21,7 @@ namespace public static . That(.? value, [.("value")] string? expression = null) { } public static . That(<.> func, [.("func")] string? expression = null) { } public static . That( func, [.("func")] string? expression = null) { } - public static . That(. task, [.("task")] string? expression = null) { } + public static . That(. task, [.("task")] string? expression = null) { } public static . That(TValue? value, [.("value")] string? expression = null) { } public static . That(. value, [.("value")] string? expression = null) { } public static Throws( exceptionType, action) { } @@ -136,6 +144,44 @@ namespace .Assertions } } namespace . +{ + public class GroupAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchGroupAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class MatchIndexAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class RegexMatch + { + public int Index { get; } + public int Length { get; } + public string Value { get; } + public string GetGroup(int groupIndex) { } + public string GetGroup(string groupName) { } + } + public class RegexMatchCollection : .<..RegexMatch>, .<..RegexMatch>, .<..RegexMatch>, .IEnumerable + { + public int Count { get; } + public ..RegexMatch First { get; } + public ..RegexMatch this[int index] { get; } + public .<..RegexMatch> GetEnumerator() { } + } +} +namespace . { public class IsNotParsableIntoAssertion<[.(..None | ..PublicMethods | ..Interfaces)] T> : . { @@ -177,6 +223,7 @@ namespace .Attributes public AssertionFromAttribute( targetType, containingType, string methodName) { } public ? ContainingType { get; } public string? CustomName { get; set; } + public string? ExpectationMessage { get; set; } public string MethodName { get; } public bool NegateLogic { get; set; } public bool RequiresGenericTypeParameter { get; set; } @@ -197,36 +244,6 @@ namespace .Attributes public TargetType { get; } public bool TreatAsInstance { get; set; } } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future ve" + - "rsion.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute( targetType, string methodName) { } - public CreateAssertionAttribute( targetType, containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future" + - " version.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute(string methodName) { } - public CreateAssertionAttribute( containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } [(.Method, AllowMultiple=false, Inherited=false)] public sealed class GenerateAssertionAttribute : { @@ -319,6 +336,15 @@ namespace .Conditions public . InclusiveMaximum() { } public . InclusiveMinimum() { } } + [.<.BigInteger>("IsEven", CustomName="IsNotEven", ExpectationMessage="be even", NegateLogic=true)] + [.<.BigInteger>("IsEven", ExpectationMessage="be even")] + [.<.BigInteger>("IsOne", CustomName="IsNotOne", ExpectationMessage="be one", NegateLogic=true)] + [.<.BigInteger>("IsOne", ExpectationMessage="be one")] + [.<.BigInteger>("IsPowerOfTwo", CustomName="IsNotPowerOfTwo", ExpectationMessage="be a power of two", NegateLogic=true)] + [.<.BigInteger>("IsPowerOfTwo", ExpectationMessage="be a power of two")] + [.<.BigInteger>("IsZero", CustomName="IsNotZero", ExpectationMessage="be zero", NegateLogic=true)] + [.<.BigInteger>("IsZero", ExpectationMessage="be zero")] + public static class BigIntegerAssertionExtensions { } public static class BooleanAssertionExtensions { [.(ExpectationMessage="to be false")] @@ -532,6 +558,13 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.<.Cookie>("Expired", CustomName="IsNotExpired", ExpectationMessage="be expired", NegateLogic=true)] + [.<.Cookie>("Expired", ExpectationMessage="be expired")] + [.<.Cookie>("HttpOnly", CustomName="IsNotHttpOnly", ExpectationMessage="be HTTP-only", NegateLogic=true)] + [.<.Cookie>("HttpOnly", ExpectationMessage="be HTTP-only")] + [.<.Cookie>("Secure", CustomName="IsNotSecure", ExpectationMessage="be secure", NegateLogic=true)] + [.<.Cookie>("Secure", ExpectationMessage="be secure")] + public static class CookieAssertionExtensions { } [.<.CultureInfo>("IsNeutralCulture", CustomName="IsNotNeutralCulture", ExpectationMessage="be a neutral culture", NegateLogic=true)] [.<.CultureInfo>("IsNeutralCulture", ExpectationMessage="be a neutral culture")] [.<.CultureInfo>("IsReadOnly", ExpectationMessage="be read-only culture")] @@ -738,6 +771,21 @@ namespace .Conditions [.(ExpectationMessage="to be a system directory")] public static bool IsSystemDirectory(this .DirectoryInfo value) { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class DoubleAssertionExtensions { } [.("IsEqualTo", OverloadResolutionPriority=2)] public class DoubleEqualsAssertion : . { @@ -955,6 +1003,9 @@ namespace .Conditions public . GetAwaiter() { } protected override string GetExpectation() { } } + [.<.>("IsSuccessStatusCode", CustomName="IsNotSuccessStatusCode", ExpectationMessage="have a success status code", NegateLogic=true)] + [.<.>("IsSuccessStatusCode", ExpectationMessage="have a success status code")] + public static class HttpResponseMessageAssertionExtensions { } public static class HttpStatusCodeAssertionExtensions { [.(ExpectationMessage="to be a client error status code (4xx)")] @@ -1046,14 +1097,6 @@ namespace .Conditions protected override string GetExpectation() { } public . Using(. comparer) { } } - [.("IsIn")] - public class IsInAssertion : . - { - public IsInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } [.("IsNotAssignableTo")] public class IsNotAssignableToAssertion : . { @@ -1085,14 +1128,6 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("IsNotIn")] - public class IsNotInAssertion : . - { - public IsNotInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } public class IsTypeOfRuntimeAssertion : . { public IsTypeOfRuntimeAssertion(. context, expectedType) { } @@ -1199,6 +1234,9 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.(typeof(int?), "HasValue", CustomName="DoesNotHaveValue", ExpectationMessage="have a value", NegateLogic=true)] + [.(typeof(int?), "HasValue", ExpectationMessage="have a value")] + public static class NullableAssertionExtensions { } [.("IsEquatableTo")] public class NullableEquatableAssertion : . where TActual : struct, @@ -1225,6 +1263,33 @@ namespace .Conditions [.(ExpectationMessage="to be the all range")] public static bool IsAll(this value) { } } + [.<.Rune>("IsAscii", CustomName="IsNotAscii", ExpectationMessage="be ASCII", NegateLogic=true)] + [.<.Rune>("IsAscii", ExpectationMessage="be ASCII")] + [.<.Rune>("IsBmp", CustomName="IsNotBmp", ExpectationMessage="be in the Basic Multilingual Plane", NegateLogic=true)] + [.<.Rune>("IsBmp", ExpectationMessage="be in the Basic Multilingual Plane")] + [.<.Rune>(typeof(.Rune), "IsControl", CustomName="IsNotControl", ExpectationMessage="be a control character", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsControl", ExpectationMessage="be a control character")] + [.<.Rune>(typeof(.Rune), "IsDigit", CustomName="IsNotDigit", ExpectationMessage="be a digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsDigit", ExpectationMessage="be a digit")] + [.<.Rune>(typeof(.Rune), "IsLetter", CustomName="IsNotLetter", ExpectationMessage="be a letter", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetter", ExpectationMessage="be a letter")] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", CustomName="IsNotLetterOrDigit", ExpectationMessage="be a letter or digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", ExpectationMessage="be a letter or digit")] + [.<.Rune>(typeof(.Rune), "IsLower", CustomName="IsNotLower", ExpectationMessage="be lowercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLower", ExpectationMessage="be lowercase")] + [.<.Rune>(typeof(.Rune), "IsNumber", CustomName="IsNotNumber", ExpectationMessage="be a number", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsNumber", ExpectationMessage="be a number")] + [.<.Rune>(typeof(.Rune), "IsPunctuation", CustomName="IsNotPunctuation", ExpectationMessage="be punctuation", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsPunctuation", ExpectationMessage="be punctuation")] + [.<.Rune>(typeof(.Rune), "IsSeparator", CustomName="IsNotSeparator", ExpectationMessage="be a separator", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSeparator", ExpectationMessage="be a separator")] + [.<.Rune>(typeof(.Rune), "IsSymbol", CustomName="IsNotSymbol", ExpectationMessage="be a symbol", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSymbol", ExpectationMessage="be a symbol")] + [.<.Rune>(typeof(.Rune), "IsUpper", CustomName="IsNotUpper", ExpectationMessage="be uppercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsUpper", ExpectationMessage="be uppercase")] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", CustomName="IsNotWhiteSpace", ExpectationMessage="be whitespace", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", ExpectationMessage="be whitespace")] + public static class RuneAssertionExtensions { } [.("IsSameReferenceAs")] public class SameReferenceAssertion : . { @@ -1238,6 +1303,26 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class SingleAssertionExtensions { } + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + public static class SpanAssertionExtensions { } [.<.Stream>("CanRead", CustomName="CannotRead", ExpectationMessage="be readable", NegateLogic=true)] [.<.Stream>("CanRead", ExpectationMessage="be readable")] [.<.Stream>("CanSeek", CustomName="CannotSeek", ExpectationMessage="be seekable", NegateLogic=true)] @@ -1312,6 +1397,7 @@ namespace .Conditions public class StringEqualsAssertion : . { public StringEqualsAssertion(. context, string? expected) { } + public StringEqualsAssertion(. context, string? expected, comparison) { } protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } @@ -1340,12 +1426,11 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("Matches")] - public class StringMatchesAssertion : . + public class StringMatchesAssertion : .<..RegexMatchCollection> { public StringMatchesAssertion(. context, . regex) { } public StringMatchesAssertion(. context, string pattern) { } - protected override .<.> CheckAsync(. metadata) { } + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } public . WithOptions(. options) { } @@ -1565,6 +1650,15 @@ namespace .Conditions [.<>("UserEscaped", CustomName="IsNotUserEscaped", ExpectationMessage="be user-escaped", NegateLogic=true)] [.<>("UserEscaped", ExpectationMessage="be user-escaped")] public static class UriAssertionExtensions { } + [.<.>("IsCanceled", CustomName="IsNotCanceled", ExpectationMessage="be canceled", NegateLogic=true)] + [.<.>("IsCanceled", ExpectationMessage="be canceled")] + [.<.>("IsCompleted", CustomName="IsNotCompleted", ExpectationMessage="be completed", NegateLogic=true)] + [.<.>("IsCompleted", ExpectationMessage="be completed")] + [.<.>("IsCompletedSuccessfully", CustomName="IsNotCompletedSuccessfully", ExpectationMessage="be completed successfully", NegateLogic=true)] + [.<.>("IsCompletedSuccessfully", ExpectationMessage="be completed successfully")] + [.<.>("IsFaulted", CustomName="IsNotFaulted", ExpectationMessage="be faulted", NegateLogic=true)] + [.<.>("IsFaulted", ExpectationMessage="be faulted")] + public static class ValueTaskAssertionExtensions { } public static class VersionAssertionExtensions { [.(ExpectationMessage="to have a build number")] @@ -1580,6 +1674,12 @@ namespace .Conditions [.(ExpectationMessage="to not be a major version")] public static bool IsNotMajorVersion(this value) { } } + public class WaitsForAssertion : . + { + public WaitsForAssertion(. context, <., .> assertionBuilder, timeout, ? pollingInterval = default) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } [.<>("IsAlive", CustomName="IsNotAlive", ExpectationMessage="be alive", NegateLogic=true)] [.<>("IsAlive", ExpectationMessage="be alive")] [.<>("TrackResurrection", CustomName="DoesNotTrackResurrection", ExpectationMessage="track resurrection", NegateLogic=true)] @@ -1703,6 +1803,10 @@ namespace .Core public . Map( mapper) { } public . MapException() where TException : { } + [return: .(new string?[]?[] { + "Value", + "Exception"})] + public .<> ReevaluateAsync() { } } public readonly struct EvaluationMetadata { @@ -1871,10 +1975,8 @@ namespace .Extensions public static .<> IsBeforeOrEqualTo(this .<> source, expected, [.("expected")] string? expression = null) { } public static ..IsDefinedAssertion IsDefined(this . source) where TEnum : struct, { } - public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expression = null) { } [.("Uses reflection to compare members")] public static . IsEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsIn(this . source, params TValue[] collection) { } public static . IsNegative(this . source) where TValue : { } public static . IsNegative(this . source) @@ -1884,7 +1986,6 @@ namespace .Extensions where TEnum : struct, { } [.("Uses reflection to compare members")] public static . IsNotEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsNotIn(this . source, params TValue[] collection) { } public static . IsNotNull(this . source) where TValue : class { } public static . IsNotNull(this . source) @@ -1914,7 +2015,7 @@ namespace .Extensions public static . Member(this . source, .<> memberSelector, <., .> assertions) { } public static . Member(this . source, .<>> memberSelector, <.<., TKey, TValue>, .> assertions) { } public static . Satisfies(this . source, predicate, [.("predicate")] string? expression = null) { } - public static . Satisfies(this . source, > selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } + public static . Satisfies(this . source, > selector, <., .> assertions, [.("selector")] string? selectorExpression = null) { } public static . Satisfies(this . source, selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } public static . Throws(this . source) where TException : { } @@ -1934,6 +2035,7 @@ namespace .Extensions public static . ThrowsException(this . source) where TException : { } public static . ThrowsNothing(this . source) { } + public static . WaitsFor(this . source, <., .> assertionBuilder, timeout, ? pollingInterval = default, [.("timeout")] string? timeoutExpression = null, [.("pollingInterval")] string? pollingIntervalExpression = null) { } public static ..WhenParsedIntoAssertion WhenParsedInto<[.(..None | ..PublicMethods | ..Interfaces)] T>(this . source) { } public static . WithMessage(this . source, string expectedMessage, [.("expectedMessage")] string? expression = null) where TException : { } @@ -1959,6 +2061,41 @@ namespace .Extensions public static . IsBetween(this . source, TValue minimum, TValue maximum, [.("minimum")] string? minimumExpression = null, [.("maximum")] string? maximumExpression = null) where TValue : { } } + public static class BigIntegerAssertionExtensions + { + public static . IsEven(this .<.BigInteger> source) { } + public static . IsNotEven(this .<.BigInteger> source) { } + public static . IsNotOne(this .<.BigInteger> source) { } + public static . IsNotPowerOfTwo(this .<.BigInteger> source) { } + public static . IsNotZero(this .<.BigInteger> source) { } + public static . IsOne(this .<.BigInteger> source) { } + public static . IsPowerOfTwo(this .<.BigInteger> source) { } + public static . IsZero(this .<.BigInteger> source) { } + } + public class BigIntegerIsEvenAssertion : .<.BigInteger> + { + public BigIntegerIsEvenAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsOneAssertion : .<.BigInteger> + { + public BigIntegerIsOneAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsPowerOfTwoAssertion : .<.BigInteger> + { + public BigIntegerIsPowerOfTwoAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsZeroAssertion : .<.BigInteger> + { + public BigIntegerIsZeroAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } public sealed class Bool_IsFalse_Assertion : . { public Bool_IsFalse_Assertion(. context) { } @@ -2166,6 +2303,33 @@ namespace .Extensions public static . IsInOrder(this . source) where TCollection : . { } } + public static class CookieAssertionExtensions + { + public static . Expired(this .<.Cookie> source) { } + public static . HttpOnly(this .<.Cookie> source) { } + public static . IsNotExpired(this .<.Cookie> source) { } + public static . IsNotHttpOnly(this .<.Cookie> source) { } + public static . IsNotSecure(this .<.Cookie> source) { } + public static . Secure(this .<.Cookie> source) { } + } + public class CookieExpiredAssertion : .<.Cookie> + { + public CookieExpiredAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieHttpOnlyAssertion : .<.Cookie> + { + public CookieHttpOnlyAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieSecureAssertion : .<.Cookie> + { + public CookieSecureAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } public static class CultureInfoAssertionExtensions { public static ._IsEnglish_Assertion IsEnglish(this .<.CultureInfo> source) { } @@ -2600,10 +2764,69 @@ namespace .Extensions protected override .<.> CheckAsync(.<.DirectoryInfo> metadata) { } protected override string GetExpectation() { } } + public static class DoubleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } public static class DoubleEqualsAssertionExtensions { public static . IsEqualTo(this . source, double expected, [.("expected")] string? expectedExpression = null) { } } + public class DoubleIsFiniteWithDoubleAssertion : . + { + public DoubleIsFiniteWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsInfinityWithDoubleAssertion : . + { + public DoubleIsInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNaNWithDoubleAssertion : . + { + public DoubleIsNaNWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNegativeInfinityWithDoubleAssertion : . + { + public DoubleIsNegativeInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNormalWithDoubleAssertion : . + { + public DoubleIsNormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsPositiveInfinityWithDoubleAssertion : . + { + public DoubleIsPositiveInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsSubnormalWithDoubleAssertion : . + { + public DoubleIsSubnormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class EncodingAssertionExtensions { public static ._IsASCII_Assertion IsASCII(this .<.Encoding> source) { } @@ -2827,6 +3050,63 @@ namespace .Extensions { public static . IsEqualTo(this . source, float expected, [.("expected")] string? expectedExpression = null) { } } + public class FloatIsFiniteWithFloatAssertion : . + { + public FloatIsFiniteWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsInfinityWithFloatAssertion : . + { + public FloatIsInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNaNWithFloatAssertion : . + { + public FloatIsNaNWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNegativeInfinityWithFloatAssertion : . + { + public FloatIsNegativeInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNormalWithFloatAssertion : . + { + public FloatIsNormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsPositiveInfinityWithFloatAssertion : . + { + public FloatIsPositiveInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsSubnormalWithFloatAssertion : . + { + public FloatIsSubnormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public static class GenericAssertions + { + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn__Assertion IsIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_Assertion IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_IEqualityComparerT_Assertion IsIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn__Assertion IsNotIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_Assertion IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion IsNotIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + } public static class GreaterThanAssertionExtensions { public static . IsGreaterThan(this . source, TValue minimum, [.("minimum")] string? minimumExpression = null) @@ -2859,6 +3139,17 @@ namespace .Extensions public static . HasSingleItem(this . source) where TCollection : . { } } + public static class HttpResponseMessageAssertionExtensions + { + public static . IsNotSuccessStatusCode(this .<.> source) { } + public static . IsSuccessStatusCode(this .<.> source) { } + } + public class HttpResponseMessageIsSuccessStatusCodeAssertion : .<.> + { + public HttpResponseMessageIsSuccessStatusCodeAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class HttpStatusCodeAssertionExtensions { public static ._IsClientError_Assertion IsClientError(this .<.HttpStatusCode> source) { } @@ -3034,10 +3325,6 @@ namespace .Extensions public static . IsEquivalentTo(this . source, . expected, . comparer, . ordering = 0, [.("expected")] string? expectedExpression = null, [.("comparer")] string? comparerExpression = null, [.("ordering")] string? orderingExpression = null) where TCollection : . { } } - public static class IsInAssertionExtensions - { - public static . IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class IsNotAssignableToAssertionExtensions { public static . IsNotAssignableTo(this . source) { } @@ -3057,10 +3344,6 @@ namespace .Extensions public static . IsNotDefault(this . source) where TValue : class { } } - public static class IsNotInAssertionExtensions - { - public static . IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class LazyAssertionExtensions { [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] @@ -3115,6 +3398,11 @@ namespace .Extensions { public static . IsNull(this . source) { } } + public static class NullableAssertionExtensions + { + public static . DoesNotHaveValue(this . source) { } + public static . HasValue(this . source) { } + } public sealed class NullableBool_IsFalse_Assertion : . { public NullableBool_IsFalse_Assertion(. context) { } @@ -3132,6 +3420,12 @@ namespace .Extensions public static . IsEquatableTo(this . source, TExpected expected, [.("expected")] string? expectedExpression = null) where TActual : struct, { } } + public class NullableHasValueAssertion : . + { + public NullableHasValueAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class ProcessAssertionExtensions { public static . DoesNotHaveEventRaisingEnabled(this .<.Process> source) { } @@ -3195,10 +3489,148 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class RegexAssertionExtensions + { + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, string groupName, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, int groupIndex, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, string groupName, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, string groupName, <., .?> assertion) { } + public static ..MatchIndexAssertion Match(this .<..RegexMatchCollection> continuation, int index) { } + public static ..MatchAssertion Match(this .<..RegexMatchCollection> continuation, int index, <.<..RegexMatch>, .<..RegexMatch>?> assertion) { } + public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } + public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } + } + public static class RuneAssertionExtensions + { + public static . IsAscii(this .<.Rune> source) { } + public static . IsBmp(this .<.Rune> source) { } + public static . IsControl(this .<.Rune> source) { } + public static . IsDigit(this .<.Rune> source) { } + public static . IsLetter(this .<.Rune> source) { } + public static . IsLetterOrDigit(this .<.Rune> source) { } + public static . IsLower(this .<.Rune> source) { } + public static . IsNotAscii(this .<.Rune> source) { } + public static . IsNotBmp(this .<.Rune> source) { } + public static . IsNotControl(this .<.Rune> source) { } + public static . IsNotDigit(this .<.Rune> source) { } + public static . IsNotLetter(this .<.Rune> source) { } + public static . IsNotLetterOrDigit(this .<.Rune> source) { } + public static . IsNotLower(this .<.Rune> source) { } + public static . IsNotNumber(this .<.Rune> source) { } + public static . IsNotPunctuation(this .<.Rune> source) { } + public static . IsNotSeparator(this .<.Rune> source) { } + public static . IsNotSymbol(this .<.Rune> source) { } + public static . IsNotUpper(this .<.Rune> source) { } + public static . IsNotWhiteSpace(this .<.Rune> source) { } + public static . IsNumber(this .<.Rune> source) { } + public static . IsPunctuation(this .<.Rune> source) { } + public static . IsSeparator(this .<.Rune> source) { } + public static . IsSymbol(this .<.Rune> source) { } + public static . IsUpper(this .<.Rune> source) { } + public static . IsWhiteSpace(this .<.Rune> source) { } + } + public class RuneIsAsciiAssertion : .<.Rune> + { + public RuneIsAsciiAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsBmpAssertion : .<.Rune> + { + public RuneIsBmpAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsControlWithRuneAssertion : .<.Rune> + { + public RuneIsControlWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsDigitWithRuneAssertion : .<.Rune> + { + public RuneIsDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterOrDigitWithRuneAssertion : .<.Rune> + { + public RuneIsLetterOrDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterWithRuneAssertion : .<.Rune> + { + public RuneIsLetterWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLowerWithRuneAssertion : .<.Rune> + { + public RuneIsLowerWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsNumberWithRuneAssertion : .<.Rune> + { + public RuneIsNumberWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsPunctuationWithRuneAssertion : .<.Rune> + { + public RuneIsPunctuationWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSeparatorWithRuneAssertion : .<.Rune> + { + public RuneIsSeparatorWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSymbolWithRuneAssertion : .<.Rune> + { + public RuneIsSymbolWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsUpperWithRuneAssertion : .<.Rune> + { + public RuneIsUpperWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsWhiteSpaceWithRuneAssertion : .<.Rune> + { + public RuneIsWhiteSpaceWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } public static class SameReferenceAssertionExtensions { public static . IsSameReferenceAs(this . source, object? expected, [.("expected")] string? expectedExpression = null) { } } + public static class SingleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } + public static class SpanAssertionExtensions { } public static class StreamAssertionExtensions { public static . CanRead(this .<.Stream> source) { } @@ -3309,6 +3741,7 @@ namespace .Extensions public static class StringEqualsAssertionExtensions { public static . IsEqualTo(this . source, string? expected, [.("expected")] string? expectedExpression = null) { } + public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expectedExpression = null, [.("comparison")] string? comparisonExpression = null) { } } public static class StringIsEmptyAssertionExtensions { @@ -3330,11 +3763,6 @@ namespace .Extensions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - public static class StringMatchesAssertionExtensions - { - public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } - public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } - } public static class StringStartsWithAssertionExtensions { public static . StartsWith(this . source, string expected, [.("expected")] string? expectedExpression = null) { } @@ -3347,6 +3775,48 @@ namespace .Extensions public static . IsNullOrEmpty(this . source) { } public static . IsNullOrWhiteSpace(this . source) { } } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_Assertion : . + { + public T_IsIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn__Assertion : . + { + public T_IsIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_Assertion : . + { + public T_IsNotIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn__Assertion : . + { + public T_IsNotIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class TaskAssertionExtensions { public static . IsCanceled(this . source) @@ -3783,6 +4253,41 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class ValueTaskAssertionExtensions + { + public static . IsCanceled(this .<.> source) { } + public static . IsCompleted(this .<.> source) { } + public static . IsCompletedSuccessfully(this .<.> source) { } + public static . IsFaulted(this .<.> source) { } + public static . IsNotCanceled(this .<.> source) { } + public static . IsNotCompleted(this .<.> source) { } + public static . IsNotCompletedSuccessfully(this .<.> source) { } + public static . IsNotFaulted(this .<.> source) { } + } + public class ValueTaskIsCanceledAssertion : .<.> + { + public ValueTaskIsCanceledAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedAssertion : .<.> + { + public ValueTaskIsCompletedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedSuccessfullyAssertion : .<.> + { + public ValueTaskIsCompletedSuccessfullyAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsFaultedAssertion : .<.> + { + public ValueTaskIsFaultedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class VersionAssertionExtensions { public static ._HasBuildNumber_Assertion HasBuildNumber(this .<> source) { } diff --git a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet9_0.verified.txt b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet9_0.verified.txt index 941d60bc07..cb85a09ae9 100644 --- a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet9_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.DotNet9_0.verified.txt @@ -5,6 +5,14 @@ namespace { public static void Fail(string reason) { } public static Multiple() { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : class { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : struct { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : class { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : struct { } public static . That( action, [.("action")] string? expression = null) { } public static . That(.IEnumerable value, [.("value")] string? expression = null) { } public static . That(<.> action, [.("action")] string? expression = null) { } @@ -15,7 +23,7 @@ namespace public static . That(.? value, [.("value")] string? expression = null) { } public static . That(<.> func, [.("func")] string? expression = null) { } public static . That( func, [.("func")] string? expression = null) { } - public static . That(. task, [.("task")] string? expression = null) { } + public static . That(. task, [.("task")] string? expression = null) { } public static . That(TValue? value, [.("value")] string? expression = null) { } [.(3)] public static . That(. value, [.("value")] string? expression = null) { } @@ -139,6 +147,44 @@ namespace .Assertions } } namespace . +{ + public class GroupAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchGroupAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class MatchIndexAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class RegexMatch + { + public int Index { get; } + public int Length { get; } + public string Value { get; } + public string GetGroup(int groupIndex) { } + public string GetGroup(string groupName) { } + } + public class RegexMatchCollection : .<..RegexMatch>, .<..RegexMatch>, .<..RegexMatch>, .IEnumerable + { + public int Count { get; } + public ..RegexMatch First { get; } + public ..RegexMatch this[int index] { get; } + public .<..RegexMatch> GetEnumerator() { } + } +} +namespace . { public class IsNotParsableIntoAssertion<[.(..None | ..PublicMethods | ..Interfaces)] T> : . { @@ -180,6 +226,7 @@ namespace .Attributes public AssertionFromAttribute( targetType, containingType, string methodName) { } public ? ContainingType { get; } public string? CustomName { get; set; } + public string? ExpectationMessage { get; set; } public string MethodName { get; } public bool NegateLogic { get; set; } public bool RequiresGenericTypeParameter { get; set; } @@ -200,36 +247,6 @@ namespace .Attributes public TargetType { get; } public bool TreatAsInstance { get; set; } } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future ve" + - "rsion.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute( targetType, string methodName) { } - public CreateAssertionAttribute( targetType, containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future" + - " version.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute(string methodName) { } - public CreateAssertionAttribute( containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } [(.Method, AllowMultiple=false, Inherited=false)] public sealed class GenerateAssertionAttribute : { @@ -322,6 +339,15 @@ namespace .Conditions public . InclusiveMaximum() { } public . InclusiveMinimum() { } } + [.<.BigInteger>("IsEven", CustomName="IsNotEven", ExpectationMessage="be even", NegateLogic=true)] + [.<.BigInteger>("IsEven", ExpectationMessage="be even")] + [.<.BigInteger>("IsOne", CustomName="IsNotOne", ExpectationMessage="be one", NegateLogic=true)] + [.<.BigInteger>("IsOne", ExpectationMessage="be one")] + [.<.BigInteger>("IsPowerOfTwo", CustomName="IsNotPowerOfTwo", ExpectationMessage="be a power of two", NegateLogic=true)] + [.<.BigInteger>("IsPowerOfTwo", ExpectationMessage="be a power of two")] + [.<.BigInteger>("IsZero", CustomName="IsNotZero", ExpectationMessage="be zero", NegateLogic=true)] + [.<.BigInteger>("IsZero", ExpectationMessage="be zero")] + public static class BigIntegerAssertionExtensions { } public static class BooleanAssertionExtensions { [.(ExpectationMessage="to be false")] @@ -535,6 +561,13 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.<.Cookie>("Expired", CustomName="IsNotExpired", ExpectationMessage="be expired", NegateLogic=true)] + [.<.Cookie>("Expired", ExpectationMessage="be expired")] + [.<.Cookie>("HttpOnly", CustomName="IsNotHttpOnly", ExpectationMessage="be HTTP-only", NegateLogic=true)] + [.<.Cookie>("HttpOnly", ExpectationMessage="be HTTP-only")] + [.<.Cookie>("Secure", CustomName="IsNotSecure", ExpectationMessage="be secure", NegateLogic=true)] + [.<.Cookie>("Secure", ExpectationMessage="be secure")] + public static class CookieAssertionExtensions { } [.<.CultureInfo>("IsNeutralCulture", CustomName="IsNotNeutralCulture", ExpectationMessage="be a neutral culture", NegateLogic=true)] [.<.CultureInfo>("IsNeutralCulture", ExpectationMessage="be a neutral culture")] [.<.CultureInfo>("IsReadOnly", ExpectationMessage="be read-only culture")] @@ -741,6 +774,21 @@ namespace .Conditions [.(ExpectationMessage="to be a system directory")] public static bool IsSystemDirectory(this .DirectoryInfo value) { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class DoubleAssertionExtensions { } [.("IsEqualTo", OverloadResolutionPriority=2)] public class DoubleEqualsAssertion : . { @@ -958,6 +1006,9 @@ namespace .Conditions public . GetAwaiter() { } protected override string GetExpectation() { } } + [.<.>("IsSuccessStatusCode", CustomName="IsNotSuccessStatusCode", ExpectationMessage="have a success status code", NegateLogic=true)] + [.<.>("IsSuccessStatusCode", ExpectationMessage="have a success status code")] + public static class HttpResponseMessageAssertionExtensions { } public static class HttpStatusCodeAssertionExtensions { [.(ExpectationMessage="to be a client error status code (4xx)")] @@ -1049,14 +1100,6 @@ namespace .Conditions protected override string GetExpectation() { } public . Using(. comparer) { } } - [.("IsIn")] - public class IsInAssertion : . - { - public IsInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } [.("IsNotAssignableTo")] public class IsNotAssignableToAssertion : . { @@ -1088,14 +1131,6 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("IsNotIn")] - public class IsNotInAssertion : . - { - public IsNotInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } public class IsTypeOfRuntimeAssertion : . { public IsTypeOfRuntimeAssertion(. context, expectedType) { } @@ -1202,6 +1237,9 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.(typeof(int?), "HasValue", CustomName="DoesNotHaveValue", ExpectationMessage="have a value", NegateLogic=true)] + [.(typeof(int?), "HasValue", ExpectationMessage="have a value")] + public static class NullableAssertionExtensions { } [.("IsEquatableTo")] public class NullableEquatableAssertion : . where TActual : struct, @@ -1228,6 +1266,33 @@ namespace .Conditions [.(ExpectationMessage="to be the all range")] public static bool IsAll(this value) { } } + [.<.Rune>("IsAscii", CustomName="IsNotAscii", ExpectationMessage="be ASCII", NegateLogic=true)] + [.<.Rune>("IsAscii", ExpectationMessage="be ASCII")] + [.<.Rune>("IsBmp", CustomName="IsNotBmp", ExpectationMessage="be in the Basic Multilingual Plane", NegateLogic=true)] + [.<.Rune>("IsBmp", ExpectationMessage="be in the Basic Multilingual Plane")] + [.<.Rune>(typeof(.Rune), "IsControl", CustomName="IsNotControl", ExpectationMessage="be a control character", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsControl", ExpectationMessage="be a control character")] + [.<.Rune>(typeof(.Rune), "IsDigit", CustomName="IsNotDigit", ExpectationMessage="be a digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsDigit", ExpectationMessage="be a digit")] + [.<.Rune>(typeof(.Rune), "IsLetter", CustomName="IsNotLetter", ExpectationMessage="be a letter", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetter", ExpectationMessage="be a letter")] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", CustomName="IsNotLetterOrDigit", ExpectationMessage="be a letter or digit", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLetterOrDigit", ExpectationMessage="be a letter or digit")] + [.<.Rune>(typeof(.Rune), "IsLower", CustomName="IsNotLower", ExpectationMessage="be lowercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsLower", ExpectationMessage="be lowercase")] + [.<.Rune>(typeof(.Rune), "IsNumber", CustomName="IsNotNumber", ExpectationMessage="be a number", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsNumber", ExpectationMessage="be a number")] + [.<.Rune>(typeof(.Rune), "IsPunctuation", CustomName="IsNotPunctuation", ExpectationMessage="be punctuation", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsPunctuation", ExpectationMessage="be punctuation")] + [.<.Rune>(typeof(.Rune), "IsSeparator", CustomName="IsNotSeparator", ExpectationMessage="be a separator", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSeparator", ExpectationMessage="be a separator")] + [.<.Rune>(typeof(.Rune), "IsSymbol", CustomName="IsNotSymbol", ExpectationMessage="be a symbol", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsSymbol", ExpectationMessage="be a symbol")] + [.<.Rune>(typeof(.Rune), "IsUpper", CustomName="IsNotUpper", ExpectationMessage="be uppercase", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsUpper", ExpectationMessage="be uppercase")] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", CustomName="IsNotWhiteSpace", ExpectationMessage="be whitespace", NegateLogic=true)] + [.<.Rune>(typeof(.Rune), "IsWhiteSpace", ExpectationMessage="be whitespace")] + public static class RuneAssertionExtensions { } [.("IsSameReferenceAs")] public class SameReferenceAssertion : . { @@ -1241,6 +1306,26 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.("IsFinite", CustomName="IsNotFinite", ExpectationMessage="be finite", NegateLogic=true)] + [.("IsFinite", ExpectationMessage="be finite")] + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsNormal", CustomName="IsNotNormal", ExpectationMessage="be normal", NegateLogic=true)] + [.("IsNormal", ExpectationMessage="be normal")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + [.("IsSubnormal", CustomName="IsNotSubnormal", ExpectationMessage="be subnormal", NegateLogic=true)] + [.("IsSubnormal", ExpectationMessage="be subnormal")] + public static class SingleAssertionExtensions { } + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + [.(typeof(), "IsEmpty", CustomName="IsNotEmpty", ExpectationMessage="be empty", NegateLogic=true)] + [.(typeof(), "IsEmpty", ExpectationMessage="be empty")] + public static class SpanAssertionExtensions { } [.<.Stream>("CanRead", CustomName="CannotRead", ExpectationMessage="be readable", NegateLogic=true)] [.<.Stream>("CanRead", ExpectationMessage="be readable")] [.<.Stream>("CanSeek", CustomName="CannotSeek", ExpectationMessage="be seekable", NegateLogic=true)] @@ -1315,6 +1400,7 @@ namespace .Conditions public class StringEqualsAssertion : . { public StringEqualsAssertion(. context, string? expected) { } + public StringEqualsAssertion(. context, string? expected, comparison) { } protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } @@ -1343,12 +1429,11 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("Matches")] - public class StringMatchesAssertion : . + public class StringMatchesAssertion : .<..RegexMatchCollection> { public StringMatchesAssertion(. context, . regex) { } public StringMatchesAssertion(. context, string pattern) { } - protected override .<.> CheckAsync(. metadata) { } + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } public . WithOptions(. options) { } @@ -1568,6 +1653,15 @@ namespace .Conditions [.<>("UserEscaped", CustomName="IsNotUserEscaped", ExpectationMessage="be user-escaped", NegateLogic=true)] [.<>("UserEscaped", ExpectationMessage="be user-escaped")] public static class UriAssertionExtensions { } + [.<.>("IsCanceled", CustomName="IsNotCanceled", ExpectationMessage="be canceled", NegateLogic=true)] + [.<.>("IsCanceled", ExpectationMessage="be canceled")] + [.<.>("IsCompleted", CustomName="IsNotCompleted", ExpectationMessage="be completed", NegateLogic=true)] + [.<.>("IsCompleted", ExpectationMessage="be completed")] + [.<.>("IsCompletedSuccessfully", CustomName="IsNotCompletedSuccessfully", ExpectationMessage="be completed successfully", NegateLogic=true)] + [.<.>("IsCompletedSuccessfully", ExpectationMessage="be completed successfully")] + [.<.>("IsFaulted", CustomName="IsNotFaulted", ExpectationMessage="be faulted", NegateLogic=true)] + [.<.>("IsFaulted", ExpectationMessage="be faulted")] + public static class ValueTaskAssertionExtensions { } public static class VersionAssertionExtensions { [.(ExpectationMessage="to have a build number")] @@ -1583,6 +1677,12 @@ namespace .Conditions [.(ExpectationMessage="to not be a major version")] public static bool IsNotMajorVersion(this value) { } } + public class WaitsForAssertion : . + { + public WaitsForAssertion(. context, <., .> assertionBuilder, timeout, ? pollingInterval = default) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } [.<>("IsAlive", CustomName="IsNotAlive", ExpectationMessage="be alive", NegateLogic=true)] [.<>("IsAlive", ExpectationMessage="be alive")] [.<>("TrackResurrection", CustomName="DoesNotTrackResurrection", ExpectationMessage="track resurrection", NegateLogic=true)] @@ -1706,6 +1806,10 @@ namespace .Core public . Map( mapper) { } public . MapException() where TException : { } + [return: .(new string?[]?[] { + "Value", + "Exception"})] + public .<> ReevaluateAsync() { } } public readonly struct EvaluationMetadata { @@ -1874,10 +1978,8 @@ namespace .Extensions public static .<> IsBeforeOrEqualTo(this .<> source, expected, [.("expected")] string? expression = null) { } public static ..IsDefinedAssertion IsDefined(this . source) where TEnum : struct, { } - public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expression = null) { } [.("Uses reflection to compare members")] public static . IsEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsIn(this . source, params TValue[] collection) { } public static . IsNegative(this . source) where TValue : { } public static . IsNegative(this . source) @@ -1887,7 +1989,6 @@ namespace .Extensions where TEnum : struct, { } [.("Uses reflection to compare members")] public static . IsNotEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsNotIn(this . source, params TValue[] collection) { } public static . IsNotNull(this . source) where TValue : class { } public static . IsNotNull(this . source) @@ -1924,7 +2025,7 @@ namespace .Extensions [.(3)] public static . Member(this . source, .<>> memberSelector, <.<., TKey, TValue>, .> assertions) { } public static . Satisfies(this . source, predicate, [.("predicate")] string? expression = null) { } - public static . Satisfies(this . source, > selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } + public static . Satisfies(this . source, > selector, <., .> assertions, [.("selector")] string? selectorExpression = null) { } public static . Satisfies(this . source, selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } public static . Throws(this . source) where TException : { } @@ -1944,6 +2045,7 @@ namespace .Extensions public static . ThrowsException(this . source) where TException : { } public static . ThrowsNothing(this . source) { } + public static . WaitsFor(this . source, <., .> assertionBuilder, timeout, ? pollingInterval = default, [.("timeout")] string? timeoutExpression = null, [.("pollingInterval")] string? pollingIntervalExpression = null) { } public static ..WhenParsedIntoAssertion WhenParsedInto<[.(..None | ..PublicMethods | ..Interfaces)] T>(this . source) { } public static . WithMessage(this . source, string expectedMessage, [.("expectedMessage")] string? expression = null) where TException : { } @@ -1969,6 +2071,41 @@ namespace .Extensions public static . IsBetween(this . source, TValue minimum, TValue maximum, [.("minimum")] string? minimumExpression = null, [.("maximum")] string? maximumExpression = null) where TValue : { } } + public static class BigIntegerAssertionExtensions + { + public static . IsEven(this .<.BigInteger> source) { } + public static . IsNotEven(this .<.BigInteger> source) { } + public static . IsNotOne(this .<.BigInteger> source) { } + public static . IsNotPowerOfTwo(this .<.BigInteger> source) { } + public static . IsNotZero(this .<.BigInteger> source) { } + public static . IsOne(this .<.BigInteger> source) { } + public static . IsPowerOfTwo(this .<.BigInteger> source) { } + public static . IsZero(this .<.BigInteger> source) { } + } + public class BigIntegerIsEvenAssertion : .<.BigInteger> + { + public BigIntegerIsEvenAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsOneAssertion : .<.BigInteger> + { + public BigIntegerIsOneAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsPowerOfTwoAssertion : .<.BigInteger> + { + public BigIntegerIsPowerOfTwoAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsZeroAssertion : .<.BigInteger> + { + public BigIntegerIsZeroAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } public sealed class Bool_IsFalse_Assertion : . { public Bool_IsFalse_Assertion(. context) { } @@ -2176,6 +2313,33 @@ namespace .Extensions public static . IsInOrder(this . source) where TCollection : . { } } + public static class CookieAssertionExtensions + { + public static . Expired(this .<.Cookie> source) { } + public static . HttpOnly(this .<.Cookie> source) { } + public static . IsNotExpired(this .<.Cookie> source) { } + public static . IsNotHttpOnly(this .<.Cookie> source) { } + public static . IsNotSecure(this .<.Cookie> source) { } + public static . Secure(this .<.Cookie> source) { } + } + public class CookieExpiredAssertion : .<.Cookie> + { + public CookieExpiredAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieHttpOnlyAssertion : .<.Cookie> + { + public CookieHttpOnlyAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieSecureAssertion : .<.Cookie> + { + public CookieSecureAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } public static class CultureInfoAssertionExtensions { public static ._IsEnglish_Assertion IsEnglish(this .<.CultureInfo> source) { } @@ -2614,11 +2778,70 @@ namespace .Extensions protected override .<.> CheckAsync(.<.DirectoryInfo> metadata) { } protected override string GetExpectation() { } } + public static class DoubleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } public static class DoubleEqualsAssertionExtensions { [.(2)] public static . IsEqualTo(this . source, double expected, [.("expected")] string? expectedExpression = null) { } } + public class DoubleIsFiniteWithDoubleAssertion : . + { + public DoubleIsFiniteWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsInfinityWithDoubleAssertion : . + { + public DoubleIsInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNaNWithDoubleAssertion : . + { + public DoubleIsNaNWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNegativeInfinityWithDoubleAssertion : . + { + public DoubleIsNegativeInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNormalWithDoubleAssertion : . + { + public DoubleIsNormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsPositiveInfinityWithDoubleAssertion : . + { + public DoubleIsPositiveInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsSubnormalWithDoubleAssertion : . + { + public DoubleIsSubnormalWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class EncodingAssertionExtensions { public static ._IsASCII_Assertion IsASCII(this .<.Encoding> source) { } @@ -2843,6 +3066,63 @@ namespace .Extensions [.(2)] public static . IsEqualTo(this . source, float expected, [.("expected")] string? expectedExpression = null) { } } + public class FloatIsFiniteWithFloatAssertion : . + { + public FloatIsFiniteWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsInfinityWithFloatAssertion : . + { + public FloatIsInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNaNWithFloatAssertion : . + { + public FloatIsNaNWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNegativeInfinityWithFloatAssertion : . + { + public FloatIsNegativeInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNormalWithFloatAssertion : . + { + public FloatIsNormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsPositiveInfinityWithFloatAssertion : . + { + public FloatIsPositiveInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsSubnormalWithFloatAssertion : . + { + public FloatIsSubnormalWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public static class GenericAssertions + { + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn__Assertion IsIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_Assertion IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsIn_IEnumerableT_IEqualityComparerT_Assertion IsIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn__Assertion IsNotIn(this . source, params T[] collection) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_Assertion IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public static .Extensions.T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion IsNotIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + } public static class GreaterThanAssertionExtensions { public static . IsGreaterThan(this . source, TValue minimum, [.("minimum")] string? minimumExpression = null) @@ -2875,6 +3155,17 @@ namespace .Extensions public static . HasSingleItem(this . source) where TCollection : . { } } + public static class HttpResponseMessageAssertionExtensions + { + public static . IsNotSuccessStatusCode(this .<.> source) { } + public static . IsSuccessStatusCode(this .<.> source) { } + } + public class HttpResponseMessageIsSuccessStatusCodeAssertion : .<.> + { + public HttpResponseMessageIsSuccessStatusCodeAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class HttpStatusCodeAssertionExtensions { public static ._IsClientError_Assertion IsClientError(this .<.HttpStatusCode> source) { } @@ -3051,10 +3342,6 @@ namespace .Extensions public static . IsEquivalentTo(this . source, . expected, . comparer, . ordering = 0, [.("expected")] string? expectedExpression = null, [.("comparer")] string? comparerExpression = null, [.("ordering")] string? orderingExpression = null) where TCollection : . { } } - public static class IsInAssertionExtensions - { - public static . IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class IsNotAssignableToAssertionExtensions { public static . IsNotAssignableTo(this . source) { } @@ -3074,10 +3361,6 @@ namespace .Extensions public static . IsNotDefault(this . source) where TValue : class { } } - public static class IsNotInAssertionExtensions - { - public static . IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class LazyAssertionExtensions { [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] @@ -3133,6 +3416,11 @@ namespace .Extensions { public static . IsNull(this . source) { } } + public static class NullableAssertionExtensions + { + public static . DoesNotHaveValue(this . source) { } + public static . HasValue(this . source) { } + } public sealed class NullableBool_IsFalse_Assertion : . { public NullableBool_IsFalse_Assertion(. context) { } @@ -3150,6 +3438,12 @@ namespace .Extensions public static . IsEquatableTo(this . source, TExpected expected, [.("expected")] string? expectedExpression = null) where TActual : struct, { } } + public class NullableHasValueAssertion : . + { + public NullableHasValueAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class ProcessAssertionExtensions { public static . DoesNotHaveEventRaisingEnabled(this .<.Process> source) { } @@ -3213,10 +3507,148 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class RegexAssertionExtensions + { + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, string groupName, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, int groupIndex, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, string groupName, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, string groupName, <., .?> assertion) { } + public static ..MatchIndexAssertion Match(this .<..RegexMatchCollection> continuation, int index) { } + public static ..MatchAssertion Match(this .<..RegexMatchCollection> continuation, int index, <.<..RegexMatch>, .<..RegexMatch>?> assertion) { } + public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } + public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } + } + public static class RuneAssertionExtensions + { + public static . IsAscii(this .<.Rune> source) { } + public static . IsBmp(this .<.Rune> source) { } + public static . IsControl(this .<.Rune> source) { } + public static . IsDigit(this .<.Rune> source) { } + public static . IsLetter(this .<.Rune> source) { } + public static . IsLetterOrDigit(this .<.Rune> source) { } + public static . IsLower(this .<.Rune> source) { } + public static . IsNotAscii(this .<.Rune> source) { } + public static . IsNotBmp(this .<.Rune> source) { } + public static . IsNotControl(this .<.Rune> source) { } + public static . IsNotDigit(this .<.Rune> source) { } + public static . IsNotLetter(this .<.Rune> source) { } + public static . IsNotLetterOrDigit(this .<.Rune> source) { } + public static . IsNotLower(this .<.Rune> source) { } + public static . IsNotNumber(this .<.Rune> source) { } + public static . IsNotPunctuation(this .<.Rune> source) { } + public static . IsNotSeparator(this .<.Rune> source) { } + public static . IsNotSymbol(this .<.Rune> source) { } + public static . IsNotUpper(this .<.Rune> source) { } + public static . IsNotWhiteSpace(this .<.Rune> source) { } + public static . IsNumber(this .<.Rune> source) { } + public static . IsPunctuation(this .<.Rune> source) { } + public static . IsSeparator(this .<.Rune> source) { } + public static . IsSymbol(this .<.Rune> source) { } + public static . IsUpper(this .<.Rune> source) { } + public static . IsWhiteSpace(this .<.Rune> source) { } + } + public class RuneIsAsciiAssertion : .<.Rune> + { + public RuneIsAsciiAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsBmpAssertion : .<.Rune> + { + public RuneIsBmpAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsControlWithRuneAssertion : .<.Rune> + { + public RuneIsControlWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsDigitWithRuneAssertion : .<.Rune> + { + public RuneIsDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterOrDigitWithRuneAssertion : .<.Rune> + { + public RuneIsLetterOrDigitWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLetterWithRuneAssertion : .<.Rune> + { + public RuneIsLetterWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsLowerWithRuneAssertion : .<.Rune> + { + public RuneIsLowerWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsNumberWithRuneAssertion : .<.Rune> + { + public RuneIsNumberWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsPunctuationWithRuneAssertion : .<.Rune> + { + public RuneIsPunctuationWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSeparatorWithRuneAssertion : .<.Rune> + { + public RuneIsSeparatorWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsSymbolWithRuneAssertion : .<.Rune> + { + public RuneIsSymbolWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsUpperWithRuneAssertion : .<.Rune> + { + public RuneIsUpperWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } + public class RuneIsWhiteSpaceWithRuneAssertion : .<.Rune> + { + public RuneIsWhiteSpaceWithRuneAssertion(.<.Rune> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Rune> metadata) { } + protected override string GetExpectation() { } + } public static class SameReferenceAssertionExtensions { public static . IsSameReferenceAs(this . source, object? expected, [.("expected")] string? expectedExpression = null) { } } + public static class SingleAssertionExtensions + { + public static . IsFinite(this . source) { } + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNormal(this . source) { } + public static . IsNotFinite(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotNormal(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsNotSubnormal(this . source) { } + public static . IsPositiveInfinity(this . source) { } + public static . IsSubnormal(this . source) { } + } + public static class SpanAssertionExtensions { } public static class StreamAssertionExtensions { public static . CanRead(this .<.Stream> source) { } @@ -3328,6 +3760,8 @@ namespace .Extensions { [.(2)] public static . IsEqualTo(this . source, string? expected, [.("expected")] string? expectedExpression = null) { } + [.(2)] + public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expectedExpression = null, [.("comparison")] string? comparisonExpression = null) { } } public static class StringIsEmptyAssertionExtensions { @@ -3349,11 +3783,6 @@ namespace .Extensions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - public static class StringMatchesAssertionExtensions - { - public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } - public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } - } public static class StringStartsWithAssertionExtensions { public static . StartsWith(this . source, string expected, [.("expected")] string? expectedExpression = null) { } @@ -3366,6 +3795,48 @@ namespace .Extensions public static . IsNullOrEmpty(this . source) { } public static . IsNullOrWhiteSpace(this . source) { } } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_Assertion : . + { + public T_IsIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsIn__Assertion : . + { + public T_IsIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_Assertion : . + { + public T_IsNotIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + [.("Trimming", "IL2091", Justification="Generic type parameter is only used for property access, not instantiation")] + public sealed class T_IsNotIn__Assertion : . + { + public T_IsNotIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class TaskAssertionExtensions { public static . IsCanceled(this . source) @@ -3804,6 +4275,41 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class ValueTaskAssertionExtensions + { + public static . IsCanceled(this .<.> source) { } + public static . IsCompleted(this .<.> source) { } + public static . IsCompletedSuccessfully(this .<.> source) { } + public static . IsFaulted(this .<.> source) { } + public static . IsNotCanceled(this .<.> source) { } + public static . IsNotCompleted(this .<.> source) { } + public static . IsNotCompletedSuccessfully(this .<.> source) { } + public static . IsNotFaulted(this .<.> source) { } + } + public class ValueTaskIsCanceledAssertion : .<.> + { + public ValueTaskIsCanceledAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedAssertion : .<.> + { + public ValueTaskIsCompletedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedSuccessfullyAssertion : .<.> + { + public ValueTaskIsCompletedSuccessfullyAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsFaultedAssertion : .<.> + { + public ValueTaskIsFaultedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class VersionAssertionExtensions { public static ._HasBuildNumber_Assertion HasBuildNumber(this .<> source) { } diff --git a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.Net4_7.verified.txt b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.Net4_7.verified.txt index 67f8cfe8c3..c415d7ee64 100644 --- a/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.Net4_7.verified.txt +++ b/TUnit.PublicAPI/Tests.Assertions_Library_Has_No_API_Changes.Net4_7.verified.txt @@ -5,6 +5,14 @@ namespace { public static void Fail(string reason) { } public static Multiple() { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : class { } + public static void NotNull([.] T? value, [.("value")] string? expression = null) + where T : struct { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : class { } + public static void Null(T? value, [.("value")] string? expression = null) + where T : struct { } public static . That( action, [.("action")] string? expression = null) { } public static . That(.IEnumerable value, [.("value")] string? expression = null) { } public static . That(<.> action, [.("action")] string? expression = null) { } @@ -13,7 +21,7 @@ namespace public static . That(.? value, [.("value")] string? expression = null) { } public static . That(<.> func, [.("func")] string? expression = null) { } public static . That( func, [.("func")] string? expression = null) { } - public static . That(. task, [.("task")] string? expression = null) { } + public static . That(. task, [.("task")] string? expression = null) { } public static . That(TValue? value, [.("value")] string? expression = null) { } public static . That(. value, [.("value")] string? expression = null) { } public static Throws( exceptionType, action) { } @@ -136,6 +144,44 @@ namespace .Assertions } } namespace . +{ + public class GroupAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchAssertion : .<..RegexMatchCollection> + { + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } + protected override string GetExpectation() { } + } + public class MatchGroupAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class MatchIndexAssertion : .<..RegexMatch> + { + protected override .<.> CheckAsync(.<..RegexMatch> metadata) { } + protected override string GetExpectation() { } + } + public class RegexMatch + { + public int Index { get; } + public int Length { get; } + public string Value { get; } + public string GetGroup(int groupIndex) { } + public string GetGroup(string groupName) { } + } + public class RegexMatchCollection : .<..RegexMatch>, .<..RegexMatch>, .<..RegexMatch>, .IEnumerable + { + public int Count { get; } + public ..RegexMatch First { get; } + public ..RegexMatch this[int index] { get; } + public .<..RegexMatch> GetEnumerator() { } + } +} +namespace . { public class IsNotParsableIntoAssertion : . { @@ -177,6 +223,7 @@ namespace .Attributes public AssertionFromAttribute( targetType, containingType, string methodName) { } public ? ContainingType { get; } public string? CustomName { get; set; } + public string? ExpectationMessage { get; set; } public string MethodName { get; } public bool NegateLogic { get; set; } public bool RequiresGenericTypeParameter { get; set; } @@ -197,36 +244,6 @@ namespace .Attributes public TargetType { get; } public bool TreatAsInstance { get; set; } } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future ve" + - "rsion.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute( targetType, string methodName) { } - public CreateAssertionAttribute( targetType, containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } - [(.Class, AllowMultiple=true)] - [("Use AssertionFromAttribute instead. This attribute will be removed in a future" + - " version.")] - public class CreateAssertionAttribute : - { - public CreateAssertionAttribute(string methodName) { } - public CreateAssertionAttribute( containingType, string methodName) { } - public ? ContainingType { get; } - public string? CustomName { get; set; } - public string MethodName { get; } - public bool NegateLogic { get; set; } - public bool RequiresGenericTypeParameter { get; set; } - public TargetType { get; } - public bool TreatAsInstance { get; set; } - } [(.Method, AllowMultiple=false, Inherited=false)] public sealed class GenerateAssertionAttribute : { @@ -317,6 +334,11 @@ namespace .Conditions public . InclusiveMaximum() { } public . InclusiveMinimum() { } } + [.<.BigInteger>("IsEven", CustomName="IsNotEven", ExpectationMessage="be even", NegateLogic=true)] + [.<.BigInteger>("IsEven", ExpectationMessage="be even")] + [.<.BigInteger>("IsZero", CustomName="IsNotZero", ExpectationMessage="be zero", NegateLogic=true)] + [.<.BigInteger>("IsZero", ExpectationMessage="be zero")] + public static class BigIntegerAssertionExtensions { } public static class BooleanAssertionExtensions { [.(ExpectationMessage="to be false")] @@ -530,6 +552,13 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.<.Cookie>("Expired", CustomName="IsNotExpired", ExpectationMessage="be expired", NegateLogic=true)] + [.<.Cookie>("Expired", ExpectationMessage="be expired")] + [.<.Cookie>("HttpOnly", CustomName="IsNotHttpOnly", ExpectationMessage="be HTTP-only", NegateLogic=true)] + [.<.Cookie>("HttpOnly", ExpectationMessage="be HTTP-only")] + [.<.Cookie>("Secure", CustomName="IsNotSecure", ExpectationMessage="be secure", NegateLogic=true)] + [.<.Cookie>("Secure", ExpectationMessage="be secure")] + public static class CookieAssertionExtensions { } [.<.CultureInfo>("IsNeutralCulture", CustomName="IsNotNeutralCulture", ExpectationMessage="be a neutral culture", NegateLogic=true)] [.<.CultureInfo>("IsNeutralCulture", ExpectationMessage="be a neutral culture")] [.<.CultureInfo>("IsReadOnly", ExpectationMessage="be read-only culture")] @@ -701,6 +730,15 @@ namespace .Conditions [.(ExpectationMessage="to be a system directory")] public static bool IsSystemDirectory(this .DirectoryInfo value) { } } + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + public static class DoubleAssertionExtensions { } [.("IsEqualTo", OverloadResolutionPriority=2)] public class DoubleEqualsAssertion : . { @@ -914,6 +952,9 @@ namespace .Conditions public . GetAwaiter() { } protected override string GetExpectation() { } } + [.<.>("IsSuccessStatusCode", CustomName="IsNotSuccessStatusCode", ExpectationMessage="have a success status code", NegateLogic=true)] + [.<.>("IsSuccessStatusCode", ExpectationMessage="have a success status code")] + public static class HttpResponseMessageAssertionExtensions { } public static class HttpStatusCodeAssertionExtensions { [.(ExpectationMessage="to be a client error status code (4xx)")] @@ -999,14 +1040,6 @@ namespace .Conditions protected override string GetExpectation() { } public . Using(. comparer) { } } - [.("IsIn")] - public class IsInAssertion : . - { - public IsInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } [.("IsNotAssignableTo")] public class IsNotAssignableToAssertion : . { @@ -1038,14 +1071,6 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("IsNotIn")] - public class IsNotInAssertion : . - { - public IsNotInAssertion(. context, . collection) { } - protected override .<.> CheckAsync(. metadata) { } - protected override string GetExpectation() { } - public . Using(. comparer) { } - } public class IsTypeOfRuntimeAssertion : . { public IsTypeOfRuntimeAssertion(. context, expectedType) { } @@ -1146,6 +1171,9 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.(typeof(int?), "HasValue", CustomName="DoesNotHaveValue", ExpectationMessage="have a value", NegateLogic=true)] + [.(typeof(int?), "HasValue", ExpectationMessage="have a value")] + public static class NullableAssertionExtensions { } [.("IsEquatableTo")] public class NullableEquatableAssertion : . where TActual : struct, @@ -1174,6 +1202,15 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } + [.("IsInfinity", CustomName="IsNotInfinity", ExpectationMessage="be infinity", NegateLogic=true)] + [.("IsInfinity", ExpectationMessage="be infinity")] + [.("IsNaN", CustomName="IsNotNaN", ExpectationMessage="be NaN", NegateLogic=true)] + [.("IsNaN", ExpectationMessage="be NaN")] + [.("IsNegativeInfinity", CustomName="IsNotNegativeInfinity", ExpectationMessage="be negative infinity", NegateLogic=true)] + [.("IsNegativeInfinity", ExpectationMessage="be negative infinity")] + [.("IsPositiveInfinity", CustomName="IsNotPositiveInfinity", ExpectationMessage="be positive infinity", NegateLogic=true)] + [.("IsPositiveInfinity", ExpectationMessage="be positive infinity")] + public static class SingleAssertionExtensions { } [.<.Stream>("CanRead", CustomName="CannotRead", ExpectationMessage="be readable", NegateLogic=true)] [.<.Stream>("CanRead", ExpectationMessage="be readable")] [.<.Stream>("CanSeek", CustomName="CannotSeek", ExpectationMessage="be seekable", NegateLogic=true)] @@ -1248,6 +1285,7 @@ namespace .Conditions public class StringEqualsAssertion : . { public StringEqualsAssertion(. context, string? expected) { } + public StringEqualsAssertion(. context, string? expected, comparison) { } protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } @@ -1276,12 +1314,11 @@ namespace .Conditions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - [.("Matches")] - public class StringMatchesAssertion : . + public class StringMatchesAssertion : .<..RegexMatchCollection> { public StringMatchesAssertion(. context, . regex) { } public StringMatchesAssertion(. context, string pattern) { } - protected override .<.> CheckAsync(. metadata) { } + protected override .<.> CheckAsync(.<..RegexMatchCollection> metadata) { } protected override string GetExpectation() { } public . IgnoringCase() { } public . WithOptions(. options) { } @@ -1469,6 +1506,15 @@ namespace .Conditions [.<>("UserEscaped", CustomName="IsNotUserEscaped", ExpectationMessage="be user-escaped", NegateLogic=true)] [.<>("UserEscaped", ExpectationMessage="be user-escaped")] public static class UriAssertionExtensions { } + [.<.>("IsCanceled", CustomName="IsNotCanceled", ExpectationMessage="be canceled", NegateLogic=true)] + [.<.>("IsCanceled", ExpectationMessage="be canceled")] + [.<.>("IsCompleted", CustomName="IsNotCompleted", ExpectationMessage="be completed", NegateLogic=true)] + [.<.>("IsCompleted", ExpectationMessage="be completed")] + [.<.>("IsCompletedSuccessfully", CustomName="IsNotCompletedSuccessfully", ExpectationMessage="be completed successfully", NegateLogic=true)] + [.<.>("IsCompletedSuccessfully", ExpectationMessage="be completed successfully")] + [.<.>("IsFaulted", CustomName="IsNotFaulted", ExpectationMessage="be faulted", NegateLogic=true)] + [.<.>("IsFaulted", ExpectationMessage="be faulted")] + public static class ValueTaskAssertionExtensions { } public static class VersionAssertionExtensions { [.(ExpectationMessage="to have a build number")] @@ -1484,6 +1530,12 @@ namespace .Conditions [.(ExpectationMessage="to not be a major version")] public static bool IsNotMajorVersion(this value) { } } + public class WaitsForAssertion : . + { + public WaitsForAssertion(. context, <., .> assertionBuilder, timeout, ? pollingInterval = default) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } [.<>("IsAlive", CustomName="IsNotAlive", ExpectationMessage="be alive", NegateLogic=true)] [.<>("IsAlive", ExpectationMessage="be alive")] [.<>("TrackResurrection", CustomName="DoesNotTrackResurrection", ExpectationMessage="track resurrection", NegateLogic=true)] @@ -1605,6 +1657,10 @@ namespace .Core public . Map( mapper) { } public . MapException() where TException : { } + [return: .(new string?[]?[] { + "Value", + "Exception"})] + public .<> ReevaluateAsync() { } } public readonly struct EvaluationMetadata { @@ -1751,9 +1807,7 @@ namespace .Extensions public static .<> IsBeforeOrEqualTo(this .<> source, expected, [.("expected")] string? expression = null) { } public static ..IsDefinedAssertion IsDefined(this . source) where TEnum : struct, { } - public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expression = null) { } public static . IsEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsIn(this . source, params TValue[] collection) { } public static . IsNegative(this . source) where TValue : { } public static . IsNegative(this . source) @@ -1762,7 +1816,6 @@ namespace .Extensions public static ..IsNotDefinedAssertion IsNotDefined(this . source) where TEnum : struct, { } public static . IsNotEquivalentTo(this . source, object? expected, [.("expected")] string? expression = null) { } - public static . IsNotIn(this . source, params TValue[] collection) { } public static . IsNotNull(this . source) where TValue : class { } public static . IsNotNull(this . source) @@ -1786,7 +1839,7 @@ namespace .Extensions public static . Member(this . source, .<> memberSelector, <., .> assertions) { } public static . Member(this . source, .<>> memberSelector, <.<., TKey, TValue>, .> assertions) { } public static . Satisfies(this . source, predicate, [.("predicate")] string? expression = null) { } - public static . Satisfies(this . source, > selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } + public static . Satisfies(this . source, > selector, <., .> assertions, [.("selector")] string? selectorExpression = null) { } public static . Satisfies(this . source, selector, <., .?> assertions, [.("selector")] string? selectorExpression = null) { } public static . Throws(this . source) where TException : { } @@ -1806,6 +1859,7 @@ namespace .Extensions public static . ThrowsException(this . source) where TException : { } public static . ThrowsNothing(this . source) { } + public static . WaitsFor(this . source, <., .> assertionBuilder, timeout, ? pollingInterval = default, [.("timeout")] string? timeoutExpression = null, [.("pollingInterval")] string? pollingIntervalExpression = null) { } public static ..WhenParsedIntoAssertion WhenParsedInto(this . source) { } public static . WithMessage(this . source, string expectedMessage, [.("expectedMessage")] string? expression = null) where TException : { } @@ -1831,6 +1885,25 @@ namespace .Extensions public static . IsBetween(this . source, TValue minimum, TValue maximum, [.("minimum")] string? minimumExpression = null, [.("maximum")] string? maximumExpression = null) where TValue : { } } + public static class BigIntegerAssertionExtensions + { + public static . IsEven(this .<.BigInteger> source) { } + public static . IsNotEven(this .<.BigInteger> source) { } + public static . IsNotZero(this .<.BigInteger> source) { } + public static . IsZero(this .<.BigInteger> source) { } + } + public class BigIntegerIsEvenAssertion : .<.BigInteger> + { + public BigIntegerIsEvenAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } + public class BigIntegerIsZeroAssertion : .<.BigInteger> + { + public BigIntegerIsZeroAssertion(.<.BigInteger> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.BigInteger> metadata) { } + protected override string GetExpectation() { } + } public sealed class Bool_IsFalse_Assertion : . { public Bool_IsFalse_Assertion(. context) { } @@ -2038,6 +2111,33 @@ namespace .Extensions public static . IsInOrder(this . source) where TCollection : . { } } + public static class CookieAssertionExtensions + { + public static . Expired(this .<.Cookie> source) { } + public static . HttpOnly(this .<.Cookie> source) { } + public static . IsNotExpired(this .<.Cookie> source) { } + public static . IsNotHttpOnly(this .<.Cookie> source) { } + public static . IsNotSecure(this .<.Cookie> source) { } + public static . Secure(this .<.Cookie> source) { } + } + public class CookieExpiredAssertion : .<.Cookie> + { + public CookieExpiredAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieHttpOnlyAssertion : .<.Cookie> + { + public CookieHttpOnlyAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } + public class CookieSecureAssertion : .<.Cookie> + { + public CookieSecureAssertion(.<.Cookie> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.Cookie> metadata) { } + protected override string GetExpectation() { } + } public static class CultureInfoAssertionExtensions { public static ._IsEnglish_Assertion IsEnglish(this .<.CultureInfo> source) { } @@ -2395,10 +2495,45 @@ namespace .Extensions protected override .<.> CheckAsync(.<.DirectoryInfo> metadata) { } protected override string GetExpectation() { } } + public static class DoubleAssertionExtensions + { + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsPositiveInfinity(this . source) { } + } public static class DoubleEqualsAssertionExtensions { public static . IsEqualTo(this . source, double expected, [.("expected")] string? expectedExpression = null) { } } + public class DoubleIsInfinityWithDoubleAssertion : . + { + public DoubleIsInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNaNWithDoubleAssertion : . + { + public DoubleIsNaNWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsNegativeInfinityWithDoubleAssertion : . + { + public DoubleIsNegativeInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class DoubleIsPositiveInfinityWithDoubleAssertion : . + { + public DoubleIsPositiveInfinityWithDoubleAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class EncodingAssertionExtensions { public static ._IsASCII_Assertion IsASCII(this .<.Encoding> source) { } @@ -2622,6 +2757,39 @@ namespace .Extensions { public static . IsEqualTo(this . source, float expected, [.("expected")] string? expectedExpression = null) { } } + public class FloatIsInfinityWithFloatAssertion : . + { + public FloatIsInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNaNWithFloatAssertion : . + { + public FloatIsNaNWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsNegativeInfinityWithFloatAssertion : . + { + public FloatIsNegativeInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public class FloatIsPositiveInfinityWithFloatAssertion : . + { + public FloatIsPositiveInfinityWithFloatAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public static class GenericAssertions + { + public static .Extensions.T_IsIn__Assertion IsIn(this . source, params T[] collection) { } + public static .Extensions.T_IsIn_IEnumerableT_Assertion IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + public static .Extensions.T_IsIn_IEnumerableT_IEqualityComparerT_Assertion IsIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + public static .Extensions.T_IsNotIn__Assertion IsNotIn(this . source, params T[] collection) { } + public static .Extensions.T_IsNotIn_IEnumerableT_Assertion IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } + public static .Extensions.T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion IsNotIn(this . source, . collection, . equalityComparer, [.("collection")] string? collectionExpression = null, [.("equalityComparer")] string? equalityComparerExpression = null) { } + } public static class GreaterThanAssertionExtensions { public static . IsGreaterThan(this . source, TValue minimum, [.("minimum")] string? minimumExpression = null) @@ -2654,6 +2822,17 @@ namespace .Extensions public static . HasSingleItem(this . source) where TCollection : . { } } + public static class HttpResponseMessageAssertionExtensions + { + public static . IsNotSuccessStatusCode(this .<.> source) { } + public static . IsSuccessStatusCode(this .<.> source) { } + } + public class HttpResponseMessageIsSuccessStatusCodeAssertion : .<.> + { + public HttpResponseMessageIsSuccessStatusCodeAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class HttpStatusCodeAssertionExtensions { public static ._IsClientError_Assertion IsClientError(this .<.HttpStatusCode> source) { } @@ -2812,10 +2991,6 @@ namespace .Extensions public static . IsEquivalentTo(this . source, . expected, . comparer, . ordering = 0, [.("expected")] string? expectedExpression = null, [.("comparer")] string? comparerExpression = null, [.("ordering")] string? orderingExpression = null) where TCollection : . { } } - public static class IsInAssertionExtensions - { - public static . IsIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class IsNotAssignableToAssertionExtensions { public static . IsNotAssignableTo(this . source) { } @@ -2835,10 +3010,6 @@ namespace .Extensions public static . IsNotDefault(this . source) where TValue : class { } } - public static class IsNotInAssertionExtensions - { - public static . IsNotIn(this . source, . collection, [.("collection")] string? collectionExpression = null) { } - } public static class LazyAssertionExtensions { public static ._IsValueCreated_Assertion IsValueCreated(this .<> source) { } @@ -2887,6 +3058,11 @@ namespace .Extensions { public static . IsNull(this . source) { } } + public static class NullableAssertionExtensions + { + public static . DoesNotHaveValue(this . source) { } + public static . HasValue(this . source) { } + } public sealed class NullableBool_IsFalse_Assertion : . { public NullableBool_IsFalse_Assertion(. context) { } @@ -2904,6 +3080,12 @@ namespace .Extensions public static . IsEquatableTo(this . source, TExpected expected, [.("expected")] string? expectedExpression = null) where TActual : struct, { } } + public class NullableHasValueAssertion : . + { + public NullableHasValueAssertion(. context, bool negated = false) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class ProcessAssertionExtensions { public static . DoesNotHaveEventRaisingEnabled(this .<.Process> source) { } @@ -2936,10 +3118,34 @@ namespace .Extensions public static . HasProperty(this . source, .<> propertySelector) { } public static . HasProperty(this . source, .<> propertySelector, TProperty expectedValue, [.("expectedValue")] string? expression = null) { } } + public static class RegexAssertionExtensions + { + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> continuation, string groupName, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, int groupIndex, <., .?> assertion) { } + public static ..GroupAssertion Group(this .<..RegexMatchCollection> continuation, string groupName, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, int groupIndex, <., .?> assertion) { } + public static ..MatchGroupAssertion Group(this .<..RegexMatch> source, string groupName, <., .?> assertion) { } + public static ..MatchIndexAssertion Match(this .<..RegexMatchCollection> continuation, int index) { } + public static ..MatchAssertion Match(this .<..RegexMatchCollection> continuation, int index, <.<..RegexMatch>, .<..RegexMatch>?> assertion) { } + public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } + public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } + } public static class SameReferenceAssertionExtensions { public static . IsSameReferenceAs(this . source, object? expected, [.("expected")] string? expectedExpression = null) { } } + public static class SingleAssertionExtensions + { + public static . IsInfinity(this . source) { } + public static . IsNaN(this . source) { } + public static . IsNegativeInfinity(this . source) { } + public static . IsNotInfinity(this . source) { } + public static . IsNotNaN(this . source) { } + public static . IsNotNegativeInfinity(this . source) { } + public static . IsNotPositiveInfinity(this . source) { } + public static . IsPositiveInfinity(this . source) { } + } public static class StreamAssertionExtensions { public static . CanRead(this .<.Stream> source) { } @@ -3050,6 +3256,7 @@ namespace .Extensions public static class StringEqualsAssertionExtensions { public static . IsEqualTo(this . source, string? expected, [.("expected")] string? expectedExpression = null) { } + public static . IsEqualTo(this . source, string? expected, comparison, [.("expected")] string? expectedExpression = null, [.("comparison")] string? comparisonExpression = null) { } } public static class StringIsEmptyAssertionExtensions { @@ -3071,11 +3278,6 @@ namespace .Extensions protected override .<.> CheckAsync(. metadata) { } protected override string GetExpectation() { } } - public static class StringMatchesAssertionExtensions - { - public static . Matches(this . source, . regex, [.("regex")] string? regexExpression = null) { } - public static . Matches(this . source, string pattern, [.("pattern")] string? patternExpression = null) { } - } public static class StringStartsWithAssertionExtensions { public static . StartsWith(this . source, string expected, [.("expected")] string? expectedExpression = null) { } @@ -3088,6 +3290,42 @@ namespace .Extensions public static . IsNullOrEmpty(this . source) { } public static . IsNullOrWhiteSpace(this . source) { } } + public sealed class T_IsIn_IEnumerableT_Assertion : . + { + public T_IsIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public sealed class T_IsIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public sealed class T_IsIn__Assertion : . + { + public T_IsIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public sealed class T_IsNotIn_IEnumerableT_Assertion : . + { + public T_IsNotIn_IEnumerableT_Assertion(. context, . collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public sealed class T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion : . + { + public T_IsNotIn_IEnumerableT_IEqualityComparerT_Assertion(. context, . collection, . equalityComparer) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } + public sealed class T_IsNotIn__Assertion : . + { + public T_IsNotIn__Assertion(. context, T[] collection) { } + protected override .<.> CheckAsync(. metadata) { } + protected override string GetExpectation() { } + } public static class TaskAssertionExtensions { public static . IsCanceled(this . source) @@ -3449,6 +3687,41 @@ namespace .Extensions protected override .<.> CheckAsync(.<> metadata) { } protected override string GetExpectation() { } } + public static class ValueTaskAssertionExtensions + { + public static . IsCanceled(this .<.> source) { } + public static . IsCompleted(this .<.> source) { } + public static . IsCompletedSuccessfully(this .<.> source) { } + public static . IsFaulted(this .<.> source) { } + public static . IsNotCanceled(this .<.> source) { } + public static . IsNotCompleted(this .<.> source) { } + public static . IsNotCompletedSuccessfully(this .<.> source) { } + public static . IsNotFaulted(this .<.> source) { } + } + public class ValueTaskIsCanceledAssertion : .<.> + { + public ValueTaskIsCanceledAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedAssertion : .<.> + { + public ValueTaskIsCompletedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsCompletedSuccessfullyAssertion : .<.> + { + public ValueTaskIsCompletedSuccessfullyAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } + public class ValueTaskIsFaultedAssertion : .<.> + { + public ValueTaskIsFaultedAssertion(.<.> context, bool negated = false) { } + protected override .<.> CheckAsync(.<.> metadata) { } + protected override string GetExpectation() { } + } public static class VersionAssertionExtensions { public static ._HasBuildNumber_Assertion HasBuildNumber(this .<> source) { } diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt index de865ee675..c9501be01a 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet10_0.verified.txt @@ -169,7 +169,9 @@ namespace public class AsyncEvent { public AsyncEvent() { } - public int Order { get; set; } + public .<.AsyncEvent.Invocation> InvocationList { get; } + public void Add( callback, int order = 1073741823) { } + public void AddAt( callback, int index, int order = 1073741823) { } public .AsyncEvent InsertAtFront( callback) { } public static .AsyncEvent operator +(.AsyncEvent? e, callback) { } public class Invocation : . @@ -561,9 +563,6 @@ namespace public string GetDisplayName() { } public void SetDisplayName(string displayName) { } public void SetDisplayNameFormatter( formatterType) { } - [("Use AddParallelConstraint to support multiple constraints. This method replaces a" + - "ll existing constraints.")] - public void SetParallelConstraint(. constraint) { } public void SetPriority(. priority) { } public void SetRetryLimit(int retryLimit) { } public void SetRetryLimit(int retryCount, <.TestContext, , int, .> shouldRetry) { } @@ -610,13 +609,16 @@ namespace public .<> Attributes { get; set; } public string? CreatorFilePath { get; set; } public int? CreatorLineNumber { get; set; } + public string? DisplayName { get; set; } + public string? ParentTestId { get; set; } + public .? Properties { get; set; } + public .? Relationship { get; set; } public object?[]? TestClassArguments { get; set; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] public ? TestClassType { get; set; } public .? TestMethod { get; set; } public object?[]? TestMethodArguments { get; set; } } - [.("TUnitWIP0001")] public class DynamicTestBuilderAttribute : .BaseTestAttribute { public DynamicTestBuilderAttribute([.] string file = "", [.] int line = 0) { } @@ -1268,6 +1270,7 @@ namespace public .CancellationToken CancellationToken { get; set; } public .ClassHookContext ClassContext { get; } public int CurrentRetryAttempt { get; } + public .? CustomHookExecutor { get; set; } public .<.TestDetails> Dependencies { get; } public ? DisplayNameFormatter { get; set; } public .TestContextEvents Events { get; } @@ -1276,12 +1279,11 @@ namespace public .CancellationTokenSource? LinkedCancellationTokens { get; set; } public object Lock { get; } public . ObjectBag { get; } - [("Use ParallelConstraints collection instead. This property is maintained for backw" + - "ard compatibility.")] - public .? ParallelConstraint { get; set; } public .<.> ParallelConstraints { get; } public .? ParallelLimiter { get; } + public string? ParentTestId { get; set; } public .TestPhase Phase { get; set; } + public . Relationship { get; set; } public bool ReportResult { get; set; } public .TestResult? Result { get; set; } public <.TestContext, , int, .>? RetryFunc { get; set; } @@ -1309,9 +1311,6 @@ namespace public .<.TestContext> GetTests(string testName, classType) { } public void OverrideResult(string reason) { } public void OverrideResult(.TestState state, string reason) { } - [("This method is non-functional after the removal of ITestFinder. It will be remove" + - "d in a future version.")] - public . ReregisterTestWithArguments(object?[]? methodArguments = null, .? objectBag = null) { } public void SetParallelLimiter(. parallelLimit) { } public void WriteError(string message) { } public void WriteLine(string message) { } @@ -1375,7 +1374,7 @@ namespace public class TestDetails { public TestDetails() { } - public required .<> Attributes { get; init; } + public required .<, .<>> AttributesByType { get; init; } public . Categories { get; } public [] ClassGenericArguments { get; set; } public required object ClassInstance { get; set; } @@ -1397,6 +1396,11 @@ namespace public required object?[] TestMethodArguments { get; set; } public required string TestName { get; init; } public ? Timeout { get; set; } + public .<> GetAllAttributes() { } + public . GetAttributes() + where T : { } + public bool HasAttribute() + where T : { } } public class TestDetails : .TestDetails where T : class @@ -1437,6 +1441,7 @@ namespace public required .MethodMetadata MethodMetadata { get; init; } public required .PropertyDataSource[] PropertyDataSources { get; init; } public .PropertyInjectionData[] PropertyInjections { get; init; } + public int? RepeatCount { get; init; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] public required TestClassType { get; init; } public ? TestInvoker { get; init; } @@ -1471,6 +1476,7 @@ namespace public .TestContext TestContext { get; } public .TestDetails TestDetails { get; } public string TestName { get; } + public void SetHookExecutor(. executor) { } public void SetParallelLimiter(. parallelLimit) { } public void SetTestExecutor(. executor) { } } @@ -1700,6 +1706,13 @@ namespace .Enums High = 4, Critical = 5, } + public enum TestRelationship + { + None = 0, + Retry = 1, + Generated = 2, + Derived = 3, + } } namespace .Events { @@ -1885,6 +1898,8 @@ namespace .Extensions [.("Dynamic test metadata creation uses reflection")] public static . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(this .TestContext context, .DynamicTest dynamicTest) where T : class { } + [.("Creating test variants requires runtime compilation and reflection")] + public static . CreateTestVariant(this .TestContext context, object?[]? arguments = null, .? properties = null, . relationship = 3, string? displayName = null) { } public static string GetClassTypeName(this .TestContext context) { } public static T? GetService(this .TestContext context) where T : class { } @@ -1898,6 +1913,11 @@ namespace .Helpers public static string FormatArguments(. arguments) { } public static string GetConstantValue(.TestContext testContext, object? o) { } } + public static class AttributeDictionaryHelper + { + public static .<, .<>> Empty { get; } + public static .<, .<>> ToAttributeDictionary(this [] attributes) { } + } public static class CastHelper { [.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" + @@ -2309,6 +2329,9 @@ namespace .Interfaces "pported in native AOT scenarios.")] . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(.TestContext context, .DynamicTest dynamicTest) where T : class; + [.("Creating test variants requires runtime compilation and reflection which are not " + + "supported in native AOT scenarios.")] + . CreateTestVariant(.TestContext currentContext, object?[]? arguments, .? properties, . relationship, string? displayName); } public interface ITestRetryEventReceiver : . { diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt index f7b3d69196..e7a230ce6d 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet8_0.verified.txt @@ -169,7 +169,9 @@ namespace public class AsyncEvent { public AsyncEvent() { } - public int Order { get; set; } + public .<.AsyncEvent.Invocation> InvocationList { get; } + public void Add( callback, int order = 1073741823) { } + public void AddAt( callback, int index, int order = 1073741823) { } public .AsyncEvent InsertAtFront( callback) { } public static .AsyncEvent operator +(.AsyncEvent? e, callback) { } public class Invocation : . @@ -561,9 +563,6 @@ namespace public string GetDisplayName() { } public void SetDisplayName(string displayName) { } public void SetDisplayNameFormatter( formatterType) { } - [("Use AddParallelConstraint to support multiple constraints. This method replaces a" + - "ll existing constraints.")] - public void SetParallelConstraint(. constraint) { } public void SetPriority(. priority) { } public void SetRetryLimit(int retryLimit) { } public void SetRetryLimit(int retryCount, <.TestContext, , int, .> shouldRetry) { } @@ -610,13 +609,16 @@ namespace public .<> Attributes { get; set; } public string? CreatorFilePath { get; set; } public int? CreatorLineNumber { get; set; } + public string? DisplayName { get; set; } + public string? ParentTestId { get; set; } + public .? Properties { get; set; } + public .? Relationship { get; set; } public object?[]? TestClassArguments { get; set; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] public ? TestClassType { get; set; } public .? TestMethod { get; set; } public object?[]? TestMethodArguments { get; set; } } - [.("TUnitWIP0001")] public class DynamicTestBuilderAttribute : .BaseTestAttribute { public DynamicTestBuilderAttribute([.] string file = "", [.] int line = 0) { } @@ -1268,6 +1270,7 @@ namespace public .CancellationToken CancellationToken { get; set; } public .ClassHookContext ClassContext { get; } public int CurrentRetryAttempt { get; } + public .? CustomHookExecutor { get; set; } public .<.TestDetails> Dependencies { get; } public ? DisplayNameFormatter { get; set; } public .TestContextEvents Events { get; } @@ -1276,12 +1279,11 @@ namespace public .CancellationTokenSource? LinkedCancellationTokens { get; set; } public object Lock { get; } public . ObjectBag { get; } - [("Use ParallelConstraints collection instead. This property is maintained for backw" + - "ard compatibility.")] - public .? ParallelConstraint { get; set; } public .<.> ParallelConstraints { get; } public .? ParallelLimiter { get; } + public string? ParentTestId { get; set; } public .TestPhase Phase { get; set; } + public . Relationship { get; set; } public bool ReportResult { get; set; } public .TestResult? Result { get; set; } public <.TestContext, , int, .>? RetryFunc { get; set; } @@ -1309,9 +1311,6 @@ namespace public .<.TestContext> GetTests(string testName, classType) { } public void OverrideResult(string reason) { } public void OverrideResult(.TestState state, string reason) { } - [("This method is non-functional after the removal of ITestFinder. It will be remove" + - "d in a future version.")] - public . ReregisterTestWithArguments(object?[]? methodArguments = null, .? objectBag = null) { } public void SetParallelLimiter(. parallelLimit) { } public void WriteError(string message) { } public void WriteLine(string message) { } @@ -1375,7 +1374,7 @@ namespace public class TestDetails { public TestDetails() { } - public required .<> Attributes { get; init; } + public required .<, .<>> AttributesByType { get; init; } public . Categories { get; } public [] ClassGenericArguments { get; set; } public required object ClassInstance { get; set; } @@ -1397,6 +1396,11 @@ namespace public required object?[] TestMethodArguments { get; set; } public required string TestName { get; init; } public ? Timeout { get; set; } + public .<> GetAllAttributes() { } + public . GetAttributes() + where T : { } + public bool HasAttribute() + where T : { } } public class TestDetails : .TestDetails where T : class @@ -1437,6 +1441,7 @@ namespace public required .MethodMetadata MethodMetadata { get; init; } public required .PropertyDataSource[] PropertyDataSources { get; init; } public .PropertyInjectionData[] PropertyInjections { get; init; } + public int? RepeatCount { get; init; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] public required TestClassType { get; init; } public ? TestInvoker { get; init; } @@ -1471,6 +1476,7 @@ namespace public .TestContext TestContext { get; } public .TestDetails TestDetails { get; } public string TestName { get; } + public void SetHookExecutor(. executor) { } public void SetParallelLimiter(. parallelLimit) { } public void SetTestExecutor(. executor) { } } @@ -1700,6 +1706,13 @@ namespace .Enums High = 4, Critical = 5, } + public enum TestRelationship + { + None = 0, + Retry = 1, + Generated = 2, + Derived = 3, + } } namespace .Events { @@ -1885,6 +1898,8 @@ namespace .Extensions [.("Dynamic test metadata creation uses reflection")] public static . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(this .TestContext context, .DynamicTest dynamicTest) where T : class { } + [.("Creating test variants requires runtime compilation and reflection")] + public static . CreateTestVariant(this .TestContext context, object?[]? arguments = null, .? properties = null, . relationship = 3, string? displayName = null) { } public static string GetClassTypeName(this .TestContext context) { } public static T? GetService(this .TestContext context) where T : class { } @@ -1898,6 +1913,11 @@ namespace .Helpers public static string FormatArguments(. arguments) { } public static string GetConstantValue(.TestContext testContext, object? o) { } } + public static class AttributeDictionaryHelper + { + public static .<, .<>> Empty { get; } + public static .<, .<>> ToAttributeDictionary(this [] attributes) { } + } public static class CastHelper { [.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" + @@ -2309,6 +2329,9 @@ namespace .Interfaces "pported in native AOT scenarios.")] . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(.TestContext context, .DynamicTest dynamicTest) where T : class; + [.("Creating test variants requires runtime compilation and reflection which are not " + + "supported in native AOT scenarios.")] + . CreateTestVariant(.TestContext currentContext, object?[]? arguments, .? properties, . relationship, string? displayName); } public interface ITestRetryEventReceiver : . { diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt index c7e96f00ab..3db44143c6 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.DotNet9_0.verified.txt @@ -169,7 +169,9 @@ namespace public class AsyncEvent { public AsyncEvent() { } - public int Order { get; set; } + public .<.AsyncEvent.Invocation> InvocationList { get; } + public void Add( callback, int order = 1073741823) { } + public void AddAt( callback, int index, int order = 1073741823) { } public .AsyncEvent InsertAtFront( callback) { } public static .AsyncEvent operator +(.AsyncEvent? e, callback) { } public class Invocation : . @@ -561,9 +563,6 @@ namespace public string GetDisplayName() { } public void SetDisplayName(string displayName) { } public void SetDisplayNameFormatter( formatterType) { } - [("Use AddParallelConstraint to support multiple constraints. This method replaces a" + - "ll existing constraints.")] - public void SetParallelConstraint(. constraint) { } public void SetPriority(. priority) { } public void SetRetryLimit(int retryLimit) { } public void SetRetryLimit(int retryCount, <.TestContext, , int, .> shouldRetry) { } @@ -610,13 +609,16 @@ namespace public .<> Attributes { get; set; } public string? CreatorFilePath { get; set; } public int? CreatorLineNumber { get; set; } + public string? DisplayName { get; set; } + public string? ParentTestId { get; set; } + public .? Properties { get; set; } + public .? Relationship { get; set; } public object?[]? TestClassArguments { get; set; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] public ? TestClassType { get; set; } public .? TestMethod { get; set; } public object?[]? TestMethodArguments { get; set; } } - [.("TUnitWIP0001")] public class DynamicTestBuilderAttribute : .BaseTestAttribute { public DynamicTestBuilderAttribute([.] string file = "", [.] int line = 0) { } @@ -1268,6 +1270,7 @@ namespace public .CancellationToken CancellationToken { get; set; } public .ClassHookContext ClassContext { get; } public int CurrentRetryAttempt { get; } + public .? CustomHookExecutor { get; set; } public .<.TestDetails> Dependencies { get; } public ? DisplayNameFormatter { get; set; } public .TestContextEvents Events { get; } @@ -1276,12 +1279,11 @@ namespace public .CancellationTokenSource? LinkedCancellationTokens { get; set; } public object Lock { get; } public . ObjectBag { get; } - [("Use ParallelConstraints collection instead. This property is maintained for backw" + - "ard compatibility.")] - public .? ParallelConstraint { get; set; } public .<.> ParallelConstraints { get; } public .? ParallelLimiter { get; } + public string? ParentTestId { get; set; } public .TestPhase Phase { get; set; } + public . Relationship { get; set; } public bool ReportResult { get; set; } public .TestResult? Result { get; set; } public <.TestContext, , int, .>? RetryFunc { get; set; } @@ -1309,9 +1311,6 @@ namespace public .<.TestContext> GetTests(string testName, classType) { } public void OverrideResult(string reason) { } public void OverrideResult(.TestState state, string reason) { } - [("This method is non-functional after the removal of ITestFinder. It will be remove" + - "d in a future version.")] - public . ReregisterTestWithArguments(object?[]? methodArguments = null, .? objectBag = null) { } public void SetParallelLimiter(. parallelLimit) { } public void WriteError(string message) { } public void WriteLine(string message) { } @@ -1375,7 +1374,7 @@ namespace public class TestDetails { public TestDetails() { } - public required .<> Attributes { get; init; } + public required .<, .<>> AttributesByType { get; init; } public . Categories { get; } public [] ClassGenericArguments { get; set; } public required object ClassInstance { get; set; } @@ -1397,6 +1396,11 @@ namespace public required object?[] TestMethodArguments { get; set; } public required string TestName { get; init; } public ? Timeout { get; set; } + public .<> GetAllAttributes() { } + public . GetAttributes() + where T : { } + public bool HasAttribute() + where T : { } } public class TestDetails : .TestDetails where T : class @@ -1437,6 +1441,7 @@ namespace public required .MethodMetadata MethodMetadata { get; init; } public required .PropertyDataSource[] PropertyDataSources { get; init; } public .PropertyInjectionData[] PropertyInjections { get; init; } + public int? RepeatCount { get; init; } [.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..PublicMethods | ..PublicProperties)] public required TestClassType { get; init; } public ? TestInvoker { get; init; } @@ -1471,6 +1476,7 @@ namespace public .TestContext TestContext { get; } public .TestDetails TestDetails { get; } public string TestName { get; } + public void SetHookExecutor(. executor) { } public void SetParallelLimiter(. parallelLimit) { } public void SetTestExecutor(. executor) { } } @@ -1700,6 +1706,13 @@ namespace .Enums High = 4, Critical = 5, } + public enum TestRelationship + { + None = 0, + Retry = 1, + Generated = 2, + Derived = 3, + } } namespace .Events { @@ -1885,6 +1898,8 @@ namespace .Extensions [.("Dynamic test metadata creation uses reflection")] public static . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(this .TestContext context, .DynamicTest dynamicTest) where T : class { } + [.("Creating test variants requires runtime compilation and reflection")] + public static . CreateTestVariant(this .TestContext context, object?[]? arguments = null, .? properties = null, . relationship = 3, string? displayName = null) { } public static string GetClassTypeName(this .TestContext context) { } public static T? GetService(this .TestContext context) where T : class { } @@ -1898,6 +1913,11 @@ namespace .Helpers public static string FormatArguments(. arguments) { } public static string GetConstantValue(.TestContext testContext, object? o) { } } + public static class AttributeDictionaryHelper + { + public static .<, .<>> Empty { get; } + public static .<, .<>> ToAttributeDictionary(this [] attributes) { } + } public static class CastHelper { [.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" + @@ -2309,6 +2329,9 @@ namespace .Interfaces "pported in native AOT scenarios.")] . AddDynamicTest<[.(..None | ..PublicParameterlessConstructor | ..PublicConstructors | ..NonPublicConstructors | ..PublicMethods | ..NonPublicMethods | ..PublicFields | ..NonPublicFields | ..PublicProperties)] T>(.TestContext context, .DynamicTest dynamicTest) where T : class; + [.("Creating test variants requires runtime compilation and reflection which are not " + + "supported in native AOT scenarios.")] + . CreateTestVariant(.TestContext currentContext, object?[]? arguments, .? properties, . relationship, string? displayName); } public interface ITestRetryEventReceiver : . { diff --git a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt index 2f9c6ad709..8b79270768 100644 --- a/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt +++ b/TUnit.PublicAPI/Tests.Core_Library_Has_No_API_Changes.Net4_7.verified.txt @@ -166,7 +166,9 @@ namespace public class AsyncEvent { public AsyncEvent() { } - public int Order { get; set; } + public .<.AsyncEvent.Invocation> InvocationList { get; } + public void Add( callback, int order = 1073741823) { } + public void AddAt( callback, int index, int order = 1073741823) { } public .AsyncEvent InsertAtFront( callback) { } public static .AsyncEvent operator +(.AsyncEvent? e, callback) { } public class Invocation : . @@ -541,9 +543,6 @@ namespace public string GetDisplayName() { } public void SetDisplayName(string displayName) { } public void SetDisplayNameFormatter( formatterType) { } - [("Use AddParallelConstraint to support multiple constraints. This method replaces a" + - "ll existing constraints.")] - public void SetParallelConstraint(. constraint) { } public void SetPriority(. priority) { } public void SetRetryLimit(int retryLimit) { } public void SetRetryLimit(int retryCount, <.TestContext, , int, .> shouldRetry) { } @@ -590,6 +589,10 @@ namespace public .<> Attributes { get; set; } public string? CreatorFilePath { get; set; } public int? CreatorLineNumber { get; set; } + public string? DisplayName { get; set; } + public string? ParentTestId { get; set; } + public .? Properties { get; set; } + public .? Relationship { get; set; } public object?[]? TestClassArguments { get; set; } public ? TestClassType { get; set; } public .? TestMethod { get; set; } @@ -1222,6 +1225,7 @@ namespace public .CancellationToken CancellationToken { get; set; } public .ClassHookContext ClassContext { get; } public int CurrentRetryAttempt { get; } + public .? CustomHookExecutor { get; set; } public .<.TestDetails> Dependencies { get; } public ? DisplayNameFormatter { get; set; } public .TestContextEvents Events { get; } @@ -1230,12 +1234,11 @@ namespace public .CancellationTokenSource? LinkedCancellationTokens { get; set; } public object Lock { get; } public . ObjectBag { get; } - [("Use ParallelConstraints collection instead. This property is maintained for backw" + - "ard compatibility.")] - public .? ParallelConstraint { get; set; } public .<.> ParallelConstraints { get; } public .? ParallelLimiter { get; } + public string? ParentTestId { get; set; } public .TestPhase Phase { get; set; } + public . Relationship { get; set; } public bool ReportResult { get; set; } public .TestResult? Result { get; set; } public <.TestContext, , int, .>? RetryFunc { get; set; } @@ -1263,9 +1266,6 @@ namespace public .<.TestContext> GetTests(string testName, classType) { } public void OverrideResult(string reason) { } public void OverrideResult(.TestState state, string reason) { } - [("This method is non-functional after the removal of ITestFinder. It will be remove" + - "d in a future version.")] - public . ReregisterTestWithArguments(object?[]? methodArguments = null, .? objectBag = null) { } public void SetParallelLimiter(. parallelLimit) { } public void WriteError(string message) { } public void WriteLine(string message) { } @@ -1329,7 +1329,7 @@ namespace public class TestDetails { public TestDetails() { } - public required .<> Attributes { get; init; } + public required .<, .<>> AttributesByType { get; init; } public . Categories { get; } public [] ClassGenericArguments { get; set; } public required object ClassInstance { get; set; } @@ -1350,6 +1350,11 @@ namespace public required object?[] TestMethodArguments { get; set; } public required string TestName { get; init; } public ? Timeout { get; set; } + public .<> GetAllAttributes() { } + public . GetAttributes() + where T : { } + public bool HasAttribute() + where T : { } } public class TestDetails : .TestDetails where T : class @@ -1390,6 +1395,7 @@ namespace public required .MethodMetadata MethodMetadata { get; init; } public required .PropertyDataSource[] PropertyDataSources { get; init; } public .PropertyInjectionData[] PropertyInjections { get; init; } + public int? RepeatCount { get; init; } public required TestClassType { get; init; } public ? TestInvoker { get; init; } public required string TestMethodName { get; init; } @@ -1423,6 +1429,7 @@ namespace public .TestContext TestContext { get; } public .TestDetails TestDetails { get; } public string TestName { get; } + public void SetHookExecutor(. executor) { } public void SetParallelLimiter(. parallelLimit) { } public void SetTestExecutor(. executor) { } } @@ -1652,6 +1659,13 @@ namespace .Enums High = 4, Critical = 5, } + public enum TestRelationship + { + None = 0, + Retry = 1, + Generated = 2, + Derived = 3, + } } namespace .Events { @@ -1835,6 +1849,7 @@ namespace .Extensions { public static . AddDynamicTest(this .TestContext context, .DynamicTest dynamicTest) where T : class { } + public static . CreateTestVariant(this .TestContext context, object?[]? arguments = null, .? properties = null, . relationship = 3, string? displayName = null) { } public static string GetClassTypeName(this .TestContext context) { } public static T? GetService(this .TestContext context) where T : class { } @@ -1848,6 +1863,11 @@ namespace .Helpers public static string FormatArguments(. arguments) { } public static string GetConstantValue(.TestContext testContext, object? o) { } } + public static class AttributeDictionaryHelper + { + public static .<, .<>> Empty { get; } + public static .<, .<>> ToAttributeDictionary(this [] attributes) { } + } public static class CastHelper { public static object? Cast( type, object? value) { } @@ -2239,6 +2259,7 @@ namespace .Interfaces { . AddDynamicTest(.TestContext context, .DynamicTest dynamicTest) where T : class; + . CreateTestVariant(.TestContext currentContext, object?[]? arguments, .? properties, . relationship, string? displayName); } public interface ITestRetryEventReceiver : . { diff --git a/TUnit.Templates/content/TUnit.AspNet.FSharp/TestProject/TestProject.fsproj b/TUnit.Templates/content/TUnit.AspNet.FSharp/TestProject/TestProject.fsproj index 1e789f6706..45eaeb7b35 100644 --- a/TUnit.Templates/content/TUnit.AspNet.FSharp/TestProject/TestProject.fsproj +++ b/TUnit.Templates/content/TUnit.AspNet.FSharp/TestProject/TestProject.fsproj @@ -10,8 +10,8 @@ - - + + diff --git a/TUnit.Templates/content/TUnit.AspNet/TestProject/TestProject.csproj b/TUnit.Templates/content/TUnit.AspNet/TestProject/TestProject.csproj index 82beefd563..90975993f9 100644 --- a/TUnit.Templates/content/TUnit.AspNet/TestProject/TestProject.csproj +++ b/TUnit.Templates/content/TUnit.AspNet/TestProject/TestProject.csproj @@ -9,7 +9,7 @@ - + diff --git a/TUnit.Templates/content/TUnit.Aspire.Starter/ExampleNamespace.TestProject/ExampleNamespace.TestProject.csproj b/TUnit.Templates/content/TUnit.Aspire.Starter/ExampleNamespace.TestProject/ExampleNamespace.TestProject.csproj index 2a5e943d43..090fb5b8f7 100644 --- a/TUnit.Templates/content/TUnit.Aspire.Starter/ExampleNamespace.TestProject/ExampleNamespace.TestProject.csproj +++ b/TUnit.Templates/content/TUnit.Aspire.Starter/ExampleNamespace.TestProject/ExampleNamespace.TestProject.csproj @@ -11,7 +11,7 @@ - + diff --git a/TUnit.Templates/content/TUnit.Aspire.Test/ExampleNamespace.csproj b/TUnit.Templates/content/TUnit.Aspire.Test/ExampleNamespace.csproj index c5bc9ec8ea..0c9529b2ea 100644 --- a/TUnit.Templates/content/TUnit.Aspire.Test/ExampleNamespace.csproj +++ b/TUnit.Templates/content/TUnit.Aspire.Test/ExampleNamespace.csproj @@ -10,7 +10,7 @@ - + diff --git a/TUnit.Templates/content/TUnit.FSharp/TestProject.fsproj b/TUnit.Templates/content/TUnit.FSharp/TestProject.fsproj index b3ae846a8b..fc08b0d0cd 100644 --- a/TUnit.Templates/content/TUnit.FSharp/TestProject.fsproj +++ b/TUnit.Templates/content/TUnit.FSharp/TestProject.fsproj @@ -10,8 +10,8 @@ - - + + diff --git a/TUnit.Templates/content/TUnit.Playwright/TestProject.csproj b/TUnit.Templates/content/TUnit.Playwright/TestProject.csproj index 0f43a16a0c..ea23aa2ee7 100644 --- a/TUnit.Templates/content/TUnit.Playwright/TestProject.csproj +++ b/TUnit.Templates/content/TUnit.Playwright/TestProject.csproj @@ -8,7 +8,7 @@ - + diff --git a/TUnit.Templates/content/TUnit.VB/TestProject.vbproj b/TUnit.Templates/content/TUnit.VB/TestProject.vbproj index c9045808f4..601545ab97 100644 --- a/TUnit.Templates/content/TUnit.VB/TestProject.vbproj +++ b/TUnit.Templates/content/TUnit.VB/TestProject.vbproj @@ -8,6 +8,6 @@ - + diff --git a/TUnit.Templates/content/TUnit/TestProject.csproj b/TUnit.Templates/content/TUnit/TestProject.csproj index 30677d21dc..c33ef9f8fe 100644 --- a/TUnit.Templates/content/TUnit/TestProject.csproj +++ b/TUnit.Templates/content/TUnit/TestProject.csproj @@ -8,7 +8,7 @@ - + \ No newline at end of file diff --git a/TUnit.TestProject/AfterTests/TestDiscoveryAfterTests.cs b/TUnit.TestProject/AfterTests/TestDiscoveryAfterTests.cs index b1f80522e1..5d02d5dac8 100644 --- a/TUnit.TestProject/AfterTests/TestDiscoveryAfterTests.cs +++ b/TUnit.TestProject/AfterTests/TestDiscoveryAfterTests.cs @@ -13,10 +13,13 @@ public static async Task AfterEveryTestDiscovery(TestDiscoveryContext context) { await FilePolyfill.WriteAllTextAsync($"TestDiscoveryAfterTests{Guid.NewGuid():N}.txt", $"{context.AllTests.Count()} tests found"); - var test = context.AllTests.First(x => + var test = context.AllTests.FirstOrDefault(x => x.TestDetails.TestName == nameof(TestDiscoveryAfterTests.EnsureAfterEveryTestDiscoveryHit)); - test.ObjectBag.Add("AfterEveryTestDiscoveryHit", true); + if (test is not null) + { + test.ObjectBag.Add("AfterEveryTestDiscoveryHit", true); + } } } diff --git a/TUnit.TestProject/ArgumentDisplayFormatterTests.cs b/TUnit.TestProject/ArgumentDisplayFormatterTests.cs new file mode 100644 index 0000000000..e0e581e6bb --- /dev/null +++ b/TUnit.TestProject/ArgumentDisplayFormatterTests.cs @@ -0,0 +1,70 @@ +using TUnit.TestProject.Attributes; + +namespace TUnit.TestProject; + +[EngineTest(ExpectedResult.Pass)] +public class ArgumentDisplayFormatterTests +{ + [Test] + [MethodDataSource(nameof(Data1))] + [ArgumentDisplayFormatter] + public async Task FormatterShouldBeAppliedToMethodDataSource(Foo foo) + { + // Verify the formatter was applied by checking the display name + var displayName = TestContext.Current!.GetDisplayName(); + await Assert.That(displayName).IsEqualTo("FormatterShouldBeAppliedToMethodDataSource(FooFormatterValue)"); + } + + [Test] + [Arguments(1, 2, 3)] + [ArgumentDisplayFormatter] + public async Task FormatterShouldBeAppliedToArguments(int a, int b, int c) + { + // Verify the formatter was applied by checking the display name + var displayName = TestContext.Current!.GetDisplayName(); + await Assert.That(displayName).IsEqualTo("FormatterShouldBeAppliedToArguments(INT:1, INT:2, INT:3)"); + } + + [Test] + [MethodDataSource(nameof(DataWithBar))] + [ArgumentDisplayFormatter] + public async Task FormatterShouldBeAppliedToBarData(Bar bar) + { + // Verify the Bar formatter was applied by checking the display name + var displayName = TestContext.Current!.GetDisplayName(); + await Assert.That(displayName).IsEqualTo("FormatterShouldBeAppliedToBarData(BarFormatterValue)"); + } + + public static IEnumerable Data1() => [new Foo()]; + + public static IEnumerable DataWithBar() => [new Bar()]; +} + +public class Foo +{ +} + +public class Bar +{ +} + +public class FooFormatter : ArgumentDisplayFormatter +{ + public override bool CanHandle(object? value) => value is Foo; + + public override string FormatValue(object? value) => "FooFormatterValue"; +} + +public class BarFormatter : ArgumentDisplayFormatter +{ + public override bool CanHandle(object? value) => value is Bar; + + public override string FormatValue(object? value) => "BarFormatterValue"; +} + +public class IntFormatter : ArgumentDisplayFormatter +{ + public override bool CanHandle(object? value) => value is int; + + public override string FormatValue(object? value) => $"INT:{value}"; +} diff --git a/TUnit.TestProject/Attributes/SkipMacOSAttribute.cs b/TUnit.TestProject/Attributes/SkipMacOSAttribute.cs deleted file mode 100644 index 9d245e083a..0000000000 --- a/TUnit.TestProject/Attributes/SkipMacOSAttribute.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Runtime.InteropServices; - -namespace TUnit.TestProject.Attributes; - -[Obsolete("Use `[ExcludeOnAttribute(OS.MacOS)]` instead.")] -public class SkipMacOSAttribute(string reason) : SkipAttribute(reason) -{ - public override Task ShouldSkip(TestRegisteredContext context) - { - return Task.FromResult(RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); - } -} diff --git a/TUnit.TestProject/Bugs/1939/Tests.cs b/TUnit.TestProject/Bugs/1939/Tests.cs index e2a8c1e92f..1f81bb799d 100644 --- a/TUnit.TestProject/Bugs/1939/Tests.cs +++ b/TUnit.TestProject/Bugs/1939/Tests.cs @@ -55,7 +55,7 @@ public static async Task AssertAllDataClassesDisposed(TestSessionContext context if (!dataClass.Disposed) { var classDataSourceAttribute = - test.TestDetails.Attributes.OfType>() + test.TestDetails.GetAttributes>() .First(); throw new Exception($"Not Disposed: {classDataSourceAttribute.Shared}"); diff --git a/TUnit.TestProject/Bugs/3190/NegativeCategoryFilterTests.cs b/TUnit.TestProject/Bugs/3190/NegativeCategoryFilterTests.cs new file mode 100644 index 0000000000..80327f6b8a --- /dev/null +++ b/TUnit.TestProject/Bugs/3190/NegativeCategoryFilterTests.cs @@ -0,0 +1,112 @@ +using System; +using System.Threading.Tasks; + +namespace TUnit.TestProject.Bugs._3190; + +// This file replicates the issue from GitHub issue #3190: +// When ANY test has [Explicit], negative category filters stop working correctly. +// Expected: /*/*/*/*[Category!=Performance] should exclude all Performance tests +// Actual bug: It runs all non-explicit tests INCLUDING those with Performance category +// +// ROOT CAUSE ANALYSIS: +// The filter evaluation logic is incorrectly handling [Explicit] tests. The presence of +// explicit tests is somehow interfering with negative category filter evaluation. +// +// CORRECT DESIGN PRINCIPLE (Two-Stage Filtering): +// +// Stage 1: Pre-Filter for [Explicit] +// Create initial candidate list: +// - START WITH: All non-explicit tests +// - ADD explicit tests ONLY IF: They are positively and specifically selected +// ✓ Specific name match: /*/MyExplicitTest +// ✓ Positive property: /*/*/*/*[Category=Nightly] +// ✗ Wildcard: /*/*/*/* (too broad - not a specific selection) +// ✗ Negative filter: /*/*/*/*[Category!=Performance] (not a positive selection) +// +// Stage 2: Main Filter +// Apply the full filter logic (including negations) to the candidate list from Stage 1. +// +// WHY THIS IS CORRECT: +// - [Explicit] means "opt-in only" - never run unless specifically requested +// - Test behavior should be local to the test itself, not dependent on sibling tests +// - Aligns with industry standards (NUnit, etc.) +// - Prevents "last non-explicit test" disaster scenario where deleting one test +// changes the behavior of 99 unrelated explicit tests +// +// EXPECTED BEHAVIOR FOR THIS TEST: +// Filter: /*/*/*/*[Category!=Performance] +// +// Stage 1 Result (candidate list): +// - TestClass1.TestMethod1 ✓ (not explicit) +// - TestClass1.TestMethod2 ✓ (not explicit) +// - TestClass2.TestMethod1 ✓ (not explicit) +// - TestClass2.TestMethod2 ✗ (explicit - wildcard doesn't positively select it) +// - TestClass3.RegularTestWithoutCategory ✓ (not explicit) +// +// Stage 2 Result (after applying [Category!=Performance]): +// - TestClass1.TestMethod1 ✗ (has Performance category) +// - TestClass1.TestMethod2 ✓ (no Performance category) ← SHOULD RUN +// - TestClass2.TestMethod1 ✗ (has Performance category) +// - TestClass3.RegularTestWithoutCategory ✓ (no Performance category) ← SHOULD RUN +// +// FINAL: 2 tests should run + +public class TestClass1 +{ + [Test] + [Category("Performance")] + public Task TestMethod1() + { + // This test has Performance category + // With filter [Category!=Performance], this should be EXCLUDED + Console.WriteLine("TestClass1.TestMethod1 executed (has Performance category)"); + return Task.CompletedTask; + } + + [Test] + [Property("CI", "false")] + public Task TestMethod2() + { + // This test has CI property but NOT Performance category + // With filter [Category!=Performance], this should be INCLUDED + Console.WriteLine("TestClass1.TestMethod2 executed (no Performance category)"); + return Task.CompletedTask; + } +} + +public class TestClass2 +{ + [Test] + [Category("Performance")] + [Property("CI", "true")] + public Task TestMethod1() + { + // This test has BOTH Performance category and CI property + // With filter [Category!=Performance], this should be EXCLUDED + Console.WriteLine("TestClass2.TestMethod1 executed (has Performance category)"); + return Task.CompletedTask; + } + + [Test] + [Explicit] + public Task TestMethod2() + { + // This test is marked Explicit - the trigger for the bug + // With any wildcard filter, this should NOT run unless explicitly requested + // But its presence causes negative category filters to malfunction + Console.WriteLine("TestClass2.TestMethod2 executed (Explicit test - should not run with wildcard filter!)"); + throw new NotImplementedException("Explicit test should not run with wildcard filter!"); + } +} + +public class TestClass3 +{ + [Test] + public Task RegularTestWithoutCategory() + { + // This test has no Performance category and is not Explicit + // With filter [Category!=Performance], this should be INCLUDED + Console.WriteLine("TestClass3.RegularTestWithoutCategory executed (no Performance category)"); + return Task.CompletedTask; + } +} diff --git a/TUnit.TestProject/Bugs/Issue2504CollectionExpressionTest.cs b/TUnit.TestProject/Bugs/Issue2504CollectionExpressionTest.cs index 6623279309..ca912f64b1 100644 --- a/TUnit.TestProject/Bugs/Issue2504CollectionExpressionTest.cs +++ b/TUnit.TestProject/Bugs/Issue2504CollectionExpressionTest.cs @@ -17,7 +17,7 @@ public class Issue2504CollectionExpressionTest public async Task TestWithSingleArgument(int value) { ExecutedTests.Add($"SingleParam:{value}"); - await Assert.That(value).IsIn(10, 20); // 5*2=10, 10*2=20 + await Assert.That(value).IsIn([10, 20]); // 5*2=10, 10*2=20 } [Test] @@ -34,7 +34,7 @@ public async Task TestWithMultipleArguments(int number, string text) public async Task TestWithArrayArgument(int value) { ExecutedTests.Add($"ArrayParam:{value}"); - await Assert.That(value).IsIn(4, 5); + await Assert.That(value).IsIn([4, 5]); } public static IEnumerable GetDataWithSingleIntParam(int multiplier) diff --git a/TUnit.TestProject/Bugs/Issue2504CompilationTest.cs b/TUnit.TestProject/Bugs/Issue2504CompilationTest.cs index 462229a6d6..7232cd9f50 100644 --- a/TUnit.TestProject/Bugs/Issue2504CompilationTest.cs +++ b/TUnit.TestProject/Bugs/Issue2504CompilationTest.cs @@ -15,7 +15,7 @@ public class Issue2504CompilationTest public async Task TestWithCollectionExpressionSyntax(int value) { // Test should receive 10 (5 * 2) and 20 (10 * 2) - await Assert.That(value).IsIn(10, 20); + await Assert.That(value).IsIn([10, 20]); } [Test] diff --git a/TUnit.TestProject/DynamicTests/Basic.cs b/TUnit.TestProject/DynamicTests/Basic.cs index a47f048d72..8f9c7ce0ec 100644 --- a/TUnit.TestProject/DynamicTests/Basic.cs +++ b/TUnit.TestProject/DynamicTests/Basic.cs @@ -48,49 +48,49 @@ public void BuildTests(DynamicTestBuilderContext context) { TestMethod = @class => @class.SomeMethod(), TestMethodArguments = [], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_Task(), TestMethodArguments = [], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_ValueTask(), TestMethodArguments = [], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_Args(1, "test", true), TestMethodArguments = [2, "test", false], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_Task_Args(1, "test", true), TestMethodArguments = [2, "test", false], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_ValueTask_Args(1, "test", true), TestMethodArguments = [2, "test", false], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); context.AddTest(new DynamicTest { TestMethod = @class => @class.SomeMethod_ValueTask_Args(1, "test", true), TestMethodArguments = [2, "test", false], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); } } diff --git a/TUnit.TestProject/DynamicTests/Runtime.cs b/TUnit.TestProject/DynamicTests/Runtime.cs index b525a5f58a..79b5b5c830 100644 --- a/TUnit.TestProject/DynamicTests/Runtime.cs +++ b/TUnit.TestProject/DynamicTests/Runtime.cs @@ -29,7 +29,7 @@ await context.AddDynamicTest(new DynamicTest TestMethod = @class => @class.SomeMethod(0, 0, 0), TestClassArguments = [a + 10, b + 10, c + 10], TestMethodArguments = [d + 10, e + 10, f + 10], - Attributes = [new RepeatAttribute(5)] + Attributes = [] }); } } diff --git a/TUnit.TestProject/DynamicallyAddedTestsAtRuntimeTests.cs b/TUnit.TestProject/DynamicallyAddedTestsAtRuntimeTests.cs deleted file mode 100644 index ade4c9df14..0000000000 --- a/TUnit.TestProject/DynamicallyAddedTestsAtRuntimeTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -#pragma warning disable -namespace TUnit.TestProject; - -public class DynamicallyAddedTestsAtRuntimeTests -{ - private static int _testRepeatLimit = 0; - - [Test] - [Arguments(1)] - public void Failure(int i) - { - throw new Exception($"Random reason: {i}"); - } - - [After(Test)] - public void CreateRepeatTestIfFailure(TestContext context) - { - // Implementation pending - intended to demonstrate dynamic test repetition on failure - // See DynamicallyRegisteredTests.cs for a working example using ReregisterTestWithArguments - // Note: ReregisterTestWithArguments is currently marked as Obsolete and non-functional - - // Example implementation (currently non-functional): - // if (context.Result?.State == TestState.Failed && _testRepeatLimit < 3) - // { - // _testRepeatLimit++; - // await context.ReregisterTestWithArguments(methodArguments: [_testRepeatLimit]); - // } - } -} diff --git a/TUnit.TestProject/DynamicallyRegisteredTests.cs b/TUnit.TestProject/DynamicallyRegisteredTests.cs deleted file mode 100644 index 78dca77ec8..0000000000 --- a/TUnit.TestProject/DynamicallyRegisteredTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using TUnit.Core.Interfaces; - -namespace TUnit.TestProject; - -[DynamicCodeOnly] -public class DynamicallyRegisteredTests -{ - [Test] - [DynamicDataGenerator] - public void MyTest(int value) - { - throw new Exception($@"Value {value} !"); - } -} - -public class DynamicDataGenerator : DataSourceGeneratorAttribute, ITestStartEventReceiver, ITestEndEventReceiver -{ - private static int _count; - - private readonly CancellationTokenSource _cancellationTokenSource = new(); - - protected override IEnumerable> GenerateDataSources(DataGeneratorMetadata dataGeneratorMetadata) - { - yield return () => new Random().Next(); - } - - public ValueTask OnTestStart(TestContext testContext) - { - if (!IsReregisteredTest(testContext)) - { - testContext.AddLinkedCancellationToken(_cancellationTokenSource.Token); - } - - return default(ValueTask); - } - - [Experimental("WIP")] - [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "Dynamic Code Only attribute on test")] - public async ValueTask OnTestEnd(TestContext testContext) - { - if (testContext.Result?.State == TestState.Failed) - { - await _cancellationTokenSource.CancelAsync(); - - // We need a condition to end execution at some point otherwise we could go forever recursively - if (Interlocked.Increment(ref _count) > 5) - { - throw new Exception("DynamicDataGenerator reached maximum retry count."); - } - - if (IsReregisteredTest(testContext)) - { - // Optional to reduce noise - // testContext.SuppressReportingResult(); - } - - await testContext.ReregisterTestWithArguments(methodArguments: [new Random().Next()], - objectBag: new() - { - ["DynamicDataGeneratorRetry"] = true - }); - } - } - - private static bool IsReregisteredTest(TestContext testContext) - { - return testContext.ObjectBag.ContainsKey("DynamicDataGeneratorRetry"); - } - - public int Order => 0; -} diff --git a/TUnit.TestProject/SetHookExecutorTests.cs b/TUnit.TestProject/SetHookExecutorTests.cs new file mode 100644 index 0000000000..420fbe9ae5 --- /dev/null +++ b/TUnit.TestProject/SetHookExecutorTests.cs @@ -0,0 +1,119 @@ +using TUnit.Core.Executors; +using TUnit.Core.Interfaces; +using TUnit.TestProject.Attributes; +using TUnit.TestProject.TestExecutors; + +namespace TUnit.TestProject; + +/// +/// Attribute that sets both test and hook executors - mimics the user's [Dispatch] attribute from issue #2666 +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public class SetBothExecutorsAttribute : Attribute, ITestRegisteredEventReceiver +{ + public int Order => 0; + + public ValueTask OnTestRegistered(TestRegisteredContext context) + { + // Set both test and hook executors to use the same custom executor + // This is the key feature - users can now wrap all methods (test + hooks) in their custom dispatcher + var customExecutor = new CrossPlatformTestExecutor(); + context.SetTestExecutor(customExecutor); + context.SetHookExecutor(customExecutor); + + return default; + } +} + +/// +/// Tests demonstrating SetHookExecutor functionality for issue #2666 +/// Users can use an attribute that calls context.SetHookExecutor() to wrap both tests and their hooks in the same executor +/// +[EngineTest(ExpectedResult.Pass)] +[SetBothExecutors] // This attribute sets both executors +public class SetHookExecutorTests +{ + private static bool _beforeTestHookExecutedWithCustomExecutor; + private static bool _afterTestHookExecutedWithCustomExecutor; + + [Before(Test)] + public async Task BeforeTestHook(TestContext context) + { + // This hook should execute with the custom executor set by the attribute + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + await Assert.That(CrossPlatformTestExecutor.IsRunningInTestExecutor.Value).IsTrue(); + _beforeTestHookExecutedWithCustomExecutor = true; + } + + [After(Test)] + public async Task AfterTestHook(TestContext context) + { + // This hook should execute with the custom executor set by the attribute + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + await Assert.That(CrossPlatformTestExecutor.IsRunningInTestExecutor.Value).IsTrue(); + _afterTestHookExecutedWithCustomExecutor = true; + } + + [Test] + public async Task Test_ExecutesInCustomExecutor() + { + // Test should execute in custom executor + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + await Assert.That(CrossPlatformTestExecutor.IsRunningInTestExecutor.Value).IsTrue(); + } + + [Test] + public async Task Test_HooksAlsoExecuteInCustomExecutor() + { + // Verify that the hooks executed in the custom executor + await Assert.That(_beforeTestHookExecutedWithCustomExecutor).IsTrue(); + + // After hook will be verified by its own assertions + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + } +} + +/// +/// Tests demonstrating SetHookExecutor with static hooks +/// +[EngineTest(ExpectedResult.Pass)] +[SetBothExecutors] // This attribute sets both executors +public class SetHookExecutorWithStaticHooksTests +{ + [BeforeEvery(Test)] + public static async Task BeforeEveryTest(TestContext context) + { + // This static hook is GLOBAL and runs for ALL tests in the assembly + // Only run assertions for tests in SetHookExecutorWithStaticHooksTests class + if (context.TestDetails.ClassType == typeof(SetHookExecutorWithStaticHooksTests)) + { + // This static hook should execute with the custom executor when CustomHookExecutor is set + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + await Assert.That(CrossPlatformTestExecutor.IsRunningInTestExecutor.Value).IsTrue(); + context.ObjectBag["BeforeEveryExecuted"] = true; + } + } + + [AfterEvery(Test)] + public static async Task AfterEveryTest(TestContext context) + { + // This static hook is GLOBAL and runs for ALL tests in the assembly + // Only run assertions for tests in SetHookExecutorWithStaticHooksTests class + if (context.TestDetails.ClassType == typeof(SetHookExecutorWithStaticHooksTests)) + { + // This static hook should execute with the custom executor when CustomHookExecutor is set + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + await Assert.That(CrossPlatformTestExecutor.IsRunningInTestExecutor.Value).IsTrue(); + } + } + + [Test] + public async Task Test_StaticHooksExecuteInCustomExecutor() + { + // Verify the BeforeEvery hook ran + await Assert.That(TestContext.Current?.ObjectBag["BeforeEveryExecuted"]).IsEquatableOrEqualTo(true); + + // Test itself runs in custom executor + await Assert.That(Thread.CurrentThread.Name).IsEqualTo("CrossPlatformTestExecutor"); + } +} diff --git a/TUnit.TestProject/TestVariantTests.cs b/TUnit.TestProject/TestVariantTests.cs new file mode 100644 index 0000000000..db1007848a --- /dev/null +++ b/TUnit.TestProject/TestVariantTests.cs @@ -0,0 +1,61 @@ +using TUnit.Core; +using TUnit.Core.Extensions; + +namespace TUnit.TestProject; + +public class TestVariantTests +{ + [Test] + public async Task CreateTestVariant_ShouldCreateVariantWithDifferentArguments() + { + var context = TestContext.Current; + + if (context == null) + { + throw new InvalidOperationException("TestContext.Current is null"); + } + + await context.CreateTestVariant( + arguments: new object?[] { 42 }, + properties: new Dictionary + { + { "AttemptNumber", 1 } + }, + relationship: TUnit.Core.Enums.TestRelationship.Derived, + displayName: "Shrink Attempt" + ); + } + + [Test] + [Arguments(10)] + public async Task VariantTarget_WithArguments(int value) + { + var context = TestContext.Current; + + if (context == null) + { + throw new InvalidOperationException("TestContext.Current is null"); + } + + if (value < 0) + { + throw new InvalidOperationException($"Expected non-negative value but got {value}"); + } + + if (context.ObjectBag.ContainsKey("AttemptNumber")) + { + var attemptNumber = context.ObjectBag["AttemptNumber"]; + context.WriteLine($"Shrink attempt {attemptNumber} with value {value}"); + + if (context.Relationship != TUnit.Core.Enums.TestRelationship.Derived) + { + throw new InvalidOperationException($"Expected Derived relationship but got {context.Relationship}"); + } + + if (context.ParentTestId == null) + { + throw new InvalidOperationException("Expected ParentTestId to be set for shrink attempt"); + } + } + } +} diff --git a/TUnit/TUnit.csproj b/TUnit/TUnit.csproj index 90d69d876e..8da0bf21bf 100644 --- a/TUnit/TUnit.csproj +++ b/TUnit/TUnit.csproj @@ -7,6 +7,11 @@ + + + + + diff --git a/assets/banner.png b/assets/banner.png index 6878e6f354..ae5cb4b575 100644 Binary files a/assets/banner.png and b/assets/banner.png differ diff --git a/docs/docs/advanced/extension-points.md b/docs/docs/advanced/extension-points.md index b319f0ec67..14e8c087a8 100644 --- a/docs/docs/advanced/extension-points.md +++ b/docs/docs/advanced/extension-points.md @@ -15,7 +15,7 @@ The `ITestExecutor` interface allows you to customize how tests are executed. Th ```csharp public interface ITestExecutor { - Task ExecuteAsync(TestContext context, Func testBody); + ValueTask ExecuteTest(TestContext context, Func action); } ``` @@ -24,13 +24,13 @@ public interface ITestExecutor ```csharp public class TimingTestExecutor : ITestExecutor { - public async Task ExecuteAsync(TestContext context, Func testBody) + public async ValueTask ExecuteTest(TestContext context, Func action) { var stopwatch = Stopwatch.StartNew(); try { - await testBody(); + await action(); } finally { @@ -87,48 +87,97 @@ The `IHookExecutor` interface allows you to customize how setup and cleanup hook ```csharp public interface IHookExecutor { - Task ExecuteAsync(HookContext context, Func hookBody); + ValueTask ExecuteBeforeTestDiscoveryHook(MethodMetadata hookMethodInfo, BeforeTestDiscoveryContext context, Func action); + ValueTask ExecuteBeforeTestSessionHook(MethodMetadata hookMethodInfo, TestSessionContext context, Func action); + ValueTask ExecuteBeforeAssemblyHook(MethodMetadata hookMethodInfo, AssemblyHookContext context, Func action); + ValueTask ExecuteBeforeClassHook(MethodMetadata hookMethodInfo, ClassHookContext context, Func action); + ValueTask ExecuteBeforeTestHook(MethodMetadata hookMethodInfo, TestContext context, Func action); + + ValueTask ExecuteAfterTestDiscoveryHook(MethodMetadata hookMethodInfo, TestDiscoveryContext context, Func action); + ValueTask ExecuteAfterTestSessionHook(MethodMetadata hookMethodInfo, TestSessionContext context, Func action); + ValueTask ExecuteAfterAssemblyHook(MethodMetadata hookMethodInfo, AssemblyHookContext context, Func action); + ValueTask ExecuteAfterClassHook(MethodMetadata hookMethodInfo, ClassHookContext context, Func action); + ValueTask ExecuteAfterTestHook(MethodMetadata hookMethodInfo, TestContext context, Func action); } ``` +**Note**: This interface has specific methods for each hook type (Before/After × TestDiscovery/TestSession/Assembly/Class/Test). Each method receives: +- `MethodMetadata hookMethodInfo`: Information about the hook method being executed +- A context object specific to the hook type +- The `action` to execute (the actual hook logic) + ### Example Implementation ```csharp -public class ResourceManagingHookExecutor : IHookExecutor +public class LoggingHookExecutor : IHookExecutor { - private static readonly Dictionary Resources = new(); + public async ValueTask ExecuteBeforeTestDiscoveryHook(MethodMetadata hookMethodInfo, BeforeTestDiscoveryContext context, Func action) + { + Console.WriteLine($"Before test discovery hook: {hookMethodInfo.MethodName}"); + await action(); + } - public async Task ExecuteAsync(HookContext context, Func hookBody) + public async ValueTask ExecuteBeforeTestSessionHook(MethodMetadata hookMethodInfo, TestSessionContext context, Func action) { - if (context.HookType == HookType.Before) - { - // Allocate resources before the hook - var resource = AllocateResource(context.TestContext.TestName); - Resources[context.TestContext.TestName] = resource; - } + Console.WriteLine($"Before test session hook: {hookMethodInfo.MethodName}"); + await action(); + } + + public async ValueTask ExecuteBeforeAssemblyHook(MethodMetadata hookMethodInfo, AssemblyHookContext context, Func action) + { + Console.WriteLine($"Before assembly hook: {hookMethodInfo.MethodName}"); + await action(); + } + + public async ValueTask ExecuteBeforeClassHook(MethodMetadata hookMethodInfo, ClassHookContext context, Func action) + { + Console.WriteLine($"Before class hook: {hookMethodInfo.MethodName} for class {context.TestClassType.Name}"); try { - await hookBody(); + await action(); } - finally + catch (Exception ex) { - if (context.HookType == HookType.After) - { - // Clean up resources after the hook - if (Resources.TryGetValue(context.TestContext.TestName, out var resource)) - { - resource.Dispose(); - Resources.Remove(context.TestContext.TestName); - } - } + Console.WriteLine($"Hook failed: {ex.Message}"); + throw; } } - private IDisposable AllocateResource(string testName) + public async ValueTask ExecuteBeforeTestHook(MethodMetadata hookMethodInfo, TestContext context, Func action) + { + Console.WriteLine($"Before test hook: {hookMethodInfo.MethodName} for test {context.TestDetails.TestName}"); + await action(); + } + + public async ValueTask ExecuteAfterTestDiscoveryHook(MethodMetadata hookMethodInfo, TestDiscoveryContext context, Func action) { - // Allocate some resource - return new SomeResource(testName); + await action(); + Console.WriteLine($"After test discovery hook: {hookMethodInfo.MethodName}"); + } + + public async ValueTask ExecuteAfterTestSessionHook(MethodMetadata hookMethodInfo, TestSessionContext context, Func action) + { + await action(); + Console.WriteLine($"After test session hook: {hookMethodInfo.MethodName}"); + } + + public async ValueTask ExecuteAfterAssemblyHook(MethodMetadata hookMethodInfo, AssemblyHookContext context, Func action) + { + await action(); + Console.WriteLine($"After assembly hook: {hookMethodInfo.MethodName}"); + } + + public async ValueTask ExecuteAfterClassHook(MethodMetadata hookMethodInfo, ClassHookContext context, Func action) + { + await action(); + Console.WriteLine($"After class hook: {hookMethodInfo.MethodName} for class {context.TestClassType.Name}"); + } + + public async ValueTask ExecuteAfterTestHook(MethodMetadata hookMethodInfo, TestContext context, Func action) + { + await action(); + Console.WriteLine($"After test hook: {hookMethodInfo.MethodName} for test {context.TestDetails.TestName}"); } } ``` @@ -292,34 +341,59 @@ public class DatabaseTests ### IParallelConstraint -Defines constraints for parallel execution. +Defines constraints for parallel execution. This is a marker interface with no members - it's used to identify types that represent parallel execution constraints. ```csharp public interface IParallelConstraint { - string ConstraintKey { get; } } ``` +**Note**: `IParallelConstraint` is a marker interface. The actual constraint logic is handled by TUnit's built-in constraint implementations like `NotInParallelConstraint` and `ParallelGroupConstraint`. + Example: ```csharp -public class SharedResourceConstraint : IParallelConstraint +public class FileAccessTests { - public string ConstraintKey => "SharedFile"; -} + [Test] + [NotInParallel("SharedFile")] + public async Task Test1() + { + // This test won't run in parallel with other tests + // that have the same constraint key "SharedFile" + await File.WriteAllTextAsync("shared.txt", "test1"); + } -[NotInParallel] -public async Task Test1() -{ - // This test won't run in parallel with other tests - // that have the same constraint + [Test] + [NotInParallel("SharedFile")] + public async Task Test2() + { + // This test won't run in parallel with Test1 + // because they share the same constraint key + await File.WriteAllTextAsync("shared.txt", "test2"); + } + + [Test] + [NotInParallel("Database")] + public async Task Test3() + { + // This test can run in parallel with Test1 and Test2 + // because it has a different constraint key + await Database.ExecuteAsync("UPDATE users SET status = 'active'"); + } } +``` + +You can also use the `NotInParallel` attribute without arguments to ensure tests don't run in parallel with any other tests: -[NotInParallel] -public async Task Test2() +```csharp +[Test] +[NotInParallel] +public async Task GloballySerializedTest() { - // This test won't run in parallel with Test1 + // This test won't run in parallel with any other tests + // marked with [NotInParallel] (no constraint key) } ``` @@ -397,7 +471,7 @@ Here's a complete example that wraps each test in a database transaction: ```csharp public class TransactionalTestExecutor : ITestExecutor { - public async Task ExecuteAsync(TestContext context, Func testBody) + public async ValueTask ExecuteTest(TestContext context, Func action) { // Get the database connection from DI var dbContext = context.GetService(); @@ -406,7 +480,7 @@ public class TransactionalTestExecutor : ITestExecutor try { - await testBody(); + await action(); // Rollback instead of commit to keep tests isolated await transaction.RollbackAsync(); diff --git a/docs/docs/advanced/test-variants.md b/docs/docs/advanced/test-variants.md new file mode 100644 index 0000000000..7862a0327c --- /dev/null +++ b/docs/docs/advanced/test-variants.md @@ -0,0 +1,483 @@ +# Test Variants + +Test variants enable you to dynamically create additional test cases during test execution based on runtime results. This powerful feature unlocks advanced testing patterns like property-based testing shrinking, mutation testing, adaptive stress testing, and intelligent retry strategies. + +## What Are Test Variants? + +Test variants are tests that are created **during the execution** of a parent test, inheriting the parent's test method template but potentially using different arguments, properties, or display names. They appear as distinct tests in the test explorer and can have their own outcomes. + +### Test Variants vs Dynamic Tests + +| Feature | Test Variants (`CreateTestVariant`) | Dynamic Tests (`AddDynamicTest`) | +|---------|-------------------------------------|----------------------------------| +| **Created** | During test execution | During test discovery | +| **Parent** | Always has a parent test | Standalone tests | +| **Template** | Reuses parent's test method | Requires explicit method definition | +| **Use Case** | Runtime adaptation (shrinking, mutation, stress) | Pre-generation of test cases | +| **AOT Compatible** | No (requires reflection) | Yes (with source generators) | + +## Core Concepts + +### TestRelationship Enum + +The `TestRelationship` enum categorizes how a variant relates to its parent, informing the test runner about execution semantics: + +```csharp +public enum TestRelationship +{ + None, // Independent test (no parent) + Retry, // Identical re-run after failure + Generated, // Pre-execution exploration (e.g., initial PBT cases) + Derived // Post-execution analysis (e.g., shrinking, mutation) +} +``` + +**When to use each:** +- **`Retry`**: For identical re-runs, typically handled by `[Retry]` attribute +- **`Generated`**: For upfront test case generation before execution +- **`Derived`**: For runtime analysis based on parent results (most common for variants) + +### DisplayName Parameter + +The optional `displayName` parameter provides user-facing labels in test explorers and reports. While the `TestRelationship` informs the framework about execution semantics, `displayName` communicates intent to humans: + +```csharp +await context.CreateTestVariant( + arguments: new object[] { smallerInput }, + relationship: TestRelationship.Derived, + displayName: "Shrink Attempt #3" // Shows in test explorer +); +``` + +### Properties Dictionary + +Store metadata for filtering, reporting, or variant logic: + +```csharp +await context.CreateTestVariant( + arguments: new object[] { mutatedValue }, + properties: new Dictionary + { + { "AttemptNumber", 3 }, + { "ShrinkStrategy", "Binary" }, + { "OriginalValue", originalInput } + }, + relationship: TestRelationship.Derived, + displayName: "Shrink #3 (Binary)" +); +``` + +## Use Cases + +### 1. Property-Based Testing (PBT) - Shrinking + +When a property-based test fails with a complex input, create variants with progressively simpler inputs to find the minimal failing case. Use a custom attribute implementing `ITestEndEventReceiver` to automatically shrink on failure: + +```csharp +// Custom attribute that shrinks inputs on test failure +public class ShrinkOnFailureAttribute : Attribute, ITestEndEventReceiver +{ + private readonly int _maxAttempts; + + public ShrinkOnFailureAttribute(int maxAttempts = 5) + { + _maxAttempts = maxAttempts; + } + + public async ValueTask OnTestEnd(TestContext testContext) + { + // Only shrink if test failed and it's not already a shrink attempt + if (testContext.Result?.Status != TestStatus.Failed) + return; + + if (testContext.Relationship == TestRelationship.Derived) + return; // Don't shrink shrink attempts + + // Get the test's numeric argument to shrink + var args = testContext.TestDetails.TestMethodArguments; + if (args.Length == 0 || args[0] is not int size) + return; + + if (size <= 1) + return; // Can't shrink further + + // Create shrink variants + var shrinkSize = size / 2; + for (int attempt = 1; attempt <= _maxAttempts && shrinkSize > 0; attempt++) + { + await testContext.CreateTestVariant( + arguments: new object[] { shrinkSize }, + properties: new Dictionary + { + { "AttemptNumber", attempt }, + { "OriginalSize", size }, + { "ShrinkStrategy", "Binary" } + }, + relationship: TestRelationship.Derived, + displayName: $"Shrink #{attempt} (size={shrinkSize})" + ); + + shrinkSize /= 2; + } + } +} + +// Usage: Just add the attribute - shrinking happens automatically on failure +[Test] +[ShrinkOnFailure(maxAttempts: 5)] +[Arguments(1000)] +[Arguments(500)] +[Arguments(100)] +public async Task PropertyTest_ListReversal(int size) +{ + var list = Enumerable.Range(0, size).ToList(); + + // Property: reversing twice should return original + var reversed = list.Reverse().Reverse().ToList(); + await Assert.That(reversed).IsEquivalentTo(list); + + // If this fails, the attribute automatically creates shrink variants +} +``` + +**Why this pattern is better:** +- **Separation of concerns**: Test logic stays clean, shrinking is in the attribute +- **Reusable**: Apply `[ShrinkOnFailure]` to any test with numeric inputs +- **Declarative**: Intent is clear from the attribute +- **Automatic**: No try-catch or manual failure detection needed + +### 2. Mutation Testing + +Create variants that test your test's ability to catch bugs by introducing controlled mutations: + +```csharp +[Test] +[Arguments(5, 10)] +public async Task CalculatorTest_Addition(int a, int b) +{ + var context = TestContext.Current!; + var calculator = new Calculator(); + + var result = calculator.Add(a, b); + await Assert.That(result).IsEqualTo(a + b); + + // After test passes, create mutants to verify test quality + var mutations = new[] + { + (a + 1, b, "Mutant: Boundary +1 on first arg"), + (a, b + 1, "Mutant: Boundary +1 on second arg"), + (a - 1, b, "Mutant: Boundary -1 on first arg"), + (0, 0, "Mutant: Zero case") + }; + + foreach (var (mutA, mutB, name) in mutations) + { + await context.CreateTestVariant( + arguments: new object[] { mutA, mutB }, + relationship: TestRelationship.Derived, + displayName: name + ); + } +} +``` + +### 3. Adaptive Stress Testing + +Progressively increase load based on system performance: + +```csharp +[Test] +[Arguments(10)] // Start with low load +public async Task LoadTest_ApiEndpoint(int concurrentUsers) +{ + var context = TestContext.Current!; + var stopwatch = Stopwatch.StartNew(); + + // Simulate load + var tasks = Enumerable.Range(0, concurrentUsers) + .Select(_ => CallApiAsync()) + .ToArray(); + + await Task.WhenAll(tasks); + stopwatch.Stop(); + + var avgResponseTime = stopwatch.ElapsedMilliseconds / (double)concurrentUsers; + context.WriteLine($"Users: {concurrentUsers}, Avg response: {avgResponseTime}ms"); + + // If system handled load well, increase it + if (avgResponseTime < 200 && concurrentUsers < 1000) + { + var nextLoad = concurrentUsers * 2; + await context.CreateTestVariant( + arguments: new object[] { nextLoad }, + properties: new Dictionary + { + { "PreviousLoad", concurrentUsers }, + { "PreviousAvgResponseTime", avgResponseTime } + }, + relationship: TestRelationship.Derived, + displayName: $"Load Test ({nextLoad} users)" + ); + } + + await Assert.That(avgResponseTime).IsLessThan(500); +} +``` + +### 4. Exploratory Fuzzing + +Generate additional test cases when edge cases are discovered: + +```csharp +[Test] +[Arguments("normal text")] +public async Task InputValidation_SpecialCharacters(string input) +{ + var context = TestContext.Current!; + var validator = new InputValidator(); + + var result = validator.Validate(input); + await Assert.That(result.IsValid).IsTrue(); + + // If we haven't tested special characters yet, generate variants + if (!context.ObjectBag.ContainsKey("TestedSpecialChars")) + { + context.ObjectBag["TestedSpecialChars"] = true; + + var specialInputs = new[] + { + "", + "'; DROP TABLE users; --", + "../../../etc/passwd", + "\0\0\0null bytes\0", + new string('A', 10000) // Buffer overflow attempt + }; + + foreach (var specialInput in specialInputs) + { + await context.CreateTestVariant( + arguments: new object[] { specialInput }, + relationship: TestRelationship.Derived, + displayName: $"Fuzz: {specialInput.Substring(0, Math.Min(30, specialInput.Length))}" + ); + } + } +} +``` + +### 5. Smart Retry with Parameter Adjustment + +Retry failed tests with adjusted parameters to differentiate transient failures from persistent bugs: + +```csharp +[Test] +[Arguments(TimeSpan.FromSeconds(5))] +public async Task ExternalService_WithTimeout(TimeSpan timeout) +{ + var context = TestContext.Current!; + + try + { + using var cts = new CancellationTokenSource(timeout); + var result = await _externalService.FetchDataAsync(cts.Token); + await Assert.That(result).IsNotNull(); + } + catch (TimeoutException ex) + { + // If timeout, try with longer timeout to see if it's a transient issue + if (timeout < TimeSpan.FromSeconds(30)) + { + var longerTimeout = timeout.Add(TimeSpan.FromSeconds(5)); + + await context.CreateTestVariant( + arguments: new object[] { longerTimeout }, + properties: new Dictionary + { + { "OriginalTimeout", timeout }, + { "RetryReason", "Timeout" } + }, + relationship: TestRelationship.Derived, + displayName: $"Retry with {longerTimeout.TotalSeconds}s timeout" + ); + } + + throw; + } +} +``` + +### 6. Chaos Engineering + +Inject faults and verify system resilience: + +```csharp +[Test] +public async Task Resilience_DatabaseFailover() +{ + var context = TestContext.Current!; + var system = new DistributedSystem(); + + // Normal operation test + var result = await system.ProcessRequestAsync(); + await Assert.That(result.Success).IsTrue(); + + // Create chaos variants + var chaosScenarios = new[] + { + ("primary-db-down", "Primary DB Failure"), + ("network-latency-500ms", "High Network Latency"), + ("replica-lag-10s", "Replica Lag"), + ("cascading-failure", "Cascading Failure") + }; + + foreach (var (faultType, displayName) in chaosScenarios) + { + await context.CreateTestVariant( + arguments: new object[] { faultType }, + properties: new Dictionary + { + { "ChaosType", faultType }, + { "InjectionPoint", "AfterSuccess" } + }, + relationship: TestRelationship.Derived, + displayName: $"Chaos: {displayName}" + ); + } +} +``` + +## API Reference + +### Method Signature + +```csharp +public static async Task CreateTestVariant( + this TestContext context, + object?[]? arguments = null, + Dictionary? properties = null, + TestRelationship relationship = TestRelationship.Derived, + string? displayName = null) +``` + +### Parameters + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `context` | `TestContext` | Yes | - | The current test context | +| `arguments` | `object?[]?` | No | `null` | Method arguments for the variant. If `null`, reuses parent's arguments | +| `properties` | `Dictionary?` | No | `null` | Custom metadata stored in the variant's `TestContext.ObjectBag` | +| `relationship` | `TestRelationship` | No | `Derived` | Categorizes the variant's relationship to its parent | +| `displayName` | `string?` | No | `null` | User-facing label shown in test explorers. If `null`, uses default format | + +### Return Value + +Returns `Task` that completes when the variant has been queued for execution. + +### Exceptions + +- `InvalidOperationException`: Thrown if `TestContext.Current` is null +- `InvalidOperationException`: Thrown if the test method cannot be resolved + +## Best Practices + +### 1. Choose Appropriate TestRelationship + +```csharp +// ✅ Good: Derived for post-execution analysis +await context.CreateTestVariant( + arguments: [smallerInput], + relationship: TestRelationship.Derived, + displayName: "Shrink Attempt" +); + +// ❌ Bad: Using None loses parent relationship +await context.CreateTestVariant( + arguments: [smallerInput], + relationship: TestRelationship.None // Parent link lost! +); +``` + +### 2. Provide Descriptive Display Names + +```csharp +// ✅ Good: Clear, specific, actionable +displayName: "Shrink #3 (Binary Search, size=125)" + +// ⚠️ Okay: Somewhat clear +displayName: "Shrink Attempt 3" + +// ❌ Bad: Vague, unhelpful +displayName: "Variant" +``` + +### 3. Avoid Infinite Recursion + +```csharp +[Test] +public async Task RecursiveVariant() +{ + var context = TestContext.Current!; + + // ✅ Good: Check depth + var depth = context.ObjectBag.TryGetValue("Depth", out var d) ? (int)d : 0; + if (depth < 5) + { + await context.CreateTestVariant( + properties: new Dictionary { { "Depth", depth + 1 } }, + relationship: TestRelationship.Derived + ); + } + + // ❌ Bad: Infinite loop! + // await context.CreateTestVariant(relationship: TestRelationship.Derived); +} +``` + +### 4. Use Properties for Metadata + +```csharp +// ✅ Good: Structured metadata +properties: new Dictionary +{ + { "AttemptNumber", 3 }, + { "Strategy", "BinarySearch" }, + { "OriginalValue", largeInput }, + { "Timestamp", DateTime.UtcNow } +} + +// ❌ Bad: Encoding metadata in displayName +displayName: "Attempt=3,Strategy=Binary,Original=1000,Time=2024-01-01" +``` + +### 5. Consider Performance + +Creating many variants has overhead. Be strategic: + +```csharp +// ✅ Good: Limited, strategic variants +if (shouldShrink && attemptCount < 10) +{ + await context.CreateTestVariant(...); +} + +// ❌ Bad: Explosion of variants +for (int i = 0; i < 10000; i++) // Creates 10,000 tests! +{ + await context.CreateTestVariant(...); +} +``` + +## Limitations + +- **Not AOT Compatible**: Test variants require runtime reflection and expression compilation +- **Requires Reflection Mode**: Must run with reflection-based discovery (not source-generated) +- **Performance Overhead**: Each variant is a full test execution with its own lifecycle +- **No Source Generator Support**: Cannot be used in AOT-compiled scenarios + +## See Also + +- [Test Context](../test-lifecycle/test-context.md) - Understanding TestContext and ObjectBag +- [Dynamic Tests](../experimental/dynamic-tests.md) - Pre-execution test generation +- [Retrying](../execution/retrying.md) - Built-in retry mechanism comparison +- [Properties](../test-lifecycle/properties.md) - Test metadata and custom properties +- [Event Subscribing](../test-lifecycle/event-subscribing.md) - Test lifecycle event receivers diff --git a/docs/docs/assertions/awaiting.md b/docs/docs/assertions/awaiting.md index e87dec0060..2185db045c 100644 --- a/docs/docs/assertions/awaiting.md +++ b/docs/docs/assertions/awaiting.md @@ -36,6 +36,29 @@ This won't: TUnit is able to take in asynchronous delegates. To be able to assert on these, we need to execute the code. We want to avoid sync-over-async, as this can cause problems and block the thread pool, slowing down your test suite. And with how fast .NET has become, the overhead of `Task`s and `async` methods shouldn't be noticeable. +## Using Return Values from Awaited Assertions + +When you `await` an assertion in TUnit, it returns a reference to the subject that was asserted on. This allows you to capture the validated value and use it in subsequent operations or assertions, creating a fluent and readable test flow. + +### Type Casting with Confidence + +```csharp +[Test] +public async Task CastAndUseSpecificType() +{ + object shape = new Circle { Radius = 5.0 }; + + // Assert type and capture strongly-typed reference + var circle = await Assert.That(shape).IsTypeOf(); + + // Now you can use circle-specific properties without casting + await Assert.That(circle.Radius).IsEqualTo(5.0); + + var area = Math.PI * circle.Radius * circle.Radius; + await Assert.That(area).IsEqualTo(Math.PI * 25).Within(0.0001); +} +``` + ## Complex Assertion Examples ### Chaining Multiple Assertions diff --git a/docs/docs/assertions/boolean.md b/docs/docs/assertions/boolean.md new file mode 100644 index 0000000000..6773c02b2a --- /dev/null +++ b/docs/docs/assertions/boolean.md @@ -0,0 +1,463 @@ +--- +sidebar_position: 3.5 +--- + +# Boolean Assertions + +TUnit provides simple, expressive assertions for testing boolean values. These assertions work with both `bool` and `bool?` (nullable boolean) types. + +## Basic Boolean Assertions + +### IsTrue + +Tests that a boolean value is `true`: + +```csharp +[Test] +public async Task Value_Is_True() +{ + var isValid = ValidateInput("test@example.com"); + await Assert.That(isValid).IsTrue(); + + var hasPermission = user.HasPermission("write"); + await Assert.That(hasPermission).IsTrue(); +} +``` + +### IsFalse + +Tests that a boolean value is `false`: + +```csharp +[Test] +public async Task Value_Is_False() +{ + var isExpired = CheckIfExpired(futureDate); + await Assert.That(isExpired).IsFalse(); + + var isEmpty = list.Count == 0; + await Assert.That(isEmpty).IsFalse(); +} +``` + +## Alternative: Using IsEqualTo + +You can also use `IsEqualTo()` for boolean comparisons: + +```csharp +[Test] +public async Task Using_IsEqualTo() +{ + var result = PerformCheck(); + + await Assert.That(result).IsEqualTo(true); + // Same as: await Assert.That(result).IsTrue(); + + await Assert.That(result).IsEqualTo(false); + // Same as: await Assert.That(result).IsFalse(); +} +``` + +However, `IsTrue()` and `IsFalse()` are more expressive and recommended for boolean values. + +## Nullable Booleans + +Both assertions work with nullable booleans (`bool?`): + +```csharp +[Test] +public async Task Nullable_Boolean_True() +{ + bool? result = GetOptionalFlag(); + + await Assert.That(result).IsTrue(); + // This asserts both: + // 1. result is not null + // 2. result.Value is true +} + +[Test] +public async Task Nullable_Boolean_False() +{ + bool? result = GetOptionalFlag(); + + await Assert.That(result).IsFalse(); + // This asserts both: + // 1. result is not null + // 2. result.Value is false +} +``` + +### Null Nullable Booleans + +If a nullable boolean is `null`, both `IsTrue()` and `IsFalse()` will fail: + +```csharp +[Test] +public async Task Nullable_Boolean_Null() +{ + bool? result = null; + + // These will both fail: + // await Assert.That(result).IsTrue(); // ❌ Fails - null is not true + // await Assert.That(result).IsFalse(); // ❌ Fails - null is not false + + // Check for null first: + await Assert.That(result).IsNull(); +} +``` + +## Chaining Boolean Assertions + +Boolean assertions can be chained with other assertions: + +```csharp +[Test] +public async Task Chained_With_Other_Assertions() +{ + bool? flag = GetFlag(); + + await Assert.That(flag) + .IsNotNull() + .And.IsTrue(); +} +``` + +## Practical Examples + +### Validation Results + +```csharp +[Test] +public async Task Email_Validation() +{ + var isValid = EmailValidator.Validate("test@example.com"); + await Assert.That(isValid).IsTrue(); + + var isInvalid = EmailValidator.Validate("not-an-email"); + await Assert.That(isInvalid).IsFalse(); +} +``` + +### Permission Checks + +```csharp +[Test] +public async Task User_Permissions() +{ + var user = await GetUserAsync("alice"); + + await Assert.That(user.CanRead).IsTrue(); + await Assert.That(user.CanWrite).IsTrue(); + await Assert.That(user.CanDelete).IsFalse(); +} +``` + +### State Flags + +```csharp +[Test] +public async Task Service_State() +{ + var service = new BackgroundService(); + + await Assert.That(service.IsRunning).IsFalse(); + + await service.StartAsync(); + + await Assert.That(service.IsRunning).IsTrue(); +} +``` + +### Feature Flags + +```csharp +[Test] +public async Task Feature_Toggles() +{ + var config = LoadConfiguration(); + + await Assert.That(config.EnableNewFeature).IsTrue(); + await Assert.That(config.EnableBetaFeature).IsFalse(); +} +``` + +## Testing Conditional Logic + +### Logical AND + +```csharp +[Test] +public async Task Logical_AND() +{ + var isAdult = age >= 18; + var hasLicense = CheckLicense(userId); + var canDrive = isAdult && hasLicense; + + await Assert.That(canDrive).IsTrue(); +} +``` + +### Logical OR + +```csharp +[Test] +public async Task Logical_OR() +{ + var isWeekend = dayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday; + var isHoliday = CheckIfHoliday(date); + var isDayOff = isWeekend || isHoliday; + + await Assert.That(isDayOff).IsTrue(); +} +``` + +### Logical NOT + +```csharp +[Test] +public async Task Logical_NOT() +{ + var isExpired = CheckExpiration(token); + var isValid = !isExpired; + + await Assert.That(isValid).IsTrue(); +} +``` + +## Complex Boolean Expressions + +```csharp +[Test] +public async Task Complex_Expression() +{ + var user = GetUser(); + var canAccess = user.IsActive && + !user.IsBanned && + (user.IsPremium || user.HasFreeTrial); + + await Assert.That(canAccess).IsTrue(); +} +``` + +You can also break this down for clarity: + +```csharp +[Test] +public async Task Complex_Expression_Broken_Down() +{ + var user = GetUser(); + + await using (Assert.Multiple()) + { + await Assert.That(user.IsActive).IsTrue(); + await Assert.That(user.IsBanned).IsFalse(); + await Assert.That(user.IsPremium || user.HasFreeTrial).IsTrue(); + } +} +``` + +## Comparison with Other Values + +When testing boolean results of comparisons, you can often simplify: + +```csharp +[Test] +public async Task Comparison_Simplified() +{ + var count = GetCount(); + + // Less clear: + await Assert.That(count > 0).IsTrue(); + + // More clear and expressive: + await Assert.That(count).IsGreaterThan(0); +} +``` + +Similarly for equality: + +```csharp +[Test] +public async Task Equality_Simplified() +{ + var name = GetName(); + + // Less clear: + await Assert.That(name == "Alice").IsTrue(); + + // More clear: + await Assert.That(name).IsEqualTo("Alice"); +} +``` + +Use boolean assertions for actual boolean values and flags, not for comparisons. + +## Testing LINQ Queries + +```csharp +[Test] +public async Task LINQ_Any() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + var hasEven = numbers.Any(n => n % 2 == 0); + await Assert.That(hasEven).IsTrue(); + + var hasNegative = numbers.Any(n => n < 0); + await Assert.That(hasNegative).IsFalse(); +} + +[Test] +public async Task LINQ_All() +{ + var numbers = new[] { 2, 4, 6, 8 }; + + var allEven = numbers.All(n => n % 2 == 0); + await Assert.That(allEven).IsTrue(); + + var allPositive = numbers.All(n => n > 0); + await Assert.That(allPositive).IsTrue(); +} +``` + +Note: TUnit provides specialized collection assertions for these patterns: + +```csharp +[Test] +public async Task Using_Collection_Assertions() +{ + var numbers = new[] { 2, 4, 6, 8 }; + + // Instead of .All(n => n % 2 == 0): + await Assert.That(numbers).All(n => n % 2 == 0); + + // Instead of .Any(n => n > 5): + await Assert.That(numbers).Any(n => n > 5); +} +``` + +## String Boolean Methods + +Many string methods return booleans: + +```csharp +[Test] +public async Task String_Boolean_Methods() +{ + var text = "Hello World"; + + await Assert.That(text.StartsWith("Hello")).IsTrue(); + await Assert.That(text.EndsWith("World")).IsTrue(); + await Assert.That(text.Contains("lo Wo")).IsTrue(); + await Assert.That(string.IsNullOrEmpty(text)).IsFalse(); +} +``` + +But TUnit has more expressive string assertions: + +```csharp +[Test] +public async Task Using_String_Assertions() +{ + var text = "Hello World"; + + // More expressive: + await Assert.That(text).StartsWith("Hello"); + await Assert.That(text).EndsWith("World"); + await Assert.That(text).Contains("lo Wo"); + await Assert.That(text).IsNotEmpty(); +} +``` + +## Type Checking Booleans + +```csharp +[Test] +public async Task Type_Checking() +{ + var obj = GetObject(); + + await Assert.That(obj is string).IsTrue(); + await Assert.That(obj is not null).IsTrue(); +} +``` + +Or use type assertions: + +```csharp +[Test] +public async Task Using_Type_Assertions() +{ + var obj = GetObject(); + + await Assert.That(obj).IsTypeOf(); + await Assert.That(obj).IsNotNull(); +} +``` + +## Common Patterns + +### Toggle Testing + +```csharp +[Test] +public async Task Toggle_State() +{ + var toggle = new Toggle(); + + await Assert.That(toggle.IsOn).IsFalse(); + + toggle.TurnOn(); + await Assert.That(toggle.IsOn).IsTrue(); + + toggle.TurnOff(); + await Assert.That(toggle.IsOn).IsFalse(); +} +``` + +### Authentication State + +```csharp +[Test] +public async Task Authentication_State() +{ + var authService = new AuthenticationService(); + + await Assert.That(authService.IsAuthenticated).IsFalse(); + + await authService.LoginAsync("user", "password"); + + await Assert.That(authService.IsAuthenticated).IsTrue(); +} +``` + +### Validation Scenarios + +```csharp +[Test] +public async Task Multiple_Validations() +{ + var form = new RegistrationForm + { + Email = "test@example.com", + Password = "SecurePass123!", + Age = 25 + }; + + await using (Assert.Multiple()) + { + await Assert.That(form.IsEmailValid()).IsTrue(); + await Assert.That(form.IsPasswordStrong()).IsTrue(); + await Assert.That(form.IsAgeValid()).IsTrue(); + await Assert.That(form.IsComplete()).IsTrue(); + } +} +``` + +## See Also + +- [Equality & Comparison](equality-and-comparison.md) - General equality testing +- [Null & Default](null-and-default.md) - Testing for null values +- [Collections](collections.md) - Collection-specific boolean tests (All, Any) +- [Type Assertions](types.md) - Type checking instead of `is` checks diff --git a/docs/docs/assertions/collections.md b/docs/docs/assertions/collections.md new file mode 100644 index 0000000000..c11eec5f33 --- /dev/null +++ b/docs/docs/assertions/collections.md @@ -0,0 +1,788 @@ +--- +sidebar_position: 6.5 +--- + +# Collection Assertions + +TUnit provides comprehensive assertions for testing collections, including membership, count, ordering, and equivalency checks. These assertions work with any `IEnumerable`. + +## Membership Assertions + +### Contains (Item) + +Tests that a collection contains a specific item: + +```csharp +[Test] +public async Task Collection_Contains_Item() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers).Contains(3); + await Assert.That(numbers).Contains(1); +} +``` + +Works with any collection type: + +```csharp +[Test] +public async Task Various_Collection_Types() +{ + var list = new List { "apple", "banana", "cherry" }; + await Assert.That(list).Contains("banana"); + + var hashSet = new HashSet { 10, 20, 30 }; + await Assert.That(hashSet).Contains(20); + + var queue = new Queue(new[] { "first", "second" }); + await Assert.That(queue).Contains("first"); +} +``` + +### Contains (Predicate) + +Tests that a collection contains an item matching a predicate, and returns that item: + +```csharp +[Test] +public async Task Collection_Contains_Matching_Item() +{ + var users = new[] + { + new User { Name = "Alice", Age = 30 }, + new User { Name = "Bob", Age = 25 } + }; + + // Returns the found item + var user = await Assert.That(users).Contains(u => u.Name == "Alice"); + + // Can assert on the returned item + await Assert.That(user.Age).IsEqualTo(30); +} +``` + +### DoesNotContain (Item) + +Tests that a collection does not contain a specific item: + +```csharp +[Test] +public async Task Collection_Does_Not_Contain() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers).DoesNotContain(10); + await Assert.That(numbers).DoesNotContain(0); +} +``` + +### DoesNotContain (Predicate) + +Tests that no items match the predicate: + +```csharp +[Test] +public async Task Collection_Does_Not_Contain_Matching() +{ + var users = new[] + { + new User { Name = "Alice", Age = 30 }, + new User { Name = "Bob", Age = 25 } + }; + + await Assert.That(users).DoesNotContain(u => u.Age > 50); + await Assert.That(users).DoesNotContain(u => u.Name == "Charlie"); +} +``` + +## Count Assertions + +### HasCount + +Tests that a collection has an exact count: + +```csharp +[Test] +public async Task Collection_Has_Count() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers).HasCount(5); +} +``` + +### Count with Comparison + +Get the count for further assertions: + +```csharp +[Test] +public async Task Count_With_Comparison() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers) + .HasCount().EqualTo(5); + + await Assert.That(numbers) + .HasCount().GreaterThan(3) + .And.HasCount().LessThan(10); +} +``` + +### Count with Predicate + +Count items matching a predicate: + +```csharp +[Test] +public async Task Count_With_Predicate() +{ + var numbers = new[] { 1, 2, 3, 4, 5, 6 }; + + // Count even numbers + var evenCount = await Assert.That(numbers) + .Count(n => n % 2 == 0); + + await Assert.That(evenCount).IsEqualTo(3); +} +``` + +### IsEmpty + +Tests that a collection has no items: + +```csharp +[Test] +public async Task Collection_Is_Empty() +{ + var empty = new List(); + + await Assert.That(empty).IsEmpty(); + await Assert.That(empty).HasCount(0); +} +``` + +### IsNotEmpty + +Tests that a collection has at least one item: + +```csharp +[Test] +public async Task Collection_Is_Not_Empty() +{ + var numbers = new[] { 1 }; + + await Assert.That(numbers).IsNotEmpty(); +} +``` + +### HasSingleItem + +Tests that a collection has exactly one item, and returns that item: + +```csharp +[Test] +public async Task Collection_Has_Single_Item() +{ + var users = new[] { new User { Name = "Alice", Age = 30 } }; + + var user = await Assert.That(users).HasSingleItem(); + + await Assert.That(user.Name).IsEqualTo("Alice"); +} +``` + +## Ordering Assertions + +### IsInOrder + +Tests that a collection is sorted in ascending order: + +```csharp +[Test] +public async Task Collection_In_Ascending_Order() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers).IsInOrder(); +} +``` + +```csharp +[Test] +public async Task Strings_In_Order() +{ + var names = new[] { "Alice", "Bob", "Charlie" }; + + await Assert.That(names).IsInOrder(); +} +``` + +### IsInDescendingOrder + +Tests that a collection is sorted in descending order: + +```csharp +[Test] +public async Task Collection_In_Descending_Order() +{ + var numbers = new[] { 5, 4, 3, 2, 1 }; + + await Assert.That(numbers).IsInDescendingOrder(); +} +``` + +### IsOrderedBy + +Tests that a collection is ordered by a specific property: + +```csharp +[Test] +public async Task Ordered_By_Property() +{ + var users = new[] + { + new User { Name = "Alice", Age = 25 }, + new User { Name = "Bob", Age = 30 }, + new User { Name = "Charlie", Age = 35 } + }; + + await Assert.That(users).IsOrderedBy(u => u.Age); +} +``` + +### IsOrderedByDescending + +Tests that a collection is ordered by a property in descending order: + +```csharp +[Test] +public async Task Ordered_By_Descending() +{ + var users = new[] + { + new User { Name = "Charlie", Age = 35 }, + new User { Name = "Bob", Age = 30 }, + new User { Name = "Alice", Age = 25 } + }; + + await Assert.That(users).IsOrderedByDescending(u => u.Age); +} +``` + +## Predicate-Based Assertions + +### All + +Tests that all items satisfy a condition: + +```csharp +[Test] +public async Task All_Items_Match() +{ + var numbers = new[] { 2, 4, 6, 8 }; + + await Assert.That(numbers).All(n => n % 2 == 0); +} +``` + +#### With Satisfy + +Chain additional assertions on all items: + +```csharp +[Test] +public async Task All_Satisfy() +{ + var users = new[] + { + new User { Name = "Alice", Age = 25 }, + new User { Name = "Bob", Age = 30 } + }; + + await Assert.That(users) + .All() + .Satisfy(u => Assert.That(u.Age).IsGreaterThan(18)); +} +``` + +#### With Mapper + +Map items before asserting: + +```csharp +[Test] +public async Task All_Satisfy_With_Mapper() +{ + var users = new[] + { + new User { Name = "Alice", Age = 25 }, + new User { Name = "Bob", Age = 30 } + }; + + await Assert.That(users) + .All() + .Satisfy( + u => u.Name, + name => Assert.That(name).IsNotEmpty() + ); +} +``` + +### Any + +Tests that at least one item satisfies a condition: + +```csharp +[Test] +public async Task Any_Item_Matches() +{ + var numbers = new[] { 1, 3, 5, 6, 7 }; + + await Assert.That(numbers).Any(n => n % 2 == 0); +} +``` + +## Equivalency Assertions + +### IsEquivalentTo + +Tests that two collections contain the same items, regardless of order: + +```csharp +[Test] +public async Task Collections_Are_Equivalent() +{ + var actual = new[] { 1, 2, 3, 4, 5 }; + var expected = new[] { 5, 4, 3, 2, 1 }; + + await Assert.That(actual).IsEquivalentTo(expected); +} +``` + +Different collection types: + +```csharp +[Test] +public async Task Different_Collection_Types() +{ + var list = new List { 1, 2, 3 }; + var array = new[] { 3, 2, 1 }; + + await Assert.That(list).IsEquivalentTo(array); +} +``` + +#### With Custom Comparer + +```csharp +[Test] +public async Task Equivalent_With_Comparer() +{ + var actual = new[] { "apple", "banana", "cherry" }; + var expected = new[] { "APPLE", "BANANA", "CHERRY" }; + + await Assert.That(actual) + .IsEquivalentTo(expected) + .Using(StringComparer.OrdinalIgnoreCase); +} +``` + +#### With Custom Equality Predicate + +```csharp +[Test] +public async Task Equivalent_With_Predicate() +{ + var users1 = new[] + { + new User { Name = "Alice", Age = 30 }, + new User { Name = "Bob", Age = 25 } + }; + + var users2 = new[] + { + new User { Name = "Bob", Age = 25 }, + new User { Name = "Alice", Age = 30 } + }; + + await Assert.That(users1) + .IsEquivalentTo(users2) + .Using((u1, u2) => u1.Name == u2.Name && u1.Age == u2.Age); +} +``` + +#### Explicitly Ignoring Order + +```csharp +[Test] +public async Task Equivalent_Ignoring_Order() +{ + var actual = new[] { 1, 2, 3 }; + var expected = new[] { 3, 2, 1 }; + + await Assert.That(actual) + .IsEquivalentTo(expected) + .IgnoringOrder(); +} +``` + +### IsNotEquivalentTo + +Tests that collections are not equivalent: + +```csharp +[Test] +public async Task Collections_Not_Equivalent() +{ + var actual = new[] { 1, 2, 3 }; + var different = new[] { 4, 5, 6 }; + + await Assert.That(actual).IsNotEquivalentTo(different); +} +``` + +## Structural Equivalency + +### IsStructurallyEqualTo + +Deep comparison of collections including nested objects: + +```csharp +[Test] +public async Task Structurally_Equal() +{ + var actual = new[] + { + new { Name = "Alice", Address = new { City = "Seattle" } }, + new { Name = "Bob", Address = new { City = "Portland" } } + }; + + var expected = new[] + { + new { Name = "Alice", Address = new { City = "Seattle" } }, + new { Name = "Bob", Address = new { City = "Portland" } } + }; + + await Assert.That(actual).IsStructurallyEqualTo(expected); +} +``` + +### IsNotStructurallyEqualTo + +```csharp +[Test] +public async Task Not_Structurally_Equal() +{ + var actual = new[] + { + new { Name = "Alice", Age = 30 } + }; + + var different = new[] + { + new { Name = "Alice", Age = 31 } + }; + + await Assert.That(actual).IsNotStructurallyEqualTo(different); +} +``` + +## Distinctness + +### HasDistinctItems + +Tests that all items in a collection are unique: + +```csharp +[Test] +public async Task All_Items_Distinct() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers).HasDistinctItems(); +} +``` + +Fails if duplicates exist: + +```csharp +[Test] +public async Task Duplicates_Fail() +{ + var numbers = new[] { 1, 2, 2, 3 }; + + // This will fail + // await Assert.That(numbers).HasDistinctItems(); +} +``` + +## Practical Examples + +### Filtering Results + +```csharp +[Test] +public async Task Filter_And_Assert() +{ + var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + var evens = numbers.Where(n => n % 2 == 0).ToArray(); + + await Assert.That(evens) + .HasCount(5) + .And.All(n => n % 2 == 0); +} +``` + +### LINQ Query Results + +```csharp +[Test] +public async Task LINQ_Query_Results() +{ + var users = new[] + { + new User { Name = "Alice", Age = 25 }, + new User { Name = "Bob", Age = 30 }, + new User { Name = "Charlie", Age = 35 } + }; + + var adults = users.Where(u => u.Age >= 18).ToArray(); + + await Assert.That(adults) + .HasCount(3) + .And.All(u => u.Age >= 18); +} +``` + +### Sorting Validation + +```csharp +[Test] +public async Task Verify_Sorting() +{ + var unsorted = new[] { 5, 2, 8, 1, 9 }; + var sorted = unsorted.OrderBy(x => x).ToArray(); + + await Assert.That(sorted).IsInOrder(); + await Assert.That(sorted).IsEquivalentTo(unsorted); +} +``` + +### API Response Validation + +```csharp +[Test] +public async Task API_Returns_Expected_Items() +{ + var response = await _api.GetUsersAsync(); + + await Assert.That(response) + .IsNotEmpty() + .And.All(u => u.Id > 0) + .And.All(u => !string.IsNullOrEmpty(u.Name)); +} +``` + +### Collection Transformation + +```csharp +[Test] +public async Task Map_And_Verify() +{ + var users = new[] + { + new User { Name = "Alice", Age = 25 }, + new User { Name = "Bob", Age = 30 } + }; + + var names = users.Select(u => u.Name).ToArray(); + + await Assert.That(names) + .HasCount(2) + .And.Contains("Alice") + .And.Contains("Bob") + .And.All(name => !string.IsNullOrEmpty(name)); +} +``` + +## Empty vs Null Collections + +```csharp +[Test] +public async Task Empty_vs_Null() +{ + List? nullList = null; + List emptyList = new(); + List populated = new() { 1, 2, 3 }; + + await Assert.That(nullList).IsNull(); + await Assert.That(emptyList).IsNotNull(); + await Assert.That(emptyList).IsEmpty(); + await Assert.That(populated).IsNotEmpty(); +} +``` + +## Nested Collections + +```csharp +[Test] +public async Task Nested_Collections() +{ + var matrix = new[] + { + new[] { 1, 2, 3 }, + new[] { 4, 5, 6 }, + new[] { 7, 8, 9 } + }; + + await Assert.That(matrix).HasCount(3); + await Assert.That(matrix).All(row => row.Length == 3); + + // Flatten and assert + var flattened = matrix.SelectMany(x => x).ToArray(); + await Assert.That(flattened).HasCount(9); +} +``` + +## Collection of Collections + +```csharp +[Test] +public async Task Collection_Of_Collections() +{ + var groups = new List> + { + new() { 1, 2 }, + new() { 3, 4, 5 }, + new() { 6 } + }; + + await Assert.That(groups) + .HasCount(3) + .And.All(group => group.Count > 0); +} +``` + +## Chaining Collection Assertions + +```csharp +[Test] +public async Task Chained_Collection_Assertions() +{ + var numbers = new[] { 1, 2, 3, 4, 5 }; + + await Assert.That(numbers) + .IsNotEmpty() + .And.HasCount(5) + .And.Contains(3) + .And.DoesNotContain(10) + .And.IsInOrder() + .And.All(n => n > 0) + .And.Any(n => n == 5); +} +``` + +## Performance Considerations + +### Materialize IEnumerable + +```csharp +[Test] +public async Task Materialize_Before_Multiple_Assertions() +{ + // This query is deferred + IEnumerable query = Enumerable.Range(1, 1000000) + .Where(n => n % 2 == 0); + + // Materialize once to avoid re-execution + var materialized = query.ToArray(); + + await Assert.That(materialized).HasCount().GreaterThan(1000); + await Assert.That(materialized).Contains(100); + await Assert.That(materialized).All(n => n % 2 == 0); +} +``` + +## Working with HashSet and SortedSet + +```csharp +[Test] +public async Task HashSet_Assertions() +{ + var set = new HashSet { 1, 2, 3, 4, 5 }; + + await Assert.That(set) + .HasCount(5) + .And.Contains(3) + .And.HasDistinctItems(); +} + +[Test] +public async Task SortedSet_Assertions() +{ + var sorted = new SortedSet { 5, 2, 8, 1, 9 }; + + await Assert.That(sorted) + .IsInOrder() + .And.HasDistinctItems(); +} +``` + +## Common Patterns + +### Validate All Items + +```csharp +[Test] +public async Task Validate_Each_Item() +{ + var users = GetUsers(); + + await using (Assert.Multiple()) + { + foreach (var user in users) + { + await Assert.That(user.Name).IsNotEmpty(); + await Assert.That(user.Age).IsGreaterThan(0); + } + } +} +``` + +Or more elegantly: + +```csharp +[Test] +public async Task Validate_All_With_Assertion() +{ + var users = GetUsers(); + + await Assert.That(users).All(u => + !string.IsNullOrEmpty(u.Name) && u.Age > 0 + ); +} +``` + +### Find and Assert + +```csharp +[Test] +public async Task Find_And_Assert() +{ + var users = GetUsers(); + + var admin = await Assert.That(users) + .Contains(u => u.Role == "Admin"); + + await Assert.That(admin.Permissions).IsNotEmpty(); +} +``` + +## See Also + +- [Dictionaries](dictionaries.md) - Dictionary-specific assertions +- [Strings](string.md) - String collections +- [Equality & Comparison](equality-and-comparison.md) - Item comparison diff --git a/docs/docs/assertions/datetime.md b/docs/docs/assertions/datetime.md new file mode 100644 index 0000000000..accb815d46 --- /dev/null +++ b/docs/docs/assertions/datetime.md @@ -0,0 +1,591 @@ +--- +sidebar_position: 7.5 +--- + +# DateTime and Time Assertions + +TUnit provides comprehensive assertions for date and time types, including `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, and `TimeSpan`, with support for tolerance-based comparisons and specialized checks. + +## DateTime Equality with Tolerance + +DateTime comparisons often need tolerance to account for timing variations: + +```csharp +[Test] +public async Task DateTime_With_Tolerance() +{ + var now = DateTime.Now; + var almostNow = now.AddMilliseconds(50); + + // Without tolerance - might fail + // await Assert.That(almostNow).IsEqualTo(now); + + // With tolerance - passes + await Assert.That(almostNow).IsEqualTo(now, tolerance: TimeSpan.FromSeconds(1)); +} +``` + +### Tolerance Examples + +```csharp +[Test] +public async Task Various_Tolerance_Values() +{ + var baseTime = new DateTime(2024, 1, 15, 10, 30, 0); + + // Millisecond tolerance + var time1 = baseTime.AddMilliseconds(100); + await Assert.That(time1).IsEqualTo(baseTime, tolerance: TimeSpan.FromMilliseconds(500)); + + // Second tolerance + var time2 = baseTime.AddSeconds(5); + await Assert.That(time2).IsEqualTo(baseTime, tolerance: TimeSpan.FromSeconds(10)); + + // Minute tolerance + var time3 = baseTime.AddMinutes(2); + await Assert.That(time3).IsEqualTo(baseTime, tolerance: TimeSpan.FromMinutes(5)); +} +``` + +## DateTime Comparison + +Standard comparison operators work with DateTime: + +```csharp +[Test] +public async Task DateTime_Comparison() +{ + var past = DateTime.Now.AddDays(-1); + var now = DateTime.Now; + var future = DateTime.Now.AddDays(1); + + await Assert.That(now).IsGreaterThan(past); + await Assert.That(now).IsLessThan(future); + await Assert.That(past).IsLessThan(future); +} +``` + +## DateTime-Specific Assertions + +### IsToday / IsNotToday + +```csharp +[Test] +public async Task DateTime_Is_Today() +{ + var today = DateTime.Now; + await Assert.That(today).IsToday(); + + var yesterday = DateTime.Now.AddDays(-1); + await Assert.That(yesterday).IsNotToday(); + + var tomorrow = DateTime.Now.AddDays(1); + await Assert.That(tomorrow).IsNotToday(); +} +``` + +### IsUtc / IsNotUtc + +```csharp +[Test] +public async Task DateTime_Kind() +{ + var utc = DateTime.UtcNow; + await Assert.That(utc).IsUtc(); + + var local = DateTime.Now; + await Assert.That(local).IsNotUtc(); + + var unspecified = new DateTime(2024, 1, 15); + await Assert.That(unspecified).IsNotUtc(); +} +``` + +### IsLeapYear / IsNotLeapYear + +```csharp +[Test] +public async Task Leap_Year_Check() +{ + var leapYear = new DateTime(2024, 1, 1); + await Assert.That(leapYear).IsLeapYear(); + + var nonLeapYear = new DateTime(2023, 1, 1); + await Assert.That(nonLeapYear).IsNotLeapYear(); +} +``` + +### IsInFuture / IsInPast + +Compares against local time: + +```csharp +[Test] +public async Task Future_and_Past() +{ + var future = DateTime.Now.AddHours(1); + await Assert.That(future).IsInFuture(); + + var past = DateTime.Now.AddHours(-1); + await Assert.That(past).IsInPast(); +} +``` + +### IsInFutureUtc / IsInPastUtc + +Compares against UTC time: + +```csharp +[Test] +public async Task Future_and_Past_UTC() +{ + var futureUtc = DateTime.UtcNow.AddHours(1); + await Assert.That(futureUtc).IsInFutureUtc(); + + var pastUtc = DateTime.UtcNow.AddHours(-1); + await Assert.That(pastUtc).IsInPastUtc(); +} +``` + +### IsOnWeekend / IsOnWeekday + +```csharp +[Test] +public async Task Weekend_Check() +{ + var saturday = new DateTime(2024, 1, 6); // Saturday + await Assert.That(saturday).IsOnWeekend(); + + var monday = new DateTime(2024, 1, 8); // Monday + await Assert.That(monday).IsOnWeekday(); + await Assert.That(monday).IsNotOnWeekend(); +} +``` + +### IsDaylightSavingTime / IsNotDaylightSavingTime + +```csharp +[Test] +public async Task Daylight_Saving_Time() +{ + var summer = new DateTime(2024, 7, 1); // Summer in Northern Hemisphere + var winter = new DateTime(2024, 1, 1); // Winter + + // Results depend on timezone + if (TimeZoneInfo.Local.IsDaylightSavingTime(summer)) + { + await Assert.That(summer).IsDaylightSavingTime(); + } +} +``` + +## DateTimeOffset + +DateTimeOffset includes timezone information: + +```csharp +[Test] +public async Task DateTimeOffset_With_Tolerance() +{ + var now = DateTimeOffset.Now; + var almostNow = now.AddSeconds(1); + + await Assert.That(almostNow).IsEqualTo(now, tolerance: TimeSpan.FromSeconds(5)); +} +``` + +```csharp +[Test] +public async Task DateTimeOffset_Comparison() +{ + var earlier = new DateTimeOffset(2024, 1, 1, 12, 0, 0, TimeSpan.FromHours(-8)); + var later = new DateTimeOffset(2024, 1, 1, 12, 0, 0, TimeSpan.FromHours(0)); + + // Same local time, but different UTC times + await Assert.That(later).IsGreaterThan(earlier); +} +``` + +## DateOnly (.NET 6+) + +DateOnly represents just a date without time: + +```csharp +[Test] +public async Task DateOnly_Assertions() +{ + var date1 = new DateOnly(2024, 1, 15); + var date2 = new DateOnly(2024, 1, 15); + + await Assert.That(date1).IsEqualTo(date2); +} +``` + +### DateOnly with Days Tolerance + +```csharp +[Test] +public async Task DateOnly_With_Tolerance() +{ + var date1 = new DateOnly(2024, 1, 15); + var date2 = new DateOnly(2024, 1, 17); + + await Assert.That(date2).IsEqualTo(date1, daysTolerance: 5); +} +``` + +### DateOnly Comparison + +```csharp +[Test] +public async Task DateOnly_Comparison() +{ + var earlier = new DateOnly(2024, 1, 1); + var later = new DateOnly(2024, 12, 31); + + await Assert.That(later).IsGreaterThan(earlier); + await Assert.That(earlier).IsLessThan(later); +} +``` + +## TimeOnly (.NET 6+) + +TimeOnly represents just time without a date: + +```csharp +[Test] +public async Task TimeOnly_Assertions() +{ + var morning = new TimeOnly(9, 30, 0); + var evening = new TimeOnly(17, 45, 0); + + await Assert.That(evening).IsGreaterThan(morning); +} +``` + +### TimeOnly with Tolerance + +```csharp +[Test] +public async Task TimeOnly_With_Tolerance() +{ + var time1 = new TimeOnly(10, 30, 0); + var time2 = new TimeOnly(10, 30, 5); + + await Assert.That(time2).IsEqualTo(time1, tolerance: TimeSpan.FromSeconds(10)); +} +``` + +## TimeSpan + +TimeSpan represents a duration: + +```csharp +[Test] +public async Task TimeSpan_Assertions() +{ + var duration1 = TimeSpan.FromMinutes(30); + var duration2 = TimeSpan.FromMinutes(30); + + await Assert.That(duration1).IsEqualTo(duration2); +} +``` + +### TimeSpan Comparison + +```csharp +[Test] +public async Task TimeSpan_Comparison() +{ + var short_duration = TimeSpan.FromMinutes(5); + var long_duration = TimeSpan.FromHours(1); + + await Assert.That(long_duration).IsGreaterThan(short_duration); + await Assert.That(short_duration).IsLessThan(long_duration); +} +``` + +### TimeSpan Sign Checks + +```csharp +[Test] +public async Task TimeSpan_Sign() +{ + var positive = TimeSpan.FromHours(1); + await Assert.That(positive).IsPositive(); + + var negative = TimeSpan.FromHours(-1); + await Assert.That(negative).IsNegative(); +} +``` + +## Practical Examples + +### Expiration Checks + +```csharp +[Test] +public async Task Check_Token_Expiration() +{ + var token = CreateToken(); + var expiresAt = token.ExpiresAt; + + await Assert.That(expiresAt).IsInFuture(); + + // Or check if expired + var expiredToken = CreateExpiredToken(); + await Assert.That(expiredToken.ExpiresAt).IsInPast(); +} +``` + +### Age Calculation + +```csharp +[Test] +public async Task Calculate_Age() +{ + var birthDate = new DateTime(1990, 1, 1); + var age = DateTime.Now.Year - birthDate.Year; + + if (DateTime.Now.DayOfYear < birthDate.DayOfYear) + { + age--; + } + + await Assert.That(age).IsGreaterThanOrEqualTo(0); + await Assert.That(age).IsLessThan(150); // Reasonable max age +} +``` + +### Business Days + +```csharp +[Test] +public async Task Is_Business_Day() +{ + var monday = new DateTime(2024, 1, 8); + + await Assert.That(monday).IsOnWeekday(); + await Assert.That(monday.DayOfWeek).IsNotEqualTo(DayOfWeek.Saturday); + await Assert.That(monday.DayOfWeek).IsNotEqualTo(DayOfWeek.Sunday); +} +``` + +### Scheduling + +```csharp +[Test] +public async Task Scheduled_Time() +{ + var scheduledTime = new DateTime(2024, 12, 25, 9, 0, 0); + + await Assert.That(scheduledTime.Month).IsEqualTo(12); + await Assert.That(scheduledTime.Day).IsEqualTo(25); + await Assert.That(scheduledTime.Hour).IsEqualTo(9); +} +``` + +### Performance Timing + +```csharp +[Test] +public async Task Operation_Duration() +{ + var start = DateTime.Now; + await PerformOperationAsync(); + var end = DateTime.Now; + + var duration = end - start; + + await Assert.That(duration).IsLessThan(TimeSpan.FromSeconds(5)); + await Assert.That(duration).IsPositive(); +} +``` + +### Date Range Validation + +```csharp +[Test] +public async Task Date_Within_Range() +{ + var startDate = new DateTime(2024, 1, 1); + var endDate = new DateTime(2024, 12, 31); + var checkDate = new DateTime(2024, 6, 15); + + await Assert.That(checkDate).IsGreaterThan(startDate); + await Assert.That(checkDate).IsLessThan(endDate); +} +``` + +### Timestamp Validation + +```csharp +[Test] +public async Task Record_Created_Recently() +{ + var record = await CreateRecordAsync(); + var createdAt = record.CreatedAt; + var now = DateTime.UtcNow; + + // Created within last minute + await Assert.That(createdAt).IsEqualTo(now, tolerance: TimeSpan.FromMinutes(1)); + await Assert.That(createdAt).IsInPastUtc(); +} +``` + +### Time Zone Conversions + +```csharp +[Test] +public async Task Time_Zone_Conversion() +{ + var utcTime = DateTime.UtcNow; + var localTime = utcTime.ToLocalTime(); + + await Assert.That(utcTime).IsUtc(); + await Assert.That(localTime).IsNotUtc(); + + var offset = localTime - utcTime; + await Assert.That(Math.Abs(offset.TotalHours)).IsLessThan(24); +} +``` + +## Working with Date Components + +```csharp +[Test] +public async Task Date_Components() +{ + var date = new DateTime(2024, 7, 15, 14, 30, 45); + + await Assert.That(date.Year).IsEqualTo(2024); + await Assert.That(date.Month).IsEqualTo(7); + await Assert.That(date.Day).IsEqualTo(15); + await Assert.That(date.Hour).IsEqualTo(14); + await Assert.That(date.Minute).IsEqualTo(30); + await Assert.That(date.Second).IsEqualTo(45); +} +``` + +## First and Last Day of Month + +```csharp +[Test] +public async Task First_Day_Of_Month() +{ + var date = new DateTime(2024, 3, 15); + var firstDay = new DateTime(date.Year, date.Month, 1); + + await Assert.That(firstDay.Day).IsEqualTo(1); +} + +[Test] +public async Task Last_Day_Of_Month() +{ + var date = new DateTime(2024, 2, 15); + var daysInMonth = DateTime.DaysInMonth(date.Year, date.Month); + var lastDay = new DateTime(date.Year, date.Month, daysInMonth); + + await Assert.That(lastDay.Day).IsEqualTo(29); // 2024 is a leap year +} +``` + +## Quarter Calculation + +```csharp +[Test] +public async Task Date_Quarter() +{ + var q1 = new DateTime(2024, 2, 1); + var quarter1 = (q1.Month - 1) / 3 + 1; + await Assert.That(quarter1).IsEqualTo(1); + + var q3 = new DateTime(2024, 8, 1); + var quarter3 = (q3.Month - 1) / 3 + 1; + await Assert.That(quarter3).IsEqualTo(3); +} +``` + +## DayOfWeek Assertions + +DayOfWeek has its own assertions: + +```csharp +[Test] +public async Task Day_Of_Week_Checks() +{ + var dayOfWeek = DateTime.Now.DayOfWeek; + + if (dayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday) + { + await Assert.That(dayOfWeek).IsWeekend(); + } + else + { + await Assert.That(dayOfWeek).IsWeekday(); + } +} +``` + +## Chaining DateTime Assertions + +```csharp +[Test] +public async Task Chained_DateTime_Assertions() +{ + var date = DateTime.Now; + + await Assert.That(date) + .IsToday() + .And.IsGreaterThan(DateTime.MinValue) + .And.IsLessThan(DateTime.MaxValue); +} +``` + +## Common Patterns + +### Birthday Validation + +```csharp +[Test] +public async Task Validate_Birthday() +{ + var birthday = new DateTime(1990, 5, 15); + + await Assert.That(birthday).IsInPast(); + await Assert.That(birthday).IsGreaterThan(new DateTime(1900, 1, 1)); +} +``` + +### Meeting Scheduler + +```csharp +[Test] +public async Task Schedule_Meeting() +{ + var meetingTime = new DateTime(2024, 1, 15, 14, 0, 0); + + await Assert.That(meetingTime).IsInFuture(); + await Assert.That(meetingTime).IsOnWeekday(); + await Assert.That(meetingTime.Hour).IsBetween(9, 17); // Business hours +} +``` + +### Relative Time Checks + +```csharp +[Test] +public async Task Within_Last_Hour() +{ + var timestamp = DateTime.Now.AddMinutes(-30); + var hourAgo = DateTime.Now.AddHours(-1); + + await Assert.That(timestamp).IsGreaterThan(hourAgo); +} +``` + +## See Also + +- [Equality & Comparison](equality-and-comparison.md) - General comparison with tolerance +- [Numeric Assertions](numeric.md) - Numeric components of dates +- [Specialized Types](specialized-types.md) - Other time-related types diff --git a/docs/docs/assertions/dictionaries.md b/docs/docs/assertions/dictionaries.md new file mode 100644 index 0000000000..938a723f6e --- /dev/null +++ b/docs/docs/assertions/dictionaries.md @@ -0,0 +1,547 @@ +--- +sidebar_position: 6.8 +--- + +# Dictionary Assertions + +TUnit provides specialized assertions for testing dictionaries (`IReadOnlyDictionary`), including key and value membership checks. Dictionaries also inherit all collection assertions. + +## Key Assertions + +### ContainsKey + +Tests that a dictionary contains a specific key: + +```csharp +[Test] +public async Task Dictionary_Contains_Key() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2, + ["cherry"] = 3 + }; + + await Assert.That(dict).ContainsKey("apple"); + await Assert.That(dict).ContainsKey("banana"); +} +``` + +#### With Custom Comparer + +```csharp +[Test] +public async Task Contains_Key_With_Comparer() +{ + var dict = new Dictionary + { + ["Apple"] = 1, + ["Banana"] = 2 + }; + + await Assert.That(dict) + .ContainsKey("apple") + .Using(StringComparer.OrdinalIgnoreCase); +} +``` + +### DoesNotContainKey + +Tests that a dictionary does not contain a specific key: + +```csharp +[Test] +public async Task Dictionary_Does_Not_Contain_Key() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2 + }; + + await Assert.That(dict).DoesNotContainKey("cherry"); + await Assert.That(dict).DoesNotContainKey("orange"); +} +``` + +## Value Assertions + +### ContainsValue + +Tests that a dictionary contains a specific value: + +```csharp +[Test] +public async Task Dictionary_Contains_Value() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2, + ["cherry"] = 3 + }; + + await Assert.That(dict).ContainsValue(2); + await Assert.That(dict).ContainsValue(3); +} +``` + +## Collection Assertions on Dictionaries + +Dictionaries inherit all collection assertions since they implement `IEnumerable>`: + +### Count + +```csharp +[Test] +public async Task Dictionary_Count() +{ + var dict = new Dictionary + { + ["a"] = 1, + ["b"] = 2, + ["c"] = 3 + }; + + await Assert.That(dict).HasCount(3); +} +``` + +### IsEmpty / IsNotEmpty + +```csharp +[Test] +public async Task Dictionary_Empty() +{ + var empty = new Dictionary(); + var populated = new Dictionary { ["key"] = 1 }; + + await Assert.That(empty).IsEmpty(); + await Assert.That(populated).IsNotEmpty(); +} +``` + +### Contains (KeyValuePair) + +```csharp +[Test] +public async Task Dictionary_Contains_Pair() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2 + }; + + await Assert.That(dict).Contains(new KeyValuePair("apple", 1)); +} +``` + +### All Pairs Match Condition + +```csharp +[Test] +public async Task All_Values_Positive() +{ + var dict = new Dictionary + { + ["a"] = 1, + ["b"] = 2, + ["c"] = 3 + }; + + await Assert.That(dict).All(kvp => kvp.Value > 0); +} +``` + +### Any Pair Matches Condition + +```csharp +[Test] +public async Task Any_Key_Starts_With() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2, + ["cherry"] = 3 + }; + + await Assert.That(dict).Any(kvp => kvp.Key.StartsWith("b")); +} +``` + +## Practical Examples + +### Configuration Validation + +```csharp +[Test] +public async Task Configuration_Has_Required_Keys() +{ + var config = LoadConfiguration(); + + await using (Assert.Multiple()) + { + await Assert.That(config).ContainsKey("DatabaseConnection"); + await Assert.That(config).ContainsKey("ApiKey"); + await Assert.That(config).ContainsKey("Environment"); + } +} +``` + +### HTTP Headers Validation + +```csharp +[Test] +public async Task Response_Headers() +{ + var headers = new Dictionary + { + ["Content-Type"] = "application/json", + ["Cache-Control"] = "no-cache" + }; + + await Assert.That(headers) + .ContainsKey("Content-Type") + .And.ContainsValue("application/json"); +} +``` + +### Lookup Table Validation + +```csharp +[Test] +public async Task Lookup_Table() +{ + var statusCodes = new Dictionary + { + [200] = "OK", + [404] = "Not Found", + [500] = "Internal Server Error" + }; + + await Assert.That(statusCodes) + .HasCount(3) + .And.ContainsKey(200) + .And.ContainsValue("OK"); +} +``` + +### Cache Validation + +```csharp +[Test] +public async Task Cache_Contains_Entry() +{ + var cache = new Dictionary + { + ["user:123"] = new User { Id = 123 }, + ["user:456"] = new User { Id = 456 } + }; + + await Assert.That(cache) + .ContainsKey("user:123") + .And.HasCount(2) + .And.IsNotEmpty(); +} +``` + +## Dictionary Key/Value Operations + +### Accessing Values After Key Check + +```csharp +[Test] +public async Task Get_Value_After_Key_Check() +{ + var dict = new Dictionary + { + ["alice"] = new User { Name = "Alice", Age = 30 } + }; + + // First verify key exists + await Assert.That(dict).ContainsKey("alice"); + + // Then safely access + var user = dict["alice"]; + await Assert.That(user.Age).IsEqualTo(30); +} +``` + +### TryGetValue Pattern + +```csharp +[Test] +public async Task TryGetValue_Pattern() +{ + var dict = new Dictionary + { + ["count"] = 42 + }; + + var found = dict.TryGetValue("count", out var value); + + await Assert.That(found).IsTrue(); + await Assert.That(value).IsEqualTo(42); +} +``` + +## Working with Dictionary Keys and Values + +### Keys Collection + +```csharp +[Test] +public async Task Dictionary_Keys() +{ + var dict = new Dictionary + { + ["a"] = 1, + ["b"] = 2, + ["c"] = 3 + }; + + var keys = dict.Keys; + + await Assert.That(keys) + .HasCount(3) + .And.Contains("a") + .And.Contains("b") + .And.Contains("c"); +} +``` + +### Values Collection + +```csharp +[Test] +public async Task Dictionary_Values() +{ + var dict = new Dictionary + { + ["a"] = 1, + ["b"] = 2, + ["c"] = 3 + }; + + var values = dict.Values; + + await Assert.That(values) + .HasCount(3) + .And.Contains(1) + .And.Contains(2) + .And.All(v => v > 0); +} +``` + +## Equivalency Checks + +### Same Key-Value Pairs + +```csharp +[Test] +public async Task Dictionaries_Are_Equivalent() +{ + var dict1 = new Dictionary + { + ["a"] = 1, + ["b"] = 2 + }; + + var dict2 = new Dictionary + { + ["b"] = 2, + ["a"] = 1 + }; + + // Dictionaries are equivalent (same pairs, order doesn't matter) + await Assert.That(dict1).IsEquivalentTo(dict2); +} +``` + +## Chaining Dictionary Assertions + +```csharp +[Test] +public async Task Chained_Dictionary_Assertions() +{ + var dict = new Dictionary + { + ["apple"] = 1, + ["banana"] = 2, + ["cherry"] = 3 + }; + + await Assert.That(dict) + .IsNotEmpty() + .And.HasCount(3) + .And.ContainsKey("apple") + .And.ContainsKey("banana") + .And.ContainsValue(2) + .And.All(kvp => kvp.Value > 0); +} +``` + +## Specialized Dictionary Types + +### ConcurrentDictionary + +```csharp +[Test] +public async Task Concurrent_Dictionary() +{ + var concurrent = new ConcurrentDictionary(); + concurrent.TryAdd("a", 1); + concurrent.TryAdd("b", 2); + + await Assert.That(concurrent) + .HasCount(2) + .And.ContainsKey("a"); +} +``` + +### ReadOnlyDictionary + +```csharp +[Test] +public async Task ReadOnly_Dictionary() +{ + var dict = new Dictionary { ["a"] = 1 }; + var readOnly = new ReadOnlyDictionary(dict); + + await Assert.That(readOnly) + .HasCount(1) + .And.ContainsKey("a"); +} +``` + +### SortedDictionary + +```csharp +[Test] +public async Task Sorted_Dictionary() +{ + var sorted = new SortedDictionary + { + [3] = "three", + [1] = "one", + [2] = "two" + }; + + var keys = sorted.Keys.ToArray(); + + await Assert.That(keys).IsInOrder(); +} +``` + +## Null Checks + +### Null Dictionary + +```csharp +[Test] +public async Task Null_Dictionary() +{ + Dictionary? dict = null; + + await Assert.That(dict).IsNull(); +} +``` + +### Empty vs Null + +```csharp +[Test] +public async Task Empty_vs_Null_Dictionary() +{ + Dictionary? nullDict = null; + var emptyDict = new Dictionary(); + + await Assert.That(nullDict).IsNull(); + await Assert.That(emptyDict).IsNotNull(); + await Assert.That(emptyDict).IsEmpty(); +} +``` + +## Common Patterns + +### Required Configuration Keys + +```csharp +[Test] +public async Task All_Required_Keys_Present() +{ + var config = LoadConfiguration(); + var requiredKeys = new[] { "ApiKey", "Database", "Environment" }; + + foreach (var key in requiredKeys) + { + await Assert.That(config).ContainsKey(key); + } +} +``` + +Or with `Assert.Multiple`: + +```csharp +[Test] +public async Task All_Required_Keys_Present_Multiple() +{ + var config = LoadConfiguration(); + var requiredKeys = new[] { "ApiKey", "Database", "Environment" }; + + await using (Assert.Multiple()) + { + foreach (var key in requiredKeys) + { + await Assert.That(config).ContainsKey(key); + } + } +} +``` + +### Metadata Validation + +```csharp +[Test] +public async Task Validate_Metadata() +{ + var metadata = GetFileMetadata(); + + await Assert.That(metadata) + .ContainsKey("ContentType") + .And.ContainsKey("Size") + .And.ContainsKey("LastModified") + .And.All(kvp => kvp.Value != null); +} +``` + +### Feature Flags + +```csharp +[Test] +public async Task Feature_Flags() +{ + var features = new Dictionary + { + ["NewUI"] = true, + ["BetaFeature"] = false, + ["ExperimentalApi"] = true + }; + + await Assert.That(features) + .ContainsKey("NewUI") + .And.ContainsValue(true); + + var newUiEnabled = features["NewUI"]; + await Assert.That(newUiEnabled).IsTrue(); +} +``` + +## See Also + +- [Collections](collections.md) - General collection assertions +- [Equality & Comparison](equality-and-comparison.md) - Comparing dictionary values +- [Strings](string.md) - String key comparisons diff --git a/docs/docs/assertions/equality-and-comparison.md b/docs/docs/assertions/equality-and-comparison.md new file mode 100644 index 0000000000..78920a4624 --- /dev/null +++ b/docs/docs/assertions/equality-and-comparison.md @@ -0,0 +1,500 @@ +--- +sidebar_position: 2 +--- + +# Equality and Comparison Assertions + +TUnit provides comprehensive assertions for testing equality and comparing values. These assertions work with any type that implements the appropriate comparison interfaces. + +## Basic Equality + +### IsEqualTo + +Tests that two values are equal using the type's `Equals()` method or `==` operator: + +```csharp +[Test] +public async Task Basic_Equality() +{ + var result = 5 + 5; + await Assert.That(result).IsEqualTo(10); + + var name = "Alice"; + await Assert.That(name).IsEqualTo("Alice"); + + var isValid = true; + await Assert.That(isValid).IsEqualTo(true); +} +``` + +### IsNotEqualTo + +Tests that two values are not equal: + +```csharp +[Test] +public async Task Not_Equal() +{ + var actual = CalculateResult(); + await Assert.That(actual).IsNotEqualTo(0); + + var username = GetUsername(); + await Assert.That(username).IsNotEqualTo("admin"); +} +``` + +### EqualTo (Alias) + +`EqualTo()` is an alias for `IsEqualTo()` for more natural chaining: + +```csharp +[Test] +public async Task Using_EqualTo_Alias() +{ + var numbers = new[] { 1, 2, 3 }; + + await Assert.That(numbers) + .HasCount().EqualTo(3) + .And.Contains(2); +} +``` + +## Reference Equality + +### IsSameReferenceAs + +Tests that two references point to the exact same object instance: + +```csharp +[Test] +public async Task Same_Reference() +{ + var original = new Person { Name = "Alice" }; + var reference = original; + + await Assert.That(reference).IsSameReferenceAs(original); +} +``` + +### IsNotSameReferenceAs + +Tests that two references point to different object instances: + +```csharp +[Test] +public async Task Different_References() +{ + var person1 = new Person { Name = "Alice" }; + var person2 = new Person { Name = "Alice" }; + + // Same values, different instances + await Assert.That(person1).IsNotSameReferenceAs(person2); + await Assert.That(person1).IsEqualTo(person2); // If equality is overridden +} +``` + +## Comparison Assertions + +All comparison assertions work with types that implement `IComparable` or `IComparable`. + +### IsGreaterThan + +```csharp +[Test] +public async Task Greater_Than() +{ + var score = 85; + await Assert.That(score).IsGreaterThan(70); + + var temperature = 25.5; + await Assert.That(temperature).IsGreaterThan(20.0); + + var date = DateTime.Now; + await Assert.That(date).IsGreaterThan(DateTime.Now.AddDays(-1)); +} +``` + +### IsGreaterThanOrEqualTo + +```csharp +[Test] +public async Task Greater_Than_Or_Equal() +{ + var passingGrade = 60; + await Assert.That(passingGrade).IsGreaterThanOrEqualTo(60); + + var age = 18; + await Assert.That(age).IsGreaterThanOrEqualTo(18); // Exactly 18 passes +} +``` + +### IsLessThan + +```csharp +[Test] +public async Task Less_Than() +{ + var response_time = 150; // milliseconds + await Assert.That(response_time).IsLessThan(200); + + var price = 49.99m; + await Assert.That(price).IsLessThan(50.00m); +} +``` + +### IsLessThanOrEqualTo + +```csharp +[Test] +public async Task Less_Than_Or_Equal() +{ + var maxRetries = 3; + var actualRetries = 3; + await Assert.That(actualRetries).IsLessThanOrEqualTo(maxRetries); +} +``` + +## Range Assertions + +### IsBetween + +Tests that a value falls within a range (inclusive): + +```csharp +[Test] +public async Task Between_Values() +{ + var percentage = 75; + await Assert.That(percentage).IsBetween(0, 100); + + var temperature = 22.5; + await Assert.That(temperature).IsBetween(20.0, 25.0); + + var age = 30; + await Assert.That(age).IsBetween(18, 65); +} +``` + +Boundary values are included: + +```csharp +[Test] +public async Task Between_Includes_Boundaries() +{ + await Assert.That(0).IsBetween(0, 10); // ✅ Passes + await Assert.That(10).IsBetween(0, 10); // ✅ Passes + await Assert.That(5).IsBetween(0, 10); // ✅ Passes +} +``` + +## Numeric-Specific Assertions + +### IsPositive + +Tests that a numeric value is greater than zero: + +```csharp +[Test] +public async Task Positive_Numbers() +{ + var profit = 1500.50m; + await Assert.That(profit).IsPositive(); + + var count = 5; + await Assert.That(count).IsPositive(); + + // Works with all numeric types + await Assert.That(1.5).IsPositive(); // double + await Assert.That(1.5f).IsPositive(); // float + await Assert.That(1.5m).IsPositive(); // decimal + await Assert.That((byte)1).IsPositive(); // byte + await Assert.That((short)1).IsPositive(); // short + await Assert.That(1L).IsPositive(); // long +} +``` + +### IsNegative + +Tests that a numeric value is less than zero: + +```csharp +[Test] +public async Task Negative_Numbers() +{ + var loss = -500.25m; + await Assert.That(loss).IsNegative(); + + var temperature = -5; + await Assert.That(temperature).IsNegative(); +} +``` + +## Tolerance for Floating-Point Numbers + +When comparing floating-point numbers, you can specify a tolerance to account for rounding errors: + +### Double Tolerance + +```csharp +[Test] +public async Task Double_With_Tolerance() +{ + var actual = 1.0 / 3.0; // 0.333333... + var expected = 0.333; + + // Without tolerance - might fail due to precision + // await Assert.That(actual).IsEqualTo(expected); + + // With tolerance - passes + await Assert.That(actual).IsEqualTo(expected, tolerance: 0.001); +} +``` + +### Float Tolerance + +```csharp +[Test] +public async Task Float_With_Tolerance() +{ + float actual = 3.14159f; + float expected = 3.14f; + + await Assert.That(actual).IsEqualTo(expected, tolerance: 0.01f); +} +``` + +### Decimal Tolerance + +```csharp +[Test] +public async Task Decimal_With_Tolerance() +{ + decimal price = 19.995m; + decimal expected = 20.00m; + + await Assert.That(price).IsEqualTo(expected, tolerance: 0.01m); +} +``` + +### Long Tolerance + +```csharp +[Test] +public async Task Long_With_Tolerance() +{ + long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + long expected = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + // Allow 100ms difference + await Assert.That(timestamp).IsEqualTo(expected, tolerance: 100L); +} +``` + +## Chaining Comparisons + +Combine multiple comparison assertions: + +```csharp +[Test] +public async Task Chained_Comparisons() +{ + var score = 85; + + await Assert.That(score) + .IsGreaterThan(0) + .And.IsLessThan(100) + .And.IsGreaterThanOrEqualTo(80); +} +``` + +Or use `IsBetween` for simpler range checks: + +```csharp +[Test] +public async Task Range_Check_Simplified() +{ + var score = 85; + + // Instead of chaining IsGreaterThan and IsLessThan: + await Assert.That(score).IsBetween(0, 100); +} +``` + +## Custom Equality Comparers + +You can provide custom equality comparers for collections and complex types: + +```csharp +[Test] +public async Task Custom_Comparer() +{ + var people1 = new[] { new Person("Alice"), new Person("Bob") }; + var people2 = new[] { new Person("ALICE"), new Person("BOB") }; + + // Case-insensitive name comparison + var comparer = new PersonNameComparer(); + + await Assert.That(people1) + .IsEquivalentTo(people2) + .Using(comparer); +} + +public class PersonNameComparer : IEqualityComparer +{ + public bool Equals(Person? x, Person? y) => + string.Equals(x?.Name, y?.Name, StringComparison.OrdinalIgnoreCase); + + public int GetHashCode(Person obj) => + obj.Name?.ToLowerInvariant().GetHashCode() ?? 0; +} +``` + +Or use a predicate: + +```csharp +[Test] +public async Task Custom_Equality_Predicate() +{ + var people1 = new[] { new Person("Alice"), new Person("Bob") }; + var people2 = new[] { new Person("ALICE"), new Person("BOB") }; + + await Assert.That(people1) + .IsEquivalentTo(people2) + .Using((p1, p2) => string.Equals(p1.Name, p2.Name, + StringComparison.OrdinalIgnoreCase)); +} +``` + +## Working with Value Types and Records + +Equality works naturally with value types and records: + +```csharp +public record Point(int X, int Y); + +[Test] +public async Task Record_Equality() +{ + var point1 = new Point(10, 20); + var point2 = new Point(10, 20); + + // Records have built-in value equality + await Assert.That(point1).IsEqualTo(point2); + await Assert.That(point1).IsNotSameReferenceAs(point2); +} +``` + +```csharp +public struct Coordinate +{ + public double Latitude { get; init; } + public double Longitude { get; init; } +} + +[Test] +public async Task Struct_Equality() +{ + var coord1 = new Coordinate { Latitude = 47.6, Longitude = -122.3 }; + var coord2 = new Coordinate { Latitude = 47.6, Longitude = -122.3 }; + + await Assert.That(coord1).IsEqualTo(coord2); +} +``` + +## Practical Examples + +### Validating Calculation Results + +```csharp +[Test] +public async Task Calculate_Discount() +{ + var originalPrice = 100m; + var discount = 0.20m; // 20% + + var finalPrice = originalPrice * (1 - discount); + + await Assert.That(finalPrice).IsEqualTo(80m); + await Assert.That(finalPrice).IsLessThan(originalPrice); + await Assert.That(finalPrice).IsGreaterThan(0); +} +``` + +### Validating Ranges + +```csharp +[Test] +public async Task Temperature_In_Valid_Range() +{ + var roomTemperature = GetRoomTemperature(); + + await Assert.That(roomTemperature) + .IsBetween(18, 26) // Comfortable range in Celsius + .And.IsPositive(); +} +``` + +### Comparing with Mathematical Constants + +```csharp +[Test] +public async Task Mathematical_Constants() +{ + var calculatedPi = CalculatePiUsingLeibniz(10000); + + await Assert.That(calculatedPi).IsEqualTo(Math.PI, tolerance: 0.0001); +} +``` + +### API Response Validation + +```csharp +[Test] +public async Task API_Response_Time() +{ + var stopwatch = Stopwatch.StartNew(); + await CallApiEndpoint(); + stopwatch.Stop(); + + await Assert.That(stopwatch.ElapsedMilliseconds) + .IsLessThan(500) // Must respond within 500ms + .And.IsGreaterThan(0); +} +``` + +## Common Patterns + +### Validating User Input + +```csharp +[Test] +public async Task Username_Length() +{ + var username = GetUserInput(); + + await Assert.That(username.Length) + .IsBetween(3, 20) + .And.IsGreaterThan(0); +} +``` + +### Percentage Validation + +```csharp +[Test] +public async Task Percentage_Valid() +{ + var successRate = CalculateSuccessRate(); + + await Assert.That(successRate) + .IsBetween(0, 100) + .And.IsGreaterThanOrEqualTo(0); +} +``` + +## See Also + +- [Numeric Assertions](numeric.md) - Additional numeric-specific assertions +- [DateTime Assertions](datetime.md) - Time-based comparisons with tolerance +- [Collections](collections.md) - Comparing collections +- [Strings](string.md) - String equality with options diff --git a/docs/docs/assertions/exceptions.md b/docs/docs/assertions/exceptions.md new file mode 100644 index 0000000000..5eb03251c5 --- /dev/null +++ b/docs/docs/assertions/exceptions.md @@ -0,0 +1,625 @@ +--- +sidebar_position: 8 +--- + +# Exception Assertions + +TUnit provides comprehensive assertions for testing that code throws (or doesn't throw) exceptions, with rich support for validating exception types, messages, and properties. + +## Basic Exception Assertions + +### Throws<TException> + +Tests that a delegate throws a specific exception type (or a subclass): + +```csharp +[Test] +public async Task Code_Throws_Exception() +{ + await Assert.That(() => int.Parse("not a number")) + .Throws(); +} +``` + +Works with any exception type: + +```csharp +[Test] +public async Task Various_Exception_Types() +{ + await Assert.That(() => throw new InvalidOperationException()) + .Throws(); + + await Assert.That(() => throw new ArgumentNullException()) + .Throws(); + + await Assert.That(() => File.ReadAllText("nonexistent.txt")) + .Throws(); +} +``` + +### ThrowsExactly<TException> + +Tests that a delegate throws the exact exception type (not a subclass): + +```csharp +[Test] +public async Task Throws_Exact_Type() +{ + await Assert.That(() => throw new ArgumentNullException()) + .ThrowsExactly(); + + // This would fail - ArgumentNullException is a subclass of ArgumentException + // await Assert.That(() => throw new ArgumentNullException()) + // .ThrowsExactly(); +} +``` + +### Throws (Runtime Type) + +Use when the exception type is only known at runtime: + +```csharp +[Test] +public async Task Throws_Runtime_Type() +{ + Type exceptionType = typeof(InvalidOperationException); + + await Assert.That(() => throw new InvalidOperationException()) + .Throws(exceptionType); +} +``` + +### ThrowsNothing + +Tests that code does not throw any exception: + +```csharp +[Test] +public async Task Code_Does_Not_Throw() +{ + await Assert.That(() => int.Parse("42")) + .ThrowsNothing(); + + await Assert.That(() => ValidateInput("valid")) + .ThrowsNothing(); +} +``` + +## Async Exception Assertions + +For async operations, use async delegates: + +```csharp +[Test] +public async Task Async_Throws_Exception() +{ + await Assert.That(async () => await FailingOperationAsync()) + .Throws(); +} +``` + +```csharp +[Test] +public async Task Async_Does_Not_Throw() +{ + await Assert.That(async () => await SuccessfulOperationAsync()) + .ThrowsNothing(); +} +``` + +## Exception Message Assertions + +### WithMessage + +Tests that the exception has an exact message: + +```csharp +[Test] +public async Task Exception_With_Exact_Message() +{ + await Assert.That(() => throw new InvalidOperationException("Operation failed")) + .Throws() + .WithMessage("Operation failed"); +} +``` + +### WithMessageContaining + +Tests that the exception message contains a substring: + +```csharp +[Test] +public async Task Exception_Message_Contains() +{ + await Assert.That(() => throw new ArgumentException("The parameter 'userId' is invalid")) + .Throws() + .WithMessageContaining("userId"); +} +``` + +#### Case-Insensitive + +```csharp +[Test] +public async Task Message_Contains_Ignoring_Case() +{ + await Assert.That(() => throw new Exception("ERROR: Failed")) + .Throws() + .WithMessageContaining("error") + .IgnoringCase(); +} +``` + +### WithMessageNotContaining + +Tests that the exception message does not contain a substring: + +```csharp +[Test] +public async Task Message_Does_Not_Contain() +{ + await Assert.That(() => throw new Exception("User error")) + .Throws() + .WithMessageNotContaining("system"); +} +``` + +### WithMessageMatching + +Tests that the exception message matches a pattern: + +```csharp +[Test] +public async Task Message_Matches_Pattern() +{ + await Assert.That(() => throw new Exception("Error code: 12345")) + .Throws() + .WithMessageMatching("Error code: *"); +} +``` + +Or with a `StringMatcher`: + +```csharp +[Test] +public async Task Message_Matches_With_Matcher() +{ + var matcher = new StringMatcher("Error * occurred", caseSensitive: false); + + await Assert.That(() => throw new Exception("Error 500 occurred")) + .Throws() + .WithMessageMatching(matcher); +} +``` + +## ArgumentException Specific + +### WithParameterName + +For `ArgumentException` and its subclasses, you can assert on the parameter name: + +```csharp +[Test] +public async Task ArgumentException_With_Parameter_Name() +{ + await Assert.That(() => ValidateUser(null!)) + .Throws() + .WithParameterName("user"); +} + +void ValidateUser(User user) +{ + if (user == null) + throw new ArgumentNullException(nameof(user)); +} +``` + +Combine with message assertions: + +```csharp +[Test] +public async Task ArgumentException_Parameter_And_Message() +{ + await Assert.That(() => SetAge(-1)) + .Throws() + .WithParameterName("age") + .WithMessageContaining("must be positive"); +} + +void SetAge(int age) +{ + if (age < 0) + throw new ArgumentOutOfRangeException(nameof(age), "Age must be positive"); +} +``` + +## Inner Exception Assertions + +### WithInnerException + +Assert on the inner exception: + +```csharp +[Test] +public async Task Exception_With_Inner_Exception() +{ + await Assert.That(() => { + try + { + int.Parse("not a number"); + } + catch (Exception ex) + { + throw new InvalidOperationException("Processing failed", ex); + } + }) + .Throws() + .WithInnerException(); +} +``` + +Chain to assert on the inner exception type: + +```csharp +[Test] +public async Task Inner_Exception_Type() +{ + await Assert.That(() => ThrowWithInner()) + .Throws() + .WithInnerException() + .Throws(); +} + +void ThrowWithInner() +{ + try + { + int.Parse("abc"); + } + catch (Exception ex) + { + throw new InvalidOperationException("Outer", ex); + } +} +``` + +## Practical Examples + +### Validation Exceptions + +```csharp +[Test] +public async Task Validate_Email_Throws() +{ + await Assert.That(() => ValidateEmail("invalid-email")) + .Throws() + .WithParameterName("email") + .WithMessageContaining("valid email"); +} +``` + +### Null Argument Checks + +```csharp +[Test] +public async Task Null_Argument_Throws() +{ + await Assert.That(() => ProcessData(null!)) + .Throws() + .WithParameterName("data"); +} +``` + +### File Operations + +```csharp +[Test] +public async Task File_Not_Found() +{ + await Assert.That(() => File.ReadAllText("nonexistent.txt")) + .Throws() + .WithMessageContaining("nonexistent.txt"); +} +``` + +### Network Operations + +```csharp +[Test] +public async Task HTTP_Request_Fails() +{ + await Assert.That(async () => await _client.GetAsync("http://invalid-url")) + .Throws(); +} +``` + +### Database Operations + +```csharp +[Test] +public async Task Duplicate_Key_Violation() +{ + await Assert.That(async () => await InsertDuplicateAsync()) + .Throws() + .WithMessageContaining("duplicate key"); +} +``` + +### Division by Zero + +```csharp +[Test] +public async Task Division_By_Zero() +{ + await Assert.That(() => { + int a = 10; + int b = 0; + return a / b; + }) + .Throws(); +} +``` + +### Index Out of Range + +```csharp +[Test] +public async Task Array_Index_Out_Of_Range() +{ + var array = new[] { 1, 2, 3 }; + + await Assert.That(() => array[10]) + .Throws(); +} +``` + +### Invalid Cast + +```csharp +[Test] +public async Task Invalid_Cast() +{ + object obj = "string"; + + await Assert.That(() => (int)obj) + .Throws(); +} +``` + +### Custom Exceptions + +```csharp +public class BusinessRuleException : Exception +{ + public string RuleCode { get; } + + public BusinessRuleException(string ruleCode, string message) + : base(message) + { + RuleCode = ruleCode; + } +} + +[Test] +public async Task Custom_Exception_With_Properties() +{ + var exception = await Assert.That(() => + throw new BusinessRuleException("BR001", "Business rule violated")) + .Throws(); + + // Can't directly assert on exception properties yet, but you can access them + await Assert.That(exception.RuleCode).IsEqualTo("BR001"); + await Assert.That(exception.Message).Contains("Business rule"); +} +``` + +## Testing Multiple Operations + +### Using Assert.Multiple + +```csharp +[Test] +public async Task Multiple_Exception_Scenarios() +{ + await using (Assert.Multiple()) + { + await Assert.That(() => int.Parse("abc")) + .Throws(); + + await Assert.That(() => int.Parse("999999999999999999999")) + .Throws(); + + await Assert.That(() => int.Parse("42")) + .ThrowsNothing(); + } +} +``` + +## Exception Inheritance + +When using `Throws()`, subclasses are accepted: + +```csharp +[Test] +public async Task Exception_Inheritance() +{ + // ArgumentNullException inherits from ArgumentException + await Assert.That(() => throw new ArgumentNullException()) + .Throws(); // ✅ Passes + + await Assert.That(() => throw new ArgumentNullException()) + .Throws(); // ✅ Also passes +} +``` + +Use `ThrowsExactly()` if you need the exact type: + +```csharp +[Test] +public async Task Exact_Exception_Type() +{ + // This fails - ArgumentNullException is not exactly ArgumentException + // await Assert.That(() => throw new ArgumentNullException()) + // .ThrowsExactly(); + + await Assert.That(() => throw new ArgumentException()) + .ThrowsExactly(); // ✅ Passes +} +``` + +## Aggregate Exceptions + +```csharp +[Test] +public async Task Aggregate_Exception() +{ + await Assert.That(() => { + var task1 = Task.Run(() => throw new InvalidOperationException()); + var task2 = Task.Run(() => throw new ArgumentException()); + Task.WaitAll(task1, task2); + }) + .Throws(); +} +``` + +## Chaining Exception Assertions + +```csharp +[Test] +public async Task Chained_Exception_Assertions() +{ + await Assert.That(() => ValidateInput("")) + .Throws() + .WithParameterName("input") + .WithMessageContaining("cannot be empty") + .WithMessageNotContaining("null"); +} +``` + +## Testing that No Exception is Thrown + +### ThrowsNothing vs Try-Catch + +```csharp +[Test] +public async Task Explicit_No_Exception() +{ + // Using ThrowsNothing + await Assert.That(() => SafeOperation()) + .ThrowsNothing(); + + // Alternative: just call it + SafeOperation(); // If it throws, the test fails +} +``` + +## Common Patterns + +### Expected Failures + +```csharp +[Test] +public async Task Expected_Validation_Failure() +{ + var invalidUser = new User { Age = -1 }; + + await Assert.That(() => ValidateUser(invalidUser)) + .Throws() + .WithMessageContaining("Age"); +} +``` + +### Defensive Programming + +```csharp +[Test] +public async Task Guard_Clause_Validation() +{ + await Assert.That(() => new Service(null!)) + .Throws() + .WithParameterName("dependency"); +} +``` + +### State Validation + +```csharp +[Test] +public async Task Invalid_State_Operation() +{ + var connection = new Connection(); + // Don't connect + + await Assert.That(() => connection.SendData("test")) + .Throws() + .WithMessageContaining("not connected"); +} +``` + +### Configuration Errors + +```csharp +[Test] +public async Task Missing_Configuration() +{ + await Assert.That(() => LoadConfiguration("invalid.json")) + .Throws() + .WithMessageContaining("invalid.json"); +} +``` + +## Timeout Exceptions + +```csharp +[Test] +public async Task Operation_Timeout() +{ + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + await Assert.That(async () => await LongRunningOperationAsync(cts.Token)) + .Throws(); +} +``` + +## Re-throwing Exceptions + +```csharp +[Test] +public async Task Wrapper_Exception() +{ + await Assert.That(() => { + try + { + RiskyOperation(); + } + catch (Exception ex) + { + throw new ApplicationException("Operation failed", ex); + } + }) + .Throws() + .WithInnerException(); +} +``` + +## Exception Assertions with Async/Await + +```csharp +[Test] +public async Task Async_Exception_Handling() +{ + await Assert.That(async () => { + await Task.Delay(10); + throw new InvalidOperationException("Async failure"); + }) + .Throws() + .WithMessageContaining("Async failure"); +} +``` + +## See Also + +- [Tasks & Async](tasks-and-async.md) - Testing async operations and task state +- [Types](types.md) - Type checking for exception types +- [Strings](string.md) - String assertions for exception messages diff --git a/docs/docs/assertions/extensibility/source-generator-assertions.md b/docs/docs/assertions/extensibility/source-generator-assertions.md index b9c32853a4..dd907f9c21 100644 --- a/docs/docs/assertions/extensibility/source-generator-assertions.md +++ b/docs/docs/assertions/extensibility/source-generator-assertions.md @@ -382,24 +382,6 @@ await Assert.That(number) --- -## Migration from CreateAssertion - -If you're using the old `CreateAssertionAttribute`: - -```csharp -// Old (still works, but deprecated): -[CreateAssertion("StartsWith")] -public static partial class StringAssertionExtensions { } - -// New: -[AssertionFrom(nameof(string.StartsWith), ExpectationMessage = "to start with {value}")] -public static partial class StringAssertionExtensions { } -``` - -The old attribute shows an obsolete warning but continues to work for backward compatibility. - ---- - ## Complete Example Here's a comprehensive example showing all features: diff --git a/docs/docs/assertions/getting-started.md b/docs/docs/assertions/getting-started.md new file mode 100644 index 0000000000..e4d5d1fa3b --- /dev/null +++ b/docs/docs/assertions/getting-started.md @@ -0,0 +1,277 @@ +--- +sidebar_position: 1 +--- + +# Getting Started with Assertions + +TUnit provides a comprehensive, fluent assertion library that makes your tests readable and expressive. This guide introduces the core concepts and gets you started with writing assertions. + +## Basic Syntax + +All assertions in TUnit follow a consistent pattern using the `Assert.That()` method: + +```csharp +await Assert.That(actualValue).IsEqualTo(expectedValue); +``` + +The basic flow is: +1. Start with `Assert.That(value)` +2. Chain assertion methods (e.g., `.IsEqualTo()`, `.Contains()`, `.IsGreaterThan()`) +3. Always `await` the assertion (TUnit's assertions are async) + +## Why Await? + +TUnit assertions must be awaited. This design enables: +- **Async support**: Seamlessly test async operations +- **Rich error messages**: Build detailed failure messages during execution +- **Extensibility**: Create custom assertions that can perform async operations + +```csharp +// ✅ Correct - awaited +await Assert.That(result).IsEqualTo(42); + +// ❌ Wrong - will cause compiler warning +Assert.That(result).IsEqualTo(42); +``` + +TUnit includes a built-in analyzer that warns you if you forget to `await` an assertion. + +## Assertion Categories + +TUnit provides assertions for all common scenarios: + +### Equality & Comparison + +```csharp +await Assert.That(actual).IsEqualTo(expected); +await Assert.That(value).IsNotEqualTo(other); +await Assert.That(score).IsGreaterThan(70); +await Assert.That(age).IsLessThanOrEqualTo(100); +await Assert.That(temperature).IsBetween(20, 30); +``` + +### Strings + +```csharp +await Assert.That(message).Contains("Hello"); +await Assert.That(filename).StartsWith("test_"); +await Assert.That(email).Matches(@"^[\w\.-]+@[\w\.-]+\.\w+$"); +await Assert.That(input).IsNotEmpty(); +``` + +### Collections + +```csharp +await Assert.That(numbers).Contains(42); +await Assert.That(items).HasCount(5); +await Assert.That(list).IsNotEmpty(); +await Assert.That(values).All(x => x > 0); +``` + +### Booleans & Null + +```csharp +await Assert.That(isValid).IsTrue(); +await Assert.That(result).IsNotNull(); +await Assert.That(optional).IsDefault(); +``` + +### Exceptions + +```csharp +await Assert.That(() => DivideByZero()) + .Throws() + .WithMessage("Attempted to divide by zero."); +``` + +### Type Checking + +```csharp +await Assert.That(obj).IsTypeOf(); +await Assert.That(typeof(Dog)).IsAssignableTo(); +``` + +## Chaining Assertions + +Combine multiple assertions on the same value using `.And`: + +```csharp +await Assert.That(username) + .IsNotNull() + .And.IsNotEmpty() + .And.HasLength().GreaterThan(3) + .And.HasLength().LessThan(20); +``` + +Use `.Or` when any condition can be true: + +```csharp +await Assert.That(statusCode) + .IsEqualTo(200) + .Or.IsEqualTo(201) + .Or.IsEqualTo(204); +``` + +## Multiple Assertions with Assert.Multiple() + +Group related assertions together so all failures are reported: + +```csharp +await using (Assert.Multiple()) +{ + await Assert.That(user.FirstName).IsEqualTo("John"); + await Assert.That(user.LastName).IsEqualTo("Doe"); + await Assert.That(user.Age).IsGreaterThan(18); + await Assert.That(user.Email).IsNotNull(); +} +``` + +Instead of stopping at the first failure, `Assert.Multiple()` runs all assertions and reports every failure together. + +## Member Assertions + +Assert on object properties using `.Member()`: + +```csharp +await Assert.That(person) + .Member(p => p.Name, name => name.IsEqualTo("Alice")) + .And.Member(p => p.Age, age => age.IsGreaterThan(18)); +``` + +This works with nested properties too: + +```csharp +await Assert.That(order) + .Member(o => o.Customer.Address.City, city => city.IsEqualTo("Seattle"); +``` + +## Working with Collections + +Collections have rich assertion support: + +```csharp +var numbers = new[] { 1, 2, 3, 4, 5 }; + +// Count and emptiness +await Assert.That(numbers).HasCount(5); +await Assert.That(numbers).IsNotEmpty(); + +// Membership +await Assert.That(numbers).Contains(3); +await Assert.That(numbers).DoesNotContain(10); + +// Predicates +await Assert.That(numbers).All(n => n > 0); +await Assert.That(numbers).Any(n => n == 3); + +// Ordering +await Assert.That(numbers).IsInOrder(); + +// Equivalence (same items, any order) +await Assert.That(numbers).IsEquivalentTo(new[] { 5, 4, 3, 2, 1 }); +``` + +## Returning Values from Assertions + +Some assertions return the value being tested, allowing you to continue working with it: + +```csharp +// HasSingleItem returns the single item +var user = await Assert.That(users).HasSingleItem(); +await Assert.That(user.Name).IsEqualTo("Alice"); + +// Contains with predicate returns the found item +var admin = await Assert.That(users).Contains(u => u.Role == "Admin"); +await Assert.That(admin.Permissions).IsNotEmpty(); +``` + +## Custom Expectations + +Use `.Satisfies()` for custom conditions: + +```csharp +await Assert.That(value).Satisfies(v => v % 2 == 0, "Value must be even"); +``` + +Or map to a different value before asserting: + +```csharp +await Assert.That(order) + .Satisfies(o => o.Total, total => total > 100); +``` + +## Common Patterns + +### Testing Numeric Ranges + +```csharp +await Assert.That(score).IsBetween(0, 100); +await Assert.That(temperature).IsGreaterThanOrEqualTo(32); +``` + +### Testing with Tolerance + +For floating-point comparisons: + +```csharp +await Assert.That(3.14159).IsEqualTo(Math.PI, tolerance: 0.001); +``` + +### Testing Async Operations + +```csharp +await Assert.That(async () => await FetchDataAsync()) + .Throws(); + +await Assert.That(longRunningTask).CompletesWithin(TimeSpan.FromSeconds(5)); +``` + +### Testing Multiple Conditions + +```csharp +await Assert.That(username) + .IsNotNull() + .And.Satisfies(name => name.Length >= 3 && name.Length <= 20, + "Username must be 3-20 characters"); +``` + +## Type Safety + +TUnit's assertions are strongly typed and catch type mismatches at compile time: + +```csharp +int number = 42; +string text = "42"; + +// ✅ This works - both are ints +await Assert.That(number).IsEqualTo(42); + +// ❌ This won't compile - can't compare int to string +// await Assert.That(number).IsEqualTo("42"); +``` + +## Next Steps + +Now that you understand the basics, explore specific assertion types: + +- **[Equality & Comparison](equality-and-comparison.md)** - Detailed equality and comparison assertions +- **[Strings](string.md)** - Comprehensive string testing +- **[Collections](collections.md)** - Advanced collection assertions +- **[Exceptions](exceptions.md)** - Testing thrown exceptions +- **[Custom Assertions](extensibility/custom-assertions.md)** - Create your own assertions + +## Quick Reference + +| Assertion Category | Example | +|-------------------|---------| +| Equality | `IsEqualTo()`, `IsNotEqualTo()` | +| Comparison | `IsGreaterThan()`, `IsLessThan()`, `IsBetween()` | +| Null/Default | `IsNull()`, `IsNotNull()`, `IsDefault()` | +| Boolean | `IsTrue()`, `IsFalse()` | +| Strings | `Contains()`, `StartsWith()`, `Matches()` | +| Collections | `Contains()`, `HasCount()`, `All()`, `Any()` | +| Exceptions | `Throws()`, `ThrowsNothing()` | +| Types | `IsTypeOf()`, `IsAssignableTo()` | +| Async | `CompletesWithin()`, async exception testing | + +For a complete list of all assertions, see the specific category pages in the sidebar. diff --git a/docs/docs/assertions/null-and-default.md b/docs/docs/assertions/null-and-default.md new file mode 100644 index 0000000000..c0570f6fbd --- /dev/null +++ b/docs/docs/assertions/null-and-default.md @@ -0,0 +1,500 @@ +--- +sidebar_position: 2.5 +--- + +# Null and Default Value Assertions + +TUnit provides assertions for testing null values and default values. These assertions integrate with C#'s nullability annotations to provide better compile-time safety. + +## Null Assertions + +### IsNull + +Tests that a value is `null`: + +```csharp +[Test] +public async Task Null_Value() +{ + string? result = GetOptionalValue(); + await Assert.That(result).IsNull(); + + Person? person = FindPerson("unknown-id"); + await Assert.That(person).IsNull(); +} +``` + +### IsNotNull + +Tests that a value is not `null`: + +```csharp +[Test] +public async Task Not_Null_Value() +{ + string? result = GetRequiredValue(); + await Assert.That(result).IsNotNull(); + + var user = GetCurrentUser(); + await Assert.That(user).IsNotNull(); +} +``` + +## Nullability Flow Analysis + +When you use `IsNotNull()`, C#'s nullability analysis understands that the value is non-null afterward: + +```csharp +[Test] +public async Task Nullability_Flow() +{ + string? maybeNull = GetValue(); + + // After this assertion, compiler knows it's not null + await Assert.That(maybeNull).IsNotNull(); + + // No warning - compiler knows it's safe + int length = maybeNull.Length; +} +``` + +This works with chaining too: + +```csharp +[Test] +public async Task Chained_After_Null_Check() +{ + string? input = GetInput(); + + await Assert.That(input) + .IsNotNull() + .And.IsNotEmpty() // Compiler knows input is not null + .And.HasLength().GreaterThan(5); +} +``` + +## Default Value Assertions + +### IsDefault + +Tests that a value equals the default value for its type: + +```csharp +[Test] +public async Task Default_Values() +{ + // Reference types - default is null + string? text = default; + await Assert.That(text).IsDefault(); + + // Value types - default is zero/false/empty struct + int number = default; + await Assert.That(number).IsDefault(); // 0 + + bool flag = default; + await Assert.That(flag).IsDefault(); // false + + DateTime date = default; + await Assert.That(date).IsDefault(); // DateTime.MinValue + + Guid id = default; + await Assert.That(id).IsDefault(); // Guid.Empty +} +``` + +### IsNotDefault + +Tests that a value is not the default value for its type: + +```csharp +[Test] +public async Task Not_Default_Values() +{ + var name = "Alice"; + await Assert.That(name).IsNotDefault(); + + var count = 42; + await Assert.That(count).IsNotDefault(); + + var isValid = true; + await Assert.That(isValid).IsNotDefault(); + + var id = Guid.NewGuid(); + await Assert.That(id).IsNotDefault(); +} +``` + +## Reference Types vs Value Types + +### Reference Type Defaults + +For reference types, default equals `null`: + +```csharp +[Test] +public async Task Reference_Type_Defaults() +{ + string? text = default; + object? obj = default; + Person? person = default; + + await Assert.That(text).IsDefault(); // Same as IsNull() + await Assert.That(obj).IsDefault(); // Same as IsNull() + await Assert.That(person).IsDefault(); // Same as IsNull() +} +``` + +### Value Type Defaults + +For value types, default is the zero-initialized value: + +```csharp +[Test] +public async Task Value_Type_Defaults() +{ + // Numeric types default to 0 + int intVal = default; + await Assert.That(intVal).IsDefault(); + await Assert.That(intVal).IsEqualTo(0); + + double doubleVal = default; + await Assert.That(doubleVal).IsDefault(); + await Assert.That(doubleVal).IsEqualTo(0.0); + + // Boolean defaults to false + bool boolVal = default; + await Assert.That(boolVal).IsDefault(); + await Assert.That(boolVal).IsFalse(); + + // Struct defaults to all fields/properties at their defaults + Point point = default; + await Assert.That(point).IsDefault(); + await Assert.That(point).IsEqualTo(new Point(0, 0)); +} +``` + +### Nullable Value Types + +Nullable value types (`T?`) are reference types, so their default is `null`: + +```csharp +[Test] +public async Task Nullable_Value_Type_Defaults() +{ + int? nullableInt = default; + await Assert.That(nullableInt).IsDefault(); // Same as IsNull() + await Assert.That(nullableInt).IsNull(); // Also works + + DateTime? nullableDate = default; + await Assert.That(nullableDate).IsDefault(); + await Assert.That(nullableDate).IsNull(); +} +``` + +## Practical Examples + +### Optional Parameters and Returns + +```csharp +[Test] +public async Task Optional_Return_Value() +{ + // API might return null if item not found + var item = await _repository.FindByIdAsync("unknown-id"); + await Assert.That(item).IsNull(); + + // API should return value if item exists + var existing = await _repository.FindByIdAsync("valid-id"); + await Assert.That(existing).IsNotNull(); +} +``` + +### Initialization Checks + +```csharp +[Test] +public async Task Uninitialized_Field() +{ + var service = new MyService(); + + // Before initialization + await Assert.That(service.Connection).IsNull(); + + await service.InitializeAsync(); + + // After initialization + await Assert.That(service.Connection).IsNotNull(); +} +``` + +### Dependency Injection Validation + +```csharp +[Test] +public async Task Constructor_Injection() +{ + var logger = new Mock(); + var service = new UserService(logger.Object); + + // Verify dependency was injected + await Assert.That(service.Logger).IsNotNull(); +} +``` + +### Lazy Initialization + +```csharp +[Test] +public async Task Lazy_Property() +{ + var calculator = new ExpensiveCalculator(); + + // Before first access + await Assert.That(calculator.CachedResult).IsNull(); + + var result = calculator.GetResult(); + + // After first access - cached + await Assert.That(calculator.CachedResult).IsNotNull(); +} +``` + +## Checking Multiple Properties + +Use `Assert.Multiple()` to check multiple null conditions: + +```csharp +[Test] +public async Task Validate_All_Required_Fields() +{ + var user = CreateUser(); + + await using (Assert.Multiple()) + { + await Assert.That(user).IsNotNull(); + await Assert.That(user.FirstName).IsNotNull(); + await Assert.That(user.LastName).IsNotNull(); + await Assert.That(user.Email).IsNotNull(); + await Assert.That(user.CreatedDate).IsNotDefault(); + } +} +``` + +Or chain them: + +```csharp +[Test] +public async Task Required_Fields_With_Chaining() +{ + var config = LoadConfiguration(); + + await Assert.That(config.DatabaseConnection) + .IsNotNull() + .And.Member(c => c.Server).IsNotNull() + .And.Member(c => c.Database).IsNotNull(); +} +``` + +## Default Values for Custom Types + +### Structs + +```csharp +public struct Rectangle +{ + public int Width { get; init; } + public int Height { get; init; } +} + +[Test] +public async Task Struct_Default() +{ + Rectangle rect = default; + + await Assert.That(rect).IsDefault(); + await Assert.That(rect.Width).IsEqualTo(0); + await Assert.That(rect.Height).IsEqualTo(0); +} +``` + +### Records + +```csharp +public record Person(string Name, int Age); + +[Test] +public async Task Record_Default() +{ + Person? person = default; + await Assert.That(person).IsDefault(); // null for reference types + await Assert.That(person).IsNull(); +} + +public record struct Point(int X, int Y); + +[Test] +public async Task Record_Struct_Default() +{ + Point point = default; + await Assert.That(point).IsDefault(); + await Assert.That(point.X).IsEqualTo(0); + await Assert.That(point.Y).IsEqualTo(0); +} +``` + +## Special Cases + +### Empty Collections vs Null + +```csharp +[Test] +public async Task Empty_vs_Null() +{ + List? nullList = null; + List emptyList = new(); + + await Assert.That(nullList).IsNull(); + await Assert.That(emptyList).IsNotNull(); + await Assert.That(emptyList).IsEmpty(); // Not null, but empty +} +``` + +### Empty Strings vs Null + +```csharp +[Test] +public async Task Empty_String_vs_Null() +{ + string? nullString = null; + string emptyString = ""; + + await Assert.That(nullString).IsNull(); + await Assert.That(emptyString).IsNotNull(); + await Assert.That(emptyString).IsEmpty(); // Not null, but empty +} +``` + +### Default GUID + +```csharp +[Test] +public async Task GUID_Default() +{ + Guid id = default; + + await Assert.That(id).IsDefault(); + await Assert.That(id).IsEqualTo(Guid.Empty); + await Assert.That(id).IsEmptyGuid(); // TUnit specific assertion +} +``` + +### Default DateTime + +```csharp +[Test] +public async Task DateTime_Default() +{ + DateTime date = default; + + await Assert.That(date).IsDefault(); + await Assert.That(date).IsEqualTo(DateTime.MinValue); +} +``` + +## Combining with Other Assertions + +### Null Coalescing Validation + +```csharp +[Test] +public async Task Null_Coalescing_Default() +{ + string? input = GetOptionalInput(); + string result = input ?? "default"; + + if (input == null) + { + await Assert.That(result).IsEqualTo("default"); + } + else + { + await Assert.That(result).IsEqualTo(input); + } +} +``` + +### Null Conditional Operator + +```csharp +[Test] +public async Task Null_Conditional() +{ + Person? person = FindPerson("id"); + string? name = person?.Name; + + if (person == null) + { + await Assert.That(name).IsNull(); + } + else + { + await Assert.That(name).IsNotNull(); + } +} +``` + +## Common Patterns + +### Validate Required Dependencies + +```csharp +[Test] +public async Task All_Dependencies_Provided() +{ + var service = CreateService(); + + await Assert.That(service.Logger).IsNotNull(); + await Assert.That(service.Repository).IsNotNull(); + await Assert.That(service.Cache).IsNotNull(); +} +``` + +### Validate Optional Features + +```csharp +[Test] +public async Task Optional_Feature_Not_Enabled() +{ + var config = LoadConfiguration(); + + if (!config.EnableAdvancedFeatures) + { + await Assert.That(config.AdvancedSettings).IsNull(); + } +} +``` + +### State Machine Validation + +```csharp +[Test] +public async Task State_Transitions() +{ + var workflow = new Workflow(); + + // Initial state + await Assert.That(workflow.CurrentState).IsDefault(); + + await workflow.StartAsync(); + + // After start + await Assert.That(workflow.CurrentState).IsNotDefault(); +} +``` + +## See Also + +- [Equality & Comparison](equality-and-comparison.md) - Comparing values including defaults +- [Boolean Assertions](boolean.md) - Testing true/false values +- [String Assertions](string.md) - String-specific null and empty checks +- [Collections](collections.md) - Collection null and empty checks diff --git a/docs/docs/assertions/numeric.md b/docs/docs/assertions/numeric.md new file mode 100644 index 0000000000..6b8cbc8f07 --- /dev/null +++ b/docs/docs/assertions/numeric.md @@ -0,0 +1,583 @@ +--- +sidebar_position: 4.5 +--- + +# Numeric Assertions + +TUnit provides comprehensive assertions for testing numeric values, including specialized assertions for positive/negative values and comparison assertions with tolerance support. + +## Sign Assertions + +### IsPositive + +Tests that a numeric value is greater than zero: + +```csharp +[Test] +public async Task Positive_Values() +{ + var profit = 1500m; + await Assert.That(profit).IsPositive(); + + var count = 5; + await Assert.That(count).IsPositive(); + + var rating = 4.5; + await Assert.That(rating).IsPositive(); +} +``` + +Works with all numeric types: + +```csharp +[Test] +public async Task All_Numeric_Types() +{ + // Integers + await Assert.That(1).IsPositive(); // int + await Assert.That(1L).IsPositive(); // long + await Assert.That((short)1).IsPositive(); // short + await Assert.That((byte)1).IsPositive(); // byte + + // Floating point + await Assert.That(1.5).IsPositive(); // double + await Assert.That(1.5f).IsPositive(); // float + await Assert.That(1.5m).IsPositive(); // decimal +} +``` + +### IsNegative + +Tests that a numeric value is less than zero: + +```csharp +[Test] +public async Task Negative_Values() +{ + var loss = -250.50m; + await Assert.That(loss).IsNegative(); + + var temperature = -5; + await Assert.That(temperature).IsNegative(); + + var delta = -0.001; + await Assert.That(delta).IsNegative(); +} +``` + +### Zero is Neither Positive Nor Negative + +```csharp +[Test] +public async Task Zero_Checks() +{ + var zero = 0; + + // These will both fail: + // await Assert.That(zero).IsPositive(); // ❌ Fails + // await Assert.That(zero).IsNegative(); // ❌ Fails + + // Instead, check for zero explicitly: + await Assert.That(zero).IsEqualTo(0); +} +``` + +## Comparison Assertions + +All comparison operators work with numeric types. See [Equality and Comparison](equality-and-comparison.md) for full details. + +### Quick Reference + +```csharp +[Test] +public async Task Numeric_Comparisons() +{ + var value = 42; + + await Assert.That(value).IsGreaterThan(40); + await Assert.That(value).IsGreaterThanOrEqualTo(42); + await Assert.That(value).IsLessThan(50); + await Assert.That(value).IsLessThanOrEqualTo(42); + await Assert.That(value).IsBetween(0, 100); +} +``` + +## Tolerance for Floating-Point Numbers + +Floating-point arithmetic can introduce rounding errors. Use tolerance for safe comparisons: + +### Double Tolerance + +```csharp +[Test] +public async Task Double_Tolerance() +{ + double result = 1.0 / 3.0; // 0.33333333... + double expected = 0.333; + + // Without tolerance - might fail + // await Assert.That(result).IsEqualTo(expected); + + // With tolerance - safe + await Assert.That(result).IsEqualTo(expected, tolerance: 0.001); +} +``` + +### Float Tolerance + +```csharp +[Test] +public async Task Float_Tolerance() +{ + float pi = 3.14159f; + float approximation = 3.14f; + + await Assert.That(pi).IsEqualTo(approximation, tolerance: 0.01f); +} +``` + +### Decimal Tolerance + +Useful for monetary calculations: + +```csharp +[Test] +public async Task Decimal_Tolerance() +{ + decimal price = 19.995m; + decimal rounded = 20.00m; + + await Assert.That(price).IsEqualTo(rounded, tolerance: 0.01m); +} +``` + +### Long Tolerance + +For timestamp or large number comparisons: + +```csharp +[Test] +public async Task Long_Tolerance() +{ + long timestamp1 = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await Task.Delay(50); + long timestamp2 = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + // Allow 100ms difference + await Assert.That(timestamp1).IsEqualTo(timestamp2, tolerance: 100L); +} +``` + +## Practical Examples + +### Financial Calculations + +```csharp +[Test] +public async Task Calculate_Total_Price() +{ + decimal unitPrice = 9.99m; + int quantity = 3; + decimal tax = 0.08m; // 8% + + decimal subtotal = unitPrice * quantity; + decimal total = subtotal * (1 + tax); + + await Assert.That(total).IsPositive(); + await Assert.That(total).IsGreaterThan(subtotal); + await Assert.That(total).IsEqualTo(32.37m, tolerance: 0.01m); +} +``` + +### Temperature Conversions + +```csharp +[Test] +public async Task Celsius_To_Fahrenheit() +{ + double celsius = 20.0; + double fahrenheit = celsius * 9.0 / 5.0 + 32.0; + + await Assert.That(fahrenheit).IsEqualTo(68.0, tolerance: 0.1); + await Assert.That(fahrenheit).IsGreaterThan(celsius); +} +``` + +### Percentage Calculations + +```csharp +[Test] +public async Task Calculate_Percentage() +{ + int total = 200; + int passed = 175; + double percentage = (double)passed / total * 100; + + await Assert.That(percentage).IsPositive(); + await Assert.That(percentage).IsBetween(0, 100); + await Assert.That(percentage).IsEqualTo(87.5, tolerance: 0.1); +} +``` + +### Statistical Calculations + +```csharp +[Test] +public async Task Calculate_Average() +{ + var numbers = new[] { 10, 20, 30, 40, 50 }; + double average = numbers.Average(); + + await Assert.That(average).IsEqualTo(30.0, tolerance: 0.01); + await Assert.That(average).IsGreaterThan(numbers.Min()); + await Assert.That(average).IsLessThan(numbers.Max()); +} +``` + +## Range Validation + +### Valid Range Checks + +```csharp +[Test] +public async Task Validate_Age() +{ + int age = 25; + + await Assert.That(age).IsBetween(0, 120); + await Assert.That(age).IsGreaterThanOrEqualTo(0); +} +``` + +### Percentage Range + +```csharp +[Test] +public async Task Validate_Percentage() +{ + double successRate = 87.5; + + await Assert.That(successRate).IsBetween(0, 100); + await Assert.That(successRate).IsPositive(); +} +``` + +### Score Validation + +```csharp +[Test] +public async Task Validate_Score() +{ + int score = 85; + int minPassing = 60; + int maxScore = 100; + + await Assert.That(score).IsBetween(minPassing, maxScore); + await Assert.That(score).IsGreaterThanOrEqualTo(minPassing); +} +``` + +## Mathematical Operations + +### Addition + +```csharp +[Test] +public async Task Addition() +{ + var result = 5 + 3; + + await Assert.That(result).IsEqualTo(8); + await Assert.That(result).IsPositive(); + await Assert.That(result).IsGreaterThan(5); +} +``` + +### Subtraction + +```csharp +[Test] +public async Task Subtraction() +{ + var result = 10 - 3; + + await Assert.That(result).IsEqualTo(7); + await Assert.That(result).IsPositive(); +} +``` + +### Multiplication + +```csharp +[Test] +public async Task Multiplication() +{ + var result = 4 * 5; + + await Assert.That(result).IsEqualTo(20); + await Assert.That(result).IsPositive(); +} +``` + +### Division + +```csharp +[Test] +public async Task Division() +{ + double result = 10.0 / 4.0; + + await Assert.That(result).IsEqualTo(2.5, tolerance: 0.001); + await Assert.That(result).IsPositive(); +} +``` + +### Modulo + +```csharp +[Test] +public async Task Modulo() +{ + var result = 17 % 5; + + await Assert.That(result).IsEqualTo(2); + await Assert.That(result).IsGreaterThanOrEqualTo(0); + await Assert.That(result).IsLessThan(5); +} +``` + +## Working with Math Library + +### Rounding + +```csharp +[Test] +public async Task Math_Round() +{ + double value = 3.7; + double rounded = Math.Round(value); + + await Assert.That(rounded).IsEqualTo(4.0, tolerance: 0.001); +} +``` + +### Ceiling and Floor + +```csharp +[Test] +public async Task Math_Ceiling_Floor() +{ + double value = 3.2; + + double ceiling = Math.Ceiling(value); + await Assert.That(ceiling).IsEqualTo(4.0); + + double floor = Math.Floor(value); + await Assert.That(floor).IsEqualTo(3.0); +} +``` + +### Absolute Value + +```csharp +[Test] +public async Task Math_Abs() +{ + int negative = -42; + int positive = Math.Abs(negative); + + await Assert.That(positive).IsPositive(); + await Assert.That(positive).IsEqualTo(42); +} +``` + +### Power and Square Root + +```csharp +[Test] +public async Task Math_Power_Sqrt() +{ + double squared = Math.Pow(5, 2); + await Assert.That(squared).IsEqualTo(25.0, tolerance: 0.001); + + double root = Math.Sqrt(25); + await Assert.That(root).IsEqualTo(5.0, tolerance: 0.001); +} +``` + +### Trigonometry + +```csharp +[Test] +public async Task Math_Trigonometry() +{ + double angle = Math.PI / 4; // 45 degrees + double sine = Math.Sin(angle); + + await Assert.That(sine).IsEqualTo(Math.Sqrt(2) / 2, tolerance: 0.0001); + await Assert.That(sine).IsPositive(); + await Assert.That(sine).IsBetween(0, 1); +} +``` + +## Increment and Decrement + +```csharp +[Test] +public async Task Increment_Decrement() +{ + int counter = 0; + + counter++; + await Assert.That(counter).IsEqualTo(1); + await Assert.That(counter).IsPositive(); + + counter--; + await Assert.That(counter).IsEqualTo(0); + + counter--; + await Assert.That(counter).IsEqualTo(-1); + await Assert.That(counter).IsNegative(); +} +``` + +## Chaining Numeric Assertions + +```csharp +[Test] +public async Task Chained_Numeric_Assertions() +{ + int score = 85; + + await Assert.That(score) + .IsPositive() + .And.IsGreaterThan(70) + .And.IsLessThan(100) + .And.IsBetween(80, 90); +} +``` + +## Nullable Numeric Types + +```csharp +[Test] +public async Task Nullable_Numerics() +{ + int? value = 42; + + await Assert.That(value).IsNotNull(); + await Assert.That(value).IsEqualTo(42); + await Assert.That(value).IsPositive(); +} + +[Test] +public async Task Nullable_Null() +{ + int? value = null; + + await Assert.That(value).IsNull(); +} +``` + +## Special Floating-Point Values + +### Infinity + +```csharp +[Test] +public async Task Infinity_Checks() +{ + double positiveInfinity = double.PositiveInfinity; + double negativeInfinity = double.NegativeInfinity; + + await Assert.That(positiveInfinity).IsEqualTo(double.PositiveInfinity); + await Assert.That(negativeInfinity).IsEqualTo(double.NegativeInfinity); +} +``` + +### NaN (Not a Number) + +```csharp +[Test] +public async Task NaN_Checks() +{ + double nan = double.NaN; + + // NaN is never equal to itself + await Assert.That(double.IsNaN(nan)).IsTrue(); + + // Can't use IsEqualTo with NaN + // await Assert.That(nan).IsEqualTo(double.NaN); // ❌ Won't work +} +``` + +## Performance Metrics + +```csharp +[Test] +public async Task Response_Time_Check() +{ + var stopwatch = Stopwatch.StartNew(); + await PerformOperationAsync(); + stopwatch.Stop(); + + long milliseconds = stopwatch.ElapsedMilliseconds; + + await Assert.That(milliseconds).IsPositive(); + await Assert.That(milliseconds).IsLessThan(1000); // Under 1 second +} +``` + +## Common Patterns + +### Boundary Testing + +```csharp +[Test] +public async Task Boundary_Values() +{ + int min = int.MinValue; + int max = int.MaxValue; + + await Assert.That(min).IsNegative(); + await Assert.That(max).IsPositive(); + await Assert.That(min).IsLessThan(max); +} +``` + +### Growth Rate Validation + +```csharp +[Test] +public async Task Growth_Rate() +{ + decimal previousValue = 100m; + decimal currentValue = 125m; + decimal growthRate = (currentValue - previousValue) / previousValue * 100; + + await Assert.That(growthRate).IsPositive(); + await Assert.That(growthRate).IsEqualTo(25m, tolerance: 0.1m); +} +``` + +### Ratio Calculations + +```csharp +[Test] +public async Task Success_Ratio() +{ + int successful = 85; + int total = 100; + double ratio = (double)successful / total; + + await Assert.That(ratio).IsPositive(); + await Assert.That(ratio).IsBetween(0, 1); + await Assert.That(ratio).IsGreaterThan(0.8); // 80% threshold +} +``` + +## See Also + +- [Equality & Comparison](equality-and-comparison.md) - General comparison assertions +- [DateTime Assertions](datetime.md) - Time-based numeric values with tolerance +- [Collections](collections.md) - Numeric operations on collections (Count, Sum, Average) diff --git a/docs/docs/assertions/regex-assertions.md b/docs/docs/assertions/regex-assertions.md new file mode 100644 index 0000000000..6b2d9b1261 --- /dev/null +++ b/docs/docs/assertions/regex-assertions.md @@ -0,0 +1,315 @@ +# Regex Assertions + +The `.Matches()` method allows you to validate strings against regular expressions and assert on capture groups, match positions, and match lengths. This is useful when you need to validate structured text like emails, phone numbers, dates, or extract specific parts of a string. + +## Basic Usage + +```csharp +[Test] +public async Task BasicRegexAssertions() +{ + var email = "john.doe@example.com"; + + // Assert that string matches a pattern + await Assert.That(email).Matches(@"^[\w.]+@[\w.]+$"); + + // Use a compiled Regex object + var emailRegex = new Regex(@"^[\w.]+@[\w.]+$"); + await Assert.That(email).Matches(emailRegex); + + // Use source-generated regex (C# 11+) + [GeneratedRegex(@"^[\w.]+@[\w.]+$")] + static partial Regex EmailRegex(); + + await Assert.That(email).Matches(EmailRegex()); +} +``` + +## Group Assertions + +The key advantage of regex assertions is the ability to assert on capture groups using `.Group()`: + +### Named Groups + +```csharp +[Test] +public async Task NamedGroupAssertions() +{ + var email = "john.doe@example.com"; + var pattern = @"(?[\w.]+)@(?[\w.]+)"; + + // Assert on named capture groups (requires .And before .Group()) + await Assert.That(email) + .Matches(pattern) + .And.Group("username", user => user.IsEqualTo("john.doe")) + .And.Group("domain", domain => domain.IsEqualTo("example.com")); +} +``` + +### Indexed Groups + +```csharp +[Test] +public async Task IndexedGroupAssertions() +{ + var date = "2025-10-28"; + var pattern = @"(\d{4})-(\d{2})-(\d{2})"; + + // Assert on indexed capture groups (1-based, 0 is full match) + await Assert.That(date) + .Matches(pattern) + .And.Group(0, full => full.IsEqualTo("2025-10-28")) + .And.Group(1, year => year.IsEqualTo("2025")) + .And.Group(2, month => month.IsEqualTo("10")) + .And.Group(3, day => day.IsEqualTo("28")); +} +``` + +## Multiple Matches + +When a regex matches multiple times in a string, you can access specific matches using `.Match(index)`: + +```csharp +[Test] +public async Task MultipleMatchAssertions() +{ + var text = "test123 hello456 world789"; + var pattern = @"\w+\d+"; + + // Assert on first match + await Assert.That(text) + .Matches(pattern) + .And.Match(0) + .And.Group(0, match => match.IsEqualTo("test123")); + + // Use lambda pattern to assert on a specific match + await Assert.That(text) + .Matches(pattern) + .And.Match(1, match => match.Group(0, g => g.IsEqualTo("hello456"))); +} +``` + +## Match Position and Length + +You can assert on where a match occurs and its length: + +```csharp +[Test] +public async Task PositionAndLengthAssertions() +{ + var text = "Hello World 123"; + var pattern = @"\d+"; + + // Assert that match is at specific index + await Assert.That(text) + .Matches(pattern) + .AtIndex(12); + + // Assert that match has specific length + await Assert.That(text) + .Matches(pattern) + .HasLength(3); + + // Combine with group assertions + await Assert.That(text) + .Matches(pattern) + .AtIndex(12) + .And.HasLength(3); +} +``` + +## Complex Patterns with Multiple Groups + +```csharp +[Test] +public async Task ComplexPatternAssertions() +{ + var logEntry = "[2025-10-28 14:30:45] ERROR: Connection timeout"; + var pattern = @"\[(?\d{4}-\d{2}-\d{2}) (?