From a54e45469f704723e48e8d91ecb8d8fcb3da17a3 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 17:48:05 -0300 Subject: [PATCH 1/5] Improve test coverage, build hygiene, and CI/CD hardening - Add tests for ST007, analyzer-path ST013, MSBuild diagnostics (ST011, ST014, ST024), automated in-process VB compilation of Stunt.vb and Stunt.DynamicFactory.vb, and StuntCache compilation-option invalidation, pruning, and concurrency. - Remove blanket Retry/Thread.Sleep(500) from scenario tests and replace Thread.Sleep(50) in concurrency tests with deterministic Barrier synchronization. - Delete dead src/Directory.targets and legacy Jekyll files (_config.yml, assets/css/style.scss); remove dead net48 conditions from Stunts.UnitTests.csproj and Samples.csproj; remove stale wait-status.ps1 entry from Stunts.slnx. - Centralize RoslynVersion, RoslynToolsVersion, NuGetizerVersion, and PolySharpVersion in src/Directory.props. - Harden GitHub Actions workflows (least-privilege permissions, SHA-pinned actions, env-passed secrets, windows-latest native-aot, samples job, publish gated on native-aot and acceptance, PR dry-run Lunet site build, and github-actions Dependabot updates). Co-authored-by: CodeAlta --- .github/dependabot.yml | 4 + .github/workflows/build.yml | 83 ++-- .github/workflows/publish.yml | 85 +++- .github/workflows/site.yml | 23 +- Stunts.slnx | 1 - _config.yml | 3 - assets/css/style.scss | 26 -- samples/Samples/Samples.csproj | 1 - src/Directory.Packages.props | 4 +- src/Directory.props | 11 +- src/Directory.targets | 13 - .../Stunts.CodeAnalysis.csproj | 4 +- src/Stunts.CodeFixes/Stunts.CodeFixes.csproj | 4 +- .../Stunts.CompiledProxy.targets | 4 +- src/Stunts.UnitTests/.Scenarios.cs | 23 +- src/Stunts.UnitTests/BehaviorPipelineTests.cs | 7 +- src/Stunts.UnitTests/Phase4CoverageTests.cs | 390 ++++++++++++++++++ src/Stunts.UnitTests/StuntCacheTests.cs | 127 +++++- src/Stunts.UnitTests/StuntFactoryTests.cs | 7 +- src/Stunts.UnitTests/Stunts.UnitTests.csproj | 8 +- 20 files changed, 697 insertions(+), 131 deletions(-) delete mode 100644 _config.yml delete mode 100644 assets/css/style.scss delete mode 100644 src/Directory.targets create mode 100644 src/Stunts.UnitTests/Phase4CoverageTests.cs diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a3ba5bf8..cdf1c451 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -51,3 +51,7 @@ updates: Spectre: patterns: - "Spectre.Console*" +- package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0144ec81..a435ac6e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,8 +1,8 @@ -ο»Ώ# Builds and runs tests on Ubuntu. The full OS matrix runs in publish and release. +# Builds and runs tests on Ubuntu. The full OS matrix runs in publish and release. # Pushes CI feed if secrets.SLEET_CONNECTION is provided name: build -on: +on: workflow_dispatch: push: branches: [ main, dev, 'feature/*', 'rel/*' ] @@ -12,6 +12,9 @@ on: pull_request: types: [opened, synchronize, reopened] +permissions: + contents: read + env: DOTNET_NOLOGO: true @@ -24,13 +27,13 @@ jobs: runs-on: ubuntu-latest steps: - name: 🀘 checkout - uses: actions/checkout@v4 - with: + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: submodules: recursive fetch-depth: 0 - name: βš™ dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: βœ“ ensure format run: | @@ -43,13 +46,13 @@ jobs: runs-on: ubuntu-latest steps: - name: 🀘 checkout - uses: actions/checkout@v4 - with: + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: submodules: recursive fetch-depth: 0 - name: βš™ dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: πŸ™ build run: dotnet build -m:1 -bl:build.binlog -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" -p:RepositoryBranch=${GITHUB_REF#refs/*/} @@ -61,43 +64,52 @@ jobs: run: dotnet pack -m:1 -bl:pack.binlog -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" -p:RepositoryBranch=${GITHUB_REF#refs/*/} - name: πŸ”Ό packages - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: bin-ubuntu-latest path: bin/*.nupkg - + # Push the CI package to the sleet feed when a connection is configured - name: πŸš€ sleet env: SLEET_CONNECTION: ${{ secrets.SLEET_CONNECTION }} + SLEET_FEED_URL: ${{ vars.SLEET_FEED_URL }} if: env.SLEET_CONNECTION != '' run: | - dotnet tool update sleet -g --allow-downgrade --version $(curl -s --compressed ${{ vars.SLEET_FEED_URL }} | jq '.["sleet:version"]' -r) - sleet push bin --config none -f --verbose -p "SLEET_FEED_CONTAINER=nuget" -p "SLEET_FEED_CONNECTIONSTRING=${{ secrets.SLEET_CONNECTION }}" -p "SLEET_FEED_TYPE=azure" || echo "No packages found" + dotnet tool update sleet -g --allow-downgrade --version $(curl -s --compressed "$SLEET_FEED_URL" | jq '.["sleet:version"]' -r) + sleet push bin --config none -f --verbose -p "SLEET_FEED_CONTAINER=nuget" -p "SLEET_FEED_CONNECTIONSTRING=$SLEET_CONNECTION" -p "SLEET_FEED_TYPE=azure" || echo "No packages found" native-aot: - name: native-aot-${{ matrix.framework }} - runs-on: ubuntu-latest + name: native-aot-${{ matrix.os }}-${{ matrix.framework }} + runs-on: ${{ matrix.os }} needs: build strategy: matrix: + os: [ubuntu-latest, windows-latest] framework: [net8.0, net10.0] + include: + - os: ubuntu-latest + rid: linux-x64 + exe: CompiledAot + - os: windows-latest + rid: win-x64 + exe: CompiledAot.exe steps: - name: checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: submodules: recursive - name: dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: packages - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: bin-ubuntu-latest path: bin - name: publish and execute run: | - dotnet publish src/Acceptance/CompiledAot/CompiledAot.csproj -c Release -f ${{ matrix.framework }} -r linux-x64 -p:UseSharedCompilation=false -warnaserror -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" - src/Acceptance/CompiledAot/bin/Release/${{ matrix.framework }}/linux-x64/publish/CompiledAot + dotnet publish src/Acceptance/CompiledAot/CompiledAot.csproj -c Release -f ${{ matrix.framework }} -r ${{ matrix.rid }} -p:UseSharedCompilation=false -warnaserror -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" + src/Acceptance/CompiledAot/bin/Release/${{ matrix.framework }}/${{ matrix.rid }}/publish/${{ matrix.exe }} acceptance: name: acceptance @@ -105,13 +117,13 @@ jobs: needs: build steps: - name: 🀘 checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: βš™ dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: πŸ”½ packages - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: bin-ubuntu-latest path: bin @@ -124,6 +136,27 @@ jobs: run: dotnet test Acceptance.slnx -f net10.0 -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" working-directory: src/Acceptance + samples: + name: samples + runs-on: ubuntu-latest + needs: build + steps: + - name: 🀘 checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: βš™ dotnet + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 + + - name: πŸ”½ packages + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: bin-ubuntu-latest + path: bin + + - name: πŸ§ͺ test + run: dotnet test Samples.slnx -p:VersionLabel="$GITHUB_REF.$GITHUB_RUN_NUMBER" + working-directory: samples + # The compilers that run on .NET Framework load analyzers from the analyzer references alone. # They come with Visual Studio, which the Windows image has. framework-compiler: @@ -132,13 +165,13 @@ jobs: needs: build steps: - name: 🀘 checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: βš™ dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: πŸ”½ packages - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: bin-ubuntu-latest path: bin diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9a25b78d..3d729c7d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,5 +1,6 @@ -ο»Ώ# Builds a final release version on every supported OS and pushes to nuget.org -# whenever a release is published. Packages are pushed only after the whole matrix passes. +# Builds a final release version on every supported OS and pushes to nuget.org +# whenever a release is published. Packages are pushed only after the whole matrix, +# native-aot, and acceptance checks pass. # Requires: vars.NUGET_OIDC (or secrets.NUGET_OIDC) and a nuget.org trusted publishing policy name: publish @@ -7,6 +8,9 @@ on: release: types: [prereleased, released] +permissions: + contents: read + env: DOTNET_NOLOGO: true Configuration: Release @@ -24,13 +28,13 @@ jobs: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - name: 🀘 checkout - uses: actions/checkout@v4 - with: + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: submodules: recursive fetch-depth: 0 - name: βš™ dotnet - uses: devlooped/actions-dotnet-env@v1 + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 - name: πŸ™ build run: dotnet build -m:1 -bl:build.binlog -p:version=${GITHUB_REF#refs/*/v} -p:RepositoryBranch=${GITHUB_REF#refs/*/} @@ -43,7 +47,7 @@ jobs: - name: πŸ”Ό logs if: ${{ always() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: logs-${{ matrix.os }} path: '*.binlog' @@ -60,11 +64,68 @@ jobs: - name: πŸ”Ό packages if: matrix.os == 'ubuntu-latest' - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: bin-ubuntu-latest path: bin/*.nupkg + native-aot: + name: native-aot-${{ matrix.os }}-${{ matrix.framework }} + runs-on: ${{ matrix.os }} + needs: build + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + framework: [net8.0, net10.0] + include: + - os: ubuntu-latest + rid: linux-x64 + exe: CompiledAot + - os: windows-latest + rid: win-x64 + exe: CompiledAot.exe + steps: + - name: checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + submodules: recursive + - name: dotnet + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 + - name: packages + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: bin-ubuntu-latest + path: bin + - name: publish and execute + run: | + dotnet publish src/Acceptance/CompiledAot/CompiledAot.csproj -c Release -f ${{ matrix.framework }} -r ${{ matrix.rid }} -p:UseSharedCompilation=false -warnaserror -p:version=${GITHUB_REF#refs/*/v} + src/Acceptance/CompiledAot/bin/Release/${{ matrix.framework }}/${{ matrix.rid }}/publish/${{ matrix.exe }} + + acceptance: + name: acceptance + runs-on: ubuntu-latest + needs: build + steps: + - name: 🀘 checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - name: βš™ dotnet + uses: devlooped/actions-dotnet-env@4c319f75df2949bfe5906e7b080941fe61756cf0 # v1 + + - name: πŸ”½ packages + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: bin-ubuntu-latest + path: bin + + - name: πŸ— generate comparison stunts + run: dotnet run --file GenerateReferenceStunts.cs + working-directory: src/Acceptance + + - name: πŸ§ͺ test + run: dotnet test Acceptance.slnx -f net10.0 -p:version=${GITHUB_REF#refs/*/v} + working-directory: src/Acceptance + # Pushes with nuget.org Trusted Publishing (GitHub Actions OIDC), no long-lived API key. # Only this job may request an OIDC token. The nuget.org policy, created by the # NuGet/login user (vars.NUGET_OIDC, or secrets.NUGET_OIDC when the variable is empty), @@ -80,7 +141,7 @@ jobs: # https://learn.microsoft.com/nuget/nuget-org/trusted-publishing # https://github.com/NuGet/login publish: - needs: build + needs: [build, native-aot, acceptance] if: github.event.action != 'prereleased' runs-on: ubuntu-latest environment: nuget @@ -89,16 +150,18 @@ jobs: id-token: write steps: - name: πŸ”½ packages - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: bin-ubuntu-latest path: bin - name: πŸ”‘ nuget login id: login - uses: NuGet/login@v1 + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1 with: user: ${{ vars.NUGET_OIDC || secrets.NUGET_OIDC }} - name: πŸš€ nuget - run: dotnet nuget push ./bin/**/*.nupkg -s https://api.nuget.org/v3/index.json -k ${{ steps.login.outputs.NUGET_API_KEY }} --skip-duplicate + env: + NUGET_API_KEY: ${{ steps.login.outputs.NUGET_API_KEY }} + run: dotnet nuget push ./bin/**/*.nupkg -s https://api.nuget.org/v3/index.json -k "$NUGET_API_KEY" --skip-duplicate diff --git a/.github/workflows/site.yml b/.github/workflows/site.yml index 441fdc3b..1b8f2174 100644 --- a/.github/workflows/site.yml +++ b/.github/workflows/site.yml @@ -1,4 +1,5 @@ # Builds the website (docs/, a Lunet site) and deploys it to GitHub Pages. +# Pull requests run the Lunet build as a dry run without deploying. # Requires: Settings > Pages > Build and deployment > Source set to "GitHub Actions". name: site @@ -13,15 +14,20 @@ on: - src/Stunts.Extensions/** - src/Directory.* - .github/workflows/site.yml + pull_request: + paths: + - docs/** + - src/Stunts/** + - src/Stunts.Extensions/** + - src/Directory.* + - .github/workflows/site.yml permissions: contents: read - pages: write - id-token: write -# One deployment at a time; a newer one waits for the running one to end. +# One deployment at a time on main; PR builds do not block deployments. concurrency: - group: pages + group: pages-${{ github.ref }} cancel-in-progress: false jobs: @@ -29,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - name: πŸ› οΈ build - uses: lunet-io/actions/lunet-build@v1 + uses: lunet-io/actions/lunet-build@2ea1efa0c38b53c50c3f7dd54aaf25ae4dfee6c7 # v1 with: site_path: docs build_command: pwsh ./build.ps1 @@ -38,11 +44,16 @@ jobs: deploy: needs: build + if: github.event_name != 'pull_request' runs-on: ubuntu-latest + permissions: + contents: read + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deploy.outputs.page_url }} steps: - name: πŸš€ deploy id: deploy - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 diff --git a/Stunts.slnx b/Stunts.slnx index 52b4cac4..2332f76d 100644 --- a/Stunts.slnx +++ b/Stunts.slnx @@ -16,7 +16,6 @@ - diff --git a/_config.yml b/_config.yml deleted file mode 100644 index 04e60939..00000000 --- a/_config.yml +++ /dev/null @@ -1,3 +0,0 @@ -theme: jekyll-theme-slate - -exclude: [ 'src/', '*.sln', '*.slnx', 'Gemfile*', '*.rsp' ] diff --git a/assets/css/style.scss b/assets/css/style.scss deleted file mode 100644 index 5e165a3c..00000000 --- a/assets/css/style.scss +++ /dev/null @@ -1,26 +0,0 @@ ---- ---- - -@import "jekyll-theme-slate"; - -.inner { - max-width: 960px; -} - -pre, code { - background-color: unset; - font-size: unset; -} - - code { - font-size: 0.80em; -} - -h1 > img { - border: unset; - box-shadow: unset; - vertical-align: middle; - -moz-box-shadow: unset; - -o-box-shadow: unset; - -ms-box-shadow: unset; -} diff --git a/samples/Samples/Samples.csproj b/samples/Samples/Samples.csproj index 956fd743..65eac5fe 100644 --- a/samples/Samples/Samples.csproj +++ b/samples/Samples/Samples.csproj @@ -11,7 +11,6 @@ - diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index c2de97ba..cda9fd0a 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -6,10 +6,10 @@ - + - + diff --git a/src/Directory.props b/src/Directory.props index 05499ce5..47d5f149 100644 --- a/src/Directory.props +++ b/src/Directory.props @@ -14,14 +14,17 @@ https://clarius.org/stunts 0.6.2 + + + 5.0.0 + 5.0 + 1.5.1 + 1.16.0 - - 5.0.0 - 5.0 obj\$(RoslynVersion)\ Debug bin\$(RoslynVersion)\$(Configuration) diff --git a/src/Directory.targets b/src/Directory.targets deleted file mode 100644 index 2761604d..00000000 --- a/src/Directory.targets +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Stunts.CodeAnalysis/Stunts.CodeAnalysis.csproj b/src/Stunts.CodeAnalysis/Stunts.CodeAnalysis.csproj index 6bc3a722..12525fba 100644 --- a/src/Stunts.CodeAnalysis/Stunts.CodeAnalysis.csproj +++ b/src/Stunts.CodeAnalysis/Stunts.CodeAnalysis.csproj @@ -6,7 +6,6 @@ true analyzers\dotnet - true true @@ -16,7 +15,7 @@ - + @@ -44,6 +43,7 @@ + ResXFileCodeGenerator Resources.Designer.cs diff --git a/src/Stunts.CodeFixes/Stunts.CodeFixes.csproj b/src/Stunts.CodeFixes/Stunts.CodeFixes.csproj index b51eefe8..a369ad02 100644 --- a/src/Stunts.CodeFixes/Stunts.CodeFixes.csproj +++ b/src/Stunts.CodeFixes/Stunts.CodeFixes.csproj @@ -10,8 +10,8 @@ - - + + diff --git a/src/Stunts.CompiledProxy/Stunts.CompiledProxy.targets b/src/Stunts.CompiledProxy/Stunts.CompiledProxy.targets index 565bb8da..58014e2b 100644 --- a/src/Stunts.CompiledProxy/Stunts.CompiledProxy.targets +++ b/src/Stunts.CompiledProxy/Stunts.CompiledProxy.targets @@ -16,8 +16,8 @@ - - + + diff --git a/src/Stunts.UnitTests/.Scenarios.cs b/src/Stunts.UnitTests/.Scenarios.cs index 61fd548b..c7d6af09 100644 --- a/src/Stunts.UnitTests/.Scenarios.cs +++ b/src/Stunts.UnitTests/.Scenarios.cs @@ -34,10 +34,9 @@ public class Scenarios [MemberData(nameof(GetScenarios))] public void Run(string path) { - // Getting the generated output can be flaky sometimes, so retry - var (diagnostics, compilation) = Retry(() => GetGeneratedOutput( + var (diagnostics, compilation) = GetGeneratedOutput( Path.IsPathRooted(path) ? path : - Path.Combine(ThisAssembly.Project.MSBuildProjectDirectory, path))); + Path.Combine(ThisAssembly.Project.MSBuildProjectDirectory, path)); Assert.True(diagnostics.IsEmpty, "Generated code produced diagnostics:\r\n" + @@ -60,24 +59,6 @@ public void Run(string path) } } - T Retry(Func func, int times = 2) - { - for (var i = 1; i <= times; i++) - { - try - { - return func(); - } - catch (Exception) when (i < times) - { - Thread.Sleep(500); - GC.Collect(); - } - } - - return default; - } - public static IEnumerable GetScenarios() => new[] { "Scenarios", "Castle" } .SelectMany(folder => Directory.EnumerateFiles( diff --git a/src/Stunts.UnitTests/BehaviorPipelineTests.cs b/src/Stunts.UnitTests/BehaviorPipelineTests.cs index 89539013..3d87a8f1 100644 --- a/src/Stunts.UnitTests/BehaviorPipelineTests.cs +++ b/src/Stunts.UnitTests/BehaviorPipelineTests.cs @@ -374,19 +374,22 @@ public async Task WhenRunningParallel_ThenCanReplaceLocalPipelineFactory() { var factory1 = new TestBehaviorPipelineFactory(); var factory2 = new TestBehaviorPipelineFactory(); + using var barrier = new Barrier(2); await Task.WhenAll( Task.Run(() => { using var ambient = BehaviorPipelineFactory.UseAmbient(factory1); - Thread.Sleep(50); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); Assert.Same(factory1, BehaviorPipelineFactory.Default); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); }), Task.Run(() => { using var ambient = BehaviorPipelineFactory.UseAmbient(factory2); - Thread.Sleep(50); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); Assert.Same(factory2, BehaviorPipelineFactory.Default); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); }) ); diff --git a/src/Stunts.UnitTests/Phase4CoverageTests.cs b/src/Stunts.UnitTests/Phase4CoverageTests.cs new file mode 100644 index 00000000..0a5db93a --- /dev/null +++ b/src/Stunts.UnitTests/Phase4CoverageTests.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.VisualBasic; +using Stunts.CodeAnalysis; +using Xunit; + +namespace Stunts.UnitTests +{ + public class Phase4CoverageTests + { + [Fact] + public void StuntGenerator_ReportsST007_WhenGeneratorAttributeMissingFromCompilation() + { + const string source = """ + public interface ITarget { int Value { get; } } + """; + + var parseOptions = ParseOptions(); + var compilation = CreateCompilation( + "ST007Test", + parseOptions, + includeStuntsSources: false, + CSharpSyntaxTree.ParseText(source, parseOptions, path: "Test.cs", encoding: Encoding.UTF8)); + + var generator = new StuntGenerator().WithGeneratorAttribute(typeof(MissingFromCompilationGeneratorAttribute)); + var driver = CSharpGeneratorDriver.Create( + generators: new[] { generator.AsSourceGenerator() }, + parseOptions: parseOptions, + optionsProvider: DefaultOptionsProvider()); + + driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var diagnostics); + + var st007 = Assert.Single(diagnostics, d => d.Id == StuntDiagnostics.GeneratorAttributeNotFound.Id); + Assert.Equal(DiagnosticSeverity.Error, st007.Severity); + } + + [Fact] + public async Task ValidateTypesAnalyzer_ReportsST013_ForUnsupportedClrSignatures() + { + const string source = """ + using System; + using Stunts; + + public interface ITypedRefParam + { + void Use(TypedReference value); + } + + public interface IRefSpanReturn + { + ref Span Get(); + } + + public class ArgIteratorCtor + { + public ArgIteratorCtor(ArgIterator args) { } + public virtual int Value() => 1; + } + + public static class Caller + { + public static object Use() => ( + Stunt.Of(), + Stunt.Of(), + Stunt.Of()); + } + """; + + var compileTimeDiagnostics = await RunAnalyzerAsync(source, new ValidateTypesAnalyzer()); + var st013CompileTime = compileTimeDiagnostics.Where(d => d.Id == StuntDiagnostics.UnsupportedRuntimeSignature.Id).ToList(); + + Assert.Equal(3, st013CompileTime.Count); + Assert.Contains(st013CompileTime, d => d.GetMessage().Contains("ITypedRefParam")); + Assert.Contains(st013CompileTime, d => d.GetMessage().Contains("IRefSpanReturn")); + Assert.Contains(st013CompileTime, d => d.GetMessage().Contains("ArgIteratorCtor")); + + // Run-time stunts do not intercept constructors, so ArgIteratorCtor should not report ST013 when disabled. + var runtimeDiagnostics = await RunAnalyzerAsync( + source, + new ValidateTypesAnalyzer(), + new Dictionary { [BuildProperties.Name.EnableCompileTimeStunts] = "false" }); + var st013Runtime = runtimeDiagnostics.Where(d => d.Id == StuntDiagnostics.UnsupportedRuntimeSignature.Id).ToList(); + + Assert.Equal(2, st013Runtime.Count); + Assert.DoesNotContain(st013Runtime, d => d.GetMessage().Contains("ArgIteratorCtor")); + } + + [Fact] + public void MSBuildTargets_ReportST011_ST014_And_ST024() + { + var targetsPath = Path.GetFullPath(Path.Combine( + ThisAssembly.Project.MSBuildProjectDirectory, + "..", "Stunts.Package", "Stunts.targets")); + Assert.True(File.Exists(targetsPath), $"Expected Stunts.targets at {targetsPath}"); + + var tempDir = Path.Combine(Path.GetTempPath(), "stunts-msbuild-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + var copiedTargets = Path.Combine(tempDir, "build", "netstandard2.0", "Stunts.targets"); + Directory.CreateDirectory(Path.GetDirectoryName(copiedTargets)!); + File.Copy(targetsPath, copiedTargets); + + var projectPath = Path.Combine(tempDir, "Test.proj"); + File.WriteAllText(projectPath, $""" + + + + + """); + + // ST011 for VB without Stunts.DynamicProxy. + var vbResult = RunMSBuild(projectPath, "CheckRunTimeStunts", new Dictionary + { + ["Language"] = "VB", + }); + Assert.Equal(0, vbResult.ExitCode); + Assert.Contains("ST011", vbResult.Output); + Assert.Contains("Visual Basic only supports run-time stunts", vbResult.Output); + + // ST011 for C# with EnableCompileTimeStunts=false and no Stunts.DynamicProxy. + var disabledCsResult = RunMSBuild(projectPath, "CheckRunTimeStunts", new Dictionary + { + ["Language"] = "C#", + ["EnableCompileTimeStunts"] = "false", + }); + Assert.Equal(0, disabledCsResult.ExitCode); + Assert.Contains("ST011", disabledCsResult.Output); + Assert.Contains("Compile-time stunts are disabled", disabledCsResult.Output); + + // ST011 suppressed when StuntsDynamicProxy=true. + var dynamicProxyResult = RunMSBuild(projectPath, "CheckRunTimeStunts", new Dictionary + { + ["Language"] = "VB", + ["StuntsDynamicProxy"] = "true", + }); + Assert.Equal(0, dynamicProxyResult.ExitCode); + Assert.DoesNotContain("ST011", dynamicProxyResult.Output); + + // ST014 when PublishAot=true and EnableCompileTimeStunts=false. + var aotResult = RunMSBuild(projectPath, "CheckNativeAotStunts", new Dictionary + { + ["Language"] = "C#", + ["PublishAot"] = "true", + ["EnableCompileTimeStunts"] = "false", + }); + Assert.Equal(0, aotResult.ExitCode); + Assert.Contains("ST014", aotResult.Output); + + // ST024 when Stunts.CompiledProxy.dll is missing under tools\5.0. + var missingGeneratorResult = RunMSBuild(projectPath, "ResolveCompileTimeStunts", new Dictionary + { + ["Language"] = "C#", + ["EnableCompileTimeStunts"] = "true", + }); + Assert.NotEqual(0, missingGeneratorResult.ExitCode); + Assert.Contains("ST024", missingGeneratorResult.Output); + } + finally + { + if (Directory.Exists(tempDir)) + Directory.Delete(tempDir, true); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void VisualBasicContentFiles_CompileCleanlyWithOptionStrictOn(bool net5OrGreater) + { + var stuntVbPath = Path.GetFullPath(Path.Combine( + ThisAssembly.Project.MSBuildProjectDirectory, + "..", "Stunts.Package", "Stunt.vb")); + var dynamicFactoryVbPath = Path.GetFullPath(Path.Combine( + ThisAssembly.Project.MSBuildProjectDirectory, + "..", "Stunts.DynamicProxy", "Stunt.DynamicFactory.vb")); + + Assert.True(File.Exists(stuntVbPath), $"Expected Stunt.vb at {stuntVbPath}"); + Assert.True(File.Exists(dynamicFactoryVbPath), $"Expected Stunt.DynamicFactory.vb at {dynamicFactoryVbPath}"); + + const string consumerVb = """ + Imports System + Imports Stunts + + Public Interface ICalculator + Function Add(x As Integer, y As Integer) As Integer + End Interface + + Public Delegate Function Adder(x As Integer, y As Integer) As Integer + + Public Class Consumer + Public Sub Exercise() + Dim direct As ICalculator = Stunt.Of(Of ICalculator)() + Dim withExtra As ICalculator = Stunt.Of(Of ICalculator, IDisposable)() + Dim reference As StuntReference(Of ICalculator) = Stunt.For(Of ICalculator)() _ + .AddBehavior(Of DefaultValueBehavior)() _ + .InsertBehavior(Of DefaultValueBehavior)(0) + Dim fromRef As ICalculator = reference.ToObject() + Dim existing As StuntReference(Of ICalculator) = Stunt.Get(direct) + Dim builder As StuntBuilder = Stunt.Builder() _ + .AddBehavior(Of DefaultValueBehavior)() _ + .InsertBehavior(Of DefaultValueBehavior)(0) + Dim built As ICalculator = builder.Build(Of ICalculator)() + Dim adderDelegate As Adder = Stunt.Of(Of Adder)(Function(x, y) x + y) + Dim builtDelegate As Adder = builder.Build(Of Adder)(Function(x, y) x + y) + GC.KeepAlive(withExtra) + GC.KeepAlive(fromRef) + GC.KeepAlive(existing) + GC.KeepAlive(built) + GC.KeepAlive(adderDelegate) + GC.KeepAlive(builtDelegate) + End Sub + End Class + """; + + var symbols = net5OrGreater + ? new[] { new KeyValuePair("NET5_0_OR_GREATER", true) } + : Array.Empty>(); + var parseOptions = VisualBasicParseOptions.Default + .WithLanguageVersion(Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest) + .WithPreprocessorSymbols(symbols); + + var trees = new[] + { + VisualBasicSyntaxTree.ParseText(File.ReadAllText(stuntVbPath), parseOptions, path: "Stunt.vb"), + VisualBasicSyntaxTree.ParseText(File.ReadAllText(dynamicFactoryVbPath), parseOptions, path: "Stunt.DynamicFactory.vb"), + VisualBasicSyntaxTree.ParseText(consumerVb, parseOptions, path: "Consumer.vb"), + }; + + var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + var references = tpa.Select(p => MetadataReference.CreateFromFile(p)).ToArray(); + + var compilation = VisualBasicCompilation.Create( + "StuntsVbCheck_" + (net5OrGreater ? "Net" : "Legacy"), + trees, + references, + new VisualBasicCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + optionExplicit: true, + optionInfer: true, + optionStrict: OptionStrict.On)); + + using var stream = new MemoryStream(); + var emit = compilation.Emit(stream); + var errorsAndWarnings = compilation.GetDiagnostics() + .Where(d => d.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning) + .ToList(); + + Assert.True(emit.Success, string.Join(Environment.NewLine, emit.Diagnostics)); + Assert.Empty(errorsAndWarnings); + } + + static (int ExitCode, string Output) RunMSBuild(string projectPath, string target, Dictionary properties) + { + var args = new StringBuilder(); + args.Append("msbuild \"").Append(projectPath).Append("\" -nologo -noAutoResponse -t:").Append(target); + foreach (var pair in properties) + args.Append(" -p:").Append(pair.Key).Append('=').Append(pair.Value); + + var psi = new ProcessStartInfo("dotnet", args.ToString()) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + + using var process = Process.Start(psi)!; + var stdout = process.StandardOutput.ReadToEnd(); + var stderr = process.StandardError.ReadToEnd(); + Assert.True(process.WaitForExit(30_000), "dotnet msbuild timed out"); + return (process.ExitCode, stdout + Environment.NewLine + stderr); + } + + static CSharpCommandLineArguments CompilerArguments() + => CSharpCommandLineParser.Default.Parse( + File.ReadAllLines("csc.txt"), + ThisAssembly.Project.MSBuildProjectDirectory, + sdkDirectory: null); + + static CSharpParseOptions ParseOptions() + => ((CSharpParseOptions)CompilerArguments().ParseOptions) + .WithLanguageVersion(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest) + .WithFeatures(Enumerable.Empty>()); + + static AnalyzerConfigOptionsProvider DefaultOptionsProvider() + => EditorConfigOptionsProvider.Create(Directory.EnumerateFiles( + Path.Combine(ThisAssembly.Project.MSBuildProjectDirectory, ThisAssembly.Project.IntermediateOutputPath), + "*.editorconfig", SearchOption.TopDirectoryOnly)); + + static CSharpCompilation CreateCompilation( + string assemblyName, + CSharpParseOptions parseOptions, + bool includeStuntsSources, + params SyntaxTree[] extraTrees) + { + var args = CompilerArguments(); + var libs = new HashSet(File.ReadAllLines("lib.txt"), StringComparer.OrdinalIgnoreCase) + .Distinct(FileNameEqualityComparer.Default) + .ToDictionary(x => Path.GetFileName(x)); + + var metadata = args.MetadataReferences + .Select(x => libs.TryGetValue(Path.GetFileName(x.Reference), out var lib) + ? MetadataReference.CreateFromFile(lib) + : MetadataReference.CreateFromFile(x.Reference)) + .ToArray(); + + var sources = new List(); + if (includeStuntsSources) + { + sources.Add(CSharpSyntaxTree.ParseText(File.ReadAllText("Stunt/Stunt.cs"), parseOptions, path: "Stunt.cs", encoding: Encoding.UTF8)); + sources.Add(CSharpSyntaxTree.ParseText(File.ReadAllText("Stunt/Stunt.StaticFactory.cs"), parseOptions, path: "Stunt.StaticFactory.cs", encoding: Encoding.UTF8)); + } + sources.AddRange(extraTrees); + + return CSharpCompilation.Create( + assemblyName, + sources, + metadata, + args.CompilationOptions.WithCryptoKeyFile(null).WithOutputKind(OutputKind.DynamicallyLinkedLibrary)); + } + + static async Task> RunAnalyzerAsync( + string source, + DiagnosticAnalyzer analyzer, + Dictionary? properties = null) + { + var parseOptions = ParseOptions(); + var compilation = CreateCompilation( + "ST013AnalyzerTest", + parseOptions, + includeStuntsSources: true, + CSharpSyntaxTree.ParseText(source, parseOptions, path: "Test.cs", encoding: Encoding.UTF8)); + + AnalyzerConfigOptionsProvider optionsProvider = DefaultOptionsProvider(); + if (properties != null) + optionsProvider = new OverrideOptionsProvider(optionsProvider, properties); + + var withAnalyzers = compilation.WithAnalyzers( + ImmutableArray.Create(analyzer), + new AnalyzerOptions(ImmutableArray.Empty, optionsProvider)); + return await withAnalyzers.GetAnalyzerDiagnosticsAsync(); + } + + sealed class OverrideOptionsProvider : AnalyzerConfigOptionsProvider + { + readonly AnalyzerConfigOptionsProvider inner; + readonly AnalyzerConfigOptions globalOptions; + + public OverrideOptionsProvider(AnalyzerConfigOptionsProvider inner, Dictionary overrides) + { + this.inner = inner; + globalOptions = new OverrideOptions(inner.GlobalOptions, overrides); + } + + public override AnalyzerConfigOptions GlobalOptions => globalOptions; + public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => inner.GetOptions(tree); + public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => inner.GetOptions(textFile); + + sealed class OverrideOptions : AnalyzerConfigOptions + { + readonly AnalyzerConfigOptions inner; + readonly Dictionary overrides; + + public OverrideOptions(AnalyzerConfigOptions inner, Dictionary overrides) + => (this.inner, this.overrides) = (inner, overrides); + + public override bool TryGetValue(string key, out string value) + { + if (overrides.TryGetValue(key, out value!)) + return true; + return inner.TryGetValue(key, out value!); + } + } + } + + [AttributeUsage(AttributeTargets.Method)] + sealed class MissingFromCompilationGeneratorAttribute : Attribute { } + } +} diff --git a/src/Stunts.UnitTests/StuntCacheTests.cs b/src/Stunts.UnitTests/StuntCacheTests.cs index f3104e3d..26d72ded 100644 --- a/src/Stunts.UnitTests/StuntCacheTests.cs +++ b/src/Stunts.UnitTests/StuntCacheTests.cs @@ -276,6 +276,116 @@ public void RejectsDamagedEntries() Assert.Null(StuntCacheEntry.Read("garbage")); } + [Fact] + public void InvalidatesOnCompilationOptionChanges() + { + Generate(Calculator("int"), languageVersion: LanguageVersion.CSharp13, nullable: NullableContextOptions.Enable, allowUnsafe: true); + Assert.NotEqual(0, MarkEntries()); + + // Same compilation options hit the cache. + Assert.Contains(Marker, Stunt( + Generate(Calculator("int"), languageVersion: LanguageVersion.CSharp13, nullable: NullableContextOptions.Enable, allowUnsafe: true).Compilation, + "ICalculatorStunt")); + + // Changing LanguageVersion misses the cache. + Assert.DoesNotContain(Marker, Stunt( + Generate(Calculator("int"), languageVersion: LanguageVersion.CSharp12, nullable: NullableContextOptions.Enable, allowUnsafe: true).Compilation, + "ICalculatorStunt")); + + // Changing NullableContextOptions misses the cache. + Assert.DoesNotContain(Marker, Stunt( + Generate(Calculator("int"), languageVersion: LanguageVersion.CSharp13, nullable: NullableContextOptions.Disable, allowUnsafe: true).Compilation, + "ICalculatorStunt")); + + // Changing AllowUnsafeBlocks misses the cache. + Assert.DoesNotContain(Marker, Stunt( + Generate(Calculator("int"), languageVersion: LanguageVersion.CSharp13, nullable: NullableContextOptions.Enable, allowUnsafe: false).Compilation, + "ICalculatorStunt")); + } + + [Fact] + public void PrunesStaleEntriesTemporaryFilesAndOldVersionFolders() + { + var currentVersion = "v-current"; + var currentDir = Path.Combine(cacheDir, currentVersion); + var oldVersionDir = Path.Combine(cacheDir, "v-old"); + var recentVersionDir = Path.Combine(cacheDir, "v-recent"); + Directory.CreateDirectory(currentDir); + Directory.CreateDirectory(oldVersionDir); + Directory.CreateDirectory(recentVersionDir); + + var staleEntry = Path.Combine(currentDir, "stale.stunt"); + var freshEntry = Path.Combine(currentDir, "fresh.stunt"); + var staleTemp = Path.Combine(currentDir, "leftover.tmp"); + var freshTemp = Path.Combine(currentDir, "inflight.tmp"); + var oldVersionFile = Path.Combine(oldVersionDir, "old.stunt"); + var recentVersionFile = Path.Combine(recentVersionDir, "recent.stunt"); + + var validText = new StuntCacheEntry(StuntCacheFlags.None, Array.Empty(), "class Cached { }").Write(); + File.WriteAllText(staleEntry, validText); + File.WriteAllText(freshEntry, validText); + File.WriteAllText(staleTemp, "tmp"); + File.WriteAllText(freshTemp, "tmp"); + File.WriteAllText(oldVersionFile, validText); + File.WriteAllText(recentVersionFile, validText); + + var now = DateTime.UtcNow; + File.SetLastWriteTimeUtc(staleEntry, now.AddDays(-35)); + File.SetLastWriteTimeUtc(staleTemp, now.AddDays(-2)); + File.SetLastWriteTimeUtc(oldVersionFile, now.AddDays(-10)); + Directory.SetLastWriteTimeUtc(oldVersionDir, now.AddDays(-10)); + + var options = new PropertiesProvider( + EditorConfigOptionsProvider.Create(Array.Empty()), + new Dictionary { [BuildProperties.Name.StuntsCacheDir] = cacheDir }).GlobalOptions; + + var cache = StuntCache.Create(options, currentVersion); + + Assert.NotNull(cache); + Assert.True(File.Exists(Path.Combine(cacheDir, ".pruned"))); + Assert.False(File.Exists(staleEntry)); + Assert.False(File.Exists(staleTemp)); + Assert.False(Directory.Exists(oldVersionDir)); + Assert.True(File.Exists(freshEntry)); + Assert.True(File.Exists(freshTemp)); + Assert.True(Directory.Exists(recentVersionDir)); + Assert.True(File.Exists(recentVersionFile)); + } + + [Fact] + public void HandlesConcurrentReadsAndWritesSafely() + { + var options = new PropertiesProvider( + EditorConfigOptionsProvider.Create(Array.Empty()), + new Dictionary { [BuildProperties.Name.StuntsCacheDir] = cacheDir }).GlobalOptions; + var cache = StuntCache.Create(options, "v-concurrent")!; + StuntCache.ClearMemory(); + + System.Threading.Tasks.Parallel.For(0, 32, i => + { + var sharedKey = "shared-" + (i % 4); + var uniqueKey = "unique-" + i; + var sharedEntry = new StuntCacheEntry(StuntCacheFlags.None, Array.Empty(), "// shared " + (i % 4)); + var uniqueEntry = new StuntCacheEntry(StuntCacheFlags.None, Array.Empty(), "// unique " + i); + + cache.Add(sharedKey, sharedEntry); + cache.Add(uniqueKey, uniqueEntry); + + var readShared = cache.Get(sharedKey); + var readUnique = cache.Get(uniqueKey); + + Assert.NotNull(readShared); + Assert.Equal(sharedEntry.Code, readShared!.Code); + Assert.NotNull(readUnique); + Assert.Equal(uniqueEntry.Code, readUnique!.Code); + }); + + // All entries are persisted cleanly with no orphaned temporary files. + var versionDir = Path.Combine(cacheDir, "v-concurrent"); + Assert.Empty(Directory.GetFiles(versionDir, "*.tmp")); + Assert.Equal(36, Directory.GetFiles(versionDir, "*.stunt").Length); + } + static string Calculator(string type) => $$""" using Stunts; public interface ICalculator { {{type}} Add(int x, int y); } @@ -334,9 +444,22 @@ static MetadataReference Library(string name, string source) } (ImmutableArray Diagnostics, Compilation Compilation) Generate(string source, string? assemblyName = null, - MetadataReference? reference = null, bool aot = false, bool cache = true, StuntGenerator? generator = null, [CallerMemberName] string? test = null) + MetadataReference? reference = null, bool aot = false, bool cache = true, StuntGenerator? generator = null, + LanguageVersion? languageVersion = null, NullableContextOptions? nullable = null, bool? allowUnsafe = null, + [CallerMemberName] string? test = null) { var parseOptions = ParseOptions(); + if (languageVersion.HasValue) + parseOptions = parseOptions.WithLanguageVersion(languageVersion.Value); + + var compilationOptions = CompilerArguments().CompilationOptions + .WithCryptoKeyFile(null) + .WithOutputKind(OutputKind.DynamicallyLinkedLibrary); + if (nullable.HasValue) + compilationOptions = compilationOptions.WithNullableContextOptions(nullable.Value); + if (allowUnsafe.HasValue) + compilationOptions = compilationOptions.WithAllowUnsafe(allowUnsafe.Value); + var compilation = CSharpCompilation.Create( assemblyName ?? test, new[] @@ -346,7 +469,7 @@ static MetadataReference Library(string name, string source) CSharpSyntaxTree.ParseText(File.ReadAllText("Stunt/Stunt.StaticFactory.cs"), parseOptions, path: "Stunt.StaticFactory.cs", encoding: Encoding.UTF8), }, reference == null ? References() : References().Append(reference), - CompilerArguments().CompilationOptions.WithCryptoKeyFile(null).WithOutputKind(OutputKind.DynamicallyLinkedLibrary)); + compilationOptions); var properties = new Dictionary(); if (cache) diff --git a/src/Stunts.UnitTests/StuntFactoryTests.cs b/src/Stunts.UnitTests/StuntFactoryTests.cs index e17f7404..4927e77d 100644 --- a/src/Stunts.UnitTests/StuntFactoryTests.cs +++ b/src/Stunts.UnitTests/StuntFactoryTests.cs @@ -49,19 +49,22 @@ public async Task ReplaceFactoryLocally() { var factory1 = new TestFactory(new object()); var factory2 = new TestFactory(new object()); + using var barrier = new Barrier(2); await Task.WhenAll( Task.Run(() => { StuntFactory.LocalDefault = factory1; - Thread.Sleep(50); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); Assert.Same(factory1, StuntFactory.Default); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); }), Task.Run(() => { StuntFactory.LocalDefault = factory2; - Thread.Sleep(50); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); Assert.Same(factory2, StuntFactory.Default); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); }) ); diff --git a/src/Stunts.UnitTests/Stunts.UnitTests.csproj b/src/Stunts.UnitTests/Stunts.UnitTests.csproj index 3e2a1313..04a66366 100644 --- a/src/Stunts.UnitTests/Stunts.UnitTests.csproj +++ b/src/Stunts.UnitTests/Stunts.UnitTests.csproj @@ -1,9 +1,7 @@ -ο»Ώ + net10.0 - annotations true @@ -42,7 +40,6 @@ - @@ -52,8 +49,7 @@ - - + From fcc928e4a7f05651a6295394e546be56697ed346 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 17:57:11 -0300 Subject: [PATCH 2/5] Fix samples NuGet restore on clean runners Declare nuget.org explicitly with in samples/nuget.config and remove the project-level RestoreSources override from Samples.csproj so third-party packages resolve from nuget.org while Stunts* packages resolve from the local bin feed. Co-authored-by: CodeAlta --- samples/Samples/Samples.csproj | 1 - samples/nuget.config | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/samples/Samples/Samples.csproj b/samples/Samples/Samples.csproj index 65eac5fe..16c25bba 100644 --- a/samples/Samples/Samples.csproj +++ b/samples/Samples/Samples.csproj @@ -4,7 +4,6 @@ net10.0 enable false - $(MSBuildProjectDirectory)\..\..\bin diff --git a/samples/nuget.config b/samples/nuget.config index 3a972258..19b2dec3 100644 --- a/samples/nuget.config +++ b/samples/nuget.config @@ -1,9 +1,13 @@ + + + + From bb7fc226bd980b282441dc95c9939a94a921eba3 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 18:02:35 -0300 Subject: [PATCH 3/5] Raise Roslyn test compilation and emit timeouts to avoid CI flakes WorkspaceHelper.Emit used a 10s CancellationTokenSource (and Scenarios, ManualStunts, and AssertCode used 1s-5s timeouts) which could fire under parallel test CPU contention on CI runners. Increase those timeouts to 60s (30s for syntax root) and dispose the CancellationTokenSource. Co-authored-by: CodeAlta --- src/Stunts.UnitTests/.Scenarios.cs | 3 ++- .../CodeAnalysis/Helpers/AssertCode.cs | 14 +++++++------- .../CodeAnalysis/Helpers/WorkspaceHelper.cs | 4 ++-- src/Stunts.UnitTests/ManualStunts.cs | 3 ++- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/Stunts.UnitTests/.Scenarios.cs b/src/Stunts.UnitTests/.Scenarios.cs index c7d6af09..abf06291 100644 --- a/src/Stunts.UnitTests/.Scenarios.cs +++ b/src/Stunts.UnitTests/.Scenarios.cs @@ -175,7 +175,8 @@ static Scenarios() "*.editorconfig", SearchOption.TopDirectoryOnly))); // Don't timeout if we're debugging. - var token = Debugger.IsAttached ? default : new CancellationTokenSource(5000).Token; + using var cts = Debugger.IsAttached ? null : new CancellationTokenSource(TimeSpan.FromSeconds(60)); + var token = cts?.Token ?? CancellationToken.None; driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out var diagnostics, token); diagnostics = output.GetDiagnostics().RemoveAll(ignored).RemoveAll(d => d.Severity != DiagnosticSeverity.Error); diff --git a/src/Stunts.UnitTests/CodeAnalysis/Helpers/AssertCode.cs b/src/Stunts.UnitTests/CodeAnalysis/Helpers/AssertCode.cs index 86d6a988..e1d09fd5 100644 --- a/src/Stunts.UnitTests/CodeAnalysis/Helpers/AssertCode.cs +++ b/src/Stunts.UnitTests/CodeAnalysis/Helpers/AssertCode.cs @@ -1,4 +1,4 @@ -ο»Ώusing System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -64,29 +64,29 @@ public static void Compiles(SyntaxNode proxyCode) public static async Task NoErrorsAsync(Document document) { - var compilation = await document.Project.GetCompilationAsync(TimeoutToken(5)) + var compilation = await document.Project.GetCompilationAsync(TimeoutToken(60)) ?? throw new XunitException("Unexpected null."); var noWarn = new HashSet { //"CS1701", // fusion reference mismatch, binding redirect required. }; - var diagnostics = compilation.GetDiagnostics(TimeoutToken(5)).Where(d => !noWarn.Contains(d.Id)).ToArray(); + var diagnostics = compilation.GetDiagnostics(TimeoutToken(60)).Where(d => !noWarn.Contains(d.Id)).ToArray(); if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)) { SyntaxNode syntax; try { // Attempt to normalize whitespace and get the errors again, so the code is more legible - syntax = await document.GetSyntaxRootAsync(TimeoutToken(1)) ?? throw new XunitException("Unexpected null."); + syntax = await document.GetSyntaxRootAsync(TimeoutToken(30)) ?? throw new XunitException("Unexpected null."); syntax = syntax.NormalizeWhitespace(); document = document.WithSyntaxRoot(syntax); - compilation = await document.Project.GetCompilationAsync(TimeoutToken(5)) ?? throw new XunitException("Unexpected null."); - diagnostics = compilation.GetDiagnostics(TimeoutToken(5)).Where(d => !noWarn.Contains(d.Id)).ToArray(); + compilation = await document.Project.GetCompilationAsync(TimeoutToken(60)) ?? throw new XunitException("Unexpected null."); + diagnostics = compilation.GetDiagnostics(TimeoutToken(60)).Where(d => !noWarn.Contains(d.Id)).ToArray(); } catch { - syntax = await document.GetSyntaxRootAsync(TimeoutToken(1)) ?? throw new XunitException("Unexpected null."); + syntax = await document.GetSyntaxRootAsync(TimeoutToken(30)) ?? throw new XunitException("Unexpected null."); } if (!string.IsNullOrEmpty(document.FilePath)) diff --git a/src/Stunts.UnitTests/CodeAnalysis/Helpers/WorkspaceHelper.cs b/src/Stunts.UnitTests/CodeAnalysis/Helpers/WorkspaceHelper.cs index f150a92a..7d2dd0c0 100644 --- a/src/Stunts.UnitTests/CodeAnalysis/Helpers/WorkspaceHelper.cs +++ b/src/Stunts.UnitTests/CodeAnalysis/Helpers/WorkspaceHelper.cs @@ -100,10 +100,10 @@ public static Assembly Emit(this Compilation compilation, bool symbols = true) new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded) : new EmitOptions(); - var cts = new CancellationTokenSource(10000); + using var cts = Debugger.IsAttached ? null : new CancellationTokenSource(TimeSpan.FromSeconds(60)); var result = compilation.Emit(stream, options: options, - cancellationToken: cts.Token); + cancellationToken: cts?.Token ?? CancellationToken.None); result.AssertSuccess(); diff --git a/src/Stunts.UnitTests/ManualStunts.cs b/src/Stunts.UnitTests/ManualStunts.cs index f66f31a8..f057d07b 100644 --- a/src/Stunts.UnitTests/ManualStunts.cs +++ b/src/Stunts.UnitTests/ManualStunts.cs @@ -120,7 +120,8 @@ public void Do() optionsProvider: options); // Don't timeout if we're debugging. - var token = Debugger.IsAttached ? default : new CancellationTokenSource(5000).Token; + using var cts = Debugger.IsAttached ? null : new CancellationTokenSource(TimeSpan.FromSeconds(60)); + var token = cts?.Token ?? CancellationToken.None; driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out diagnostics, token); diagnostics = diagnostics.RemoveAll(ignored); From 23a9760492e63cbbcb566f79e07d1927a9efa215 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 18:08:20 -0300 Subject: [PATCH 4/5] Raise synchronization test wait timeouts to avoid CI thread-pool flakes SynchronizedBehavior scenario waits and ambient Barrier waits used 2s-5s timeouts, which could time out when Roslyn compilation tests running in parallel starved the thread pool on CI runners. Use 30s timeouts. Co-authored-by: CodeAlta --- src/Stunts.UnitTests/BehaviorPipelineTests.cs | 8 +++--- .../Scenarios/SynchronizedBehavior.cs | 26 ++++++++++--------- src/Stunts.UnitTests/StuntFactoryTests.cs | 8 +++--- 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/Stunts.UnitTests/BehaviorPipelineTests.cs b/src/Stunts.UnitTests/BehaviorPipelineTests.cs index 3d87a8f1..bbb57d5c 100644 --- a/src/Stunts.UnitTests/BehaviorPipelineTests.cs +++ b/src/Stunts.UnitTests/BehaviorPipelineTests.cs @@ -380,16 +380,16 @@ await Task.WhenAll( Task.Run(() => { using var ambient = BehaviorPipelineFactory.UseAmbient(factory1); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); Assert.Same(factory1, BehaviorPipelineFactory.Default); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); }), Task.Run(() => { using var ambient = BehaviorPipelineFactory.UseAmbient(factory2); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); Assert.Same(factory2, BehaviorPipelineFactory.Default); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); }) ); diff --git a/src/Stunts.UnitTests/Scenarios/SynchronizedBehavior.cs b/src/Stunts.UnitTests/Scenarios/SynchronizedBehavior.cs index eb7bee9c..0cb6a149 100644 --- a/src/Stunts.UnitTests/Scenarios/SynchronizedBehavior.cs +++ b/src/Stunts.UnitTests/Scenarios/SynchronizedBehavior.cs @@ -13,6 +13,8 @@ namespace Stunts.UnitTests /// public class SynchronizedBehaviorTests : IRunnable { + static readonly TimeSpan WaitTimeout = TimeSpan.FromSeconds(30); + public void Run() { OverlappingSyncCalls_RunOneAtATime(); @@ -186,17 +188,17 @@ public void SyncRootIsNotLocked() lock (root) { held.Set(); - Assert.True(leave.Wait(TimeSpan.FromSeconds(5))); + Assert.True(leave.Wait(WaitTimeout)); } }); - Assert.True(held.Wait(TimeSpan.FromSeconds(5))); + Assert.True(held.Wait(WaitTimeout)); var worker = Create(new SynchronizedBehavior(root), new Script(invocation => invocation.CreateValueReturn(1))); var call = Dedicated(() => worker.Work(1)); - Assert.True(call.Wait(TimeSpan.FromSeconds(2)), "The call blocked on the caller's sync root."); + Assert.True(call.Wait(WaitTimeout), "The call blocked on the caller's sync root."); leave.Set(); - Assert.True(external.Wait(TimeSpan.FromSeconds(5))); + Assert.True(external.Wait(WaitTimeout)); Assert.Equal(1, call.Result); Assert.Throws("syncRoot", () => new SynchronizedBehavior(null!)); } @@ -236,9 +238,9 @@ static void Exclude(Func> call, IWorker firstWorker, IWorker using var start = new Barrier(3); var first = Start(start, firstWorker, call); var second = Start(start, secondWorker, call); - Assert.True(start.SignalAndWait(5000)); + Assert.True(start.SignalAndWait(WaitTimeout)); - Assert.True(target.FirstEntered.Task.Wait(TimeSpan.FromSeconds(5))); + Assert.True(target.FirstEntered.Task.Wait(WaitTimeout)); Assert.False(target.SecondEntered.Task.Wait(TimeSpan.FromMilliseconds(200))); Assert.Equal(1, target.Entered); @@ -252,10 +254,10 @@ static void Overlap(Func> call, IWorker firstWorker, IWorker using var start = new Barrier(3); var first = Start(start, firstWorker, call); var second = Start(start, secondWorker, call); - Assert.True(start.SignalAndWait(5000)); + Assert.True(start.SignalAndWait(WaitTimeout)); - Assert.True(target.FirstEntered.Task.Wait(TimeSpan.FromSeconds(5))); - Assert.True(target.SecondEntered.Task.Wait(TimeSpan.FromSeconds(5))); + Assert.True(target.FirstEntered.Task.Wait(WaitTimeout)); + Assert.True(target.SecondEntered.Task.Wait(WaitTimeout)); Assert.Equal(2, target.Entered); target.Release(7); @@ -266,7 +268,7 @@ static void Overlap(Func> call, IWorker firstWorker, IWorker static Task Start(Barrier start, IWorker worker, Func> call) => Dedicated(() => { - Assert.True(start.SignalAndWait(5000)); + Assert.True(start.SignalAndWait(WaitTimeout)); return call(worker); }).Unwrap(); @@ -280,7 +282,7 @@ static Task Dedicated(Func func) static int Finish(Task task) { - Assert.True(task.Wait(TimeSpan.FromSeconds(5)), "Timed out waiting for the call to finish."); + Assert.True(task.Wait(WaitTimeout), "Timed out waiting for the call to finish."); return task.Result; } @@ -324,7 +326,7 @@ public IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next) if (name == nameof(IWorker.WorkValueAsync)) return invocation.CreateValueReturn(new ValueTask(result.Task)); - if (!result.Task.Wait(TimeSpan.FromSeconds(5))) + if (!result.Task.Wait(WaitTimeout)) throw new TimeoutException("The synchronized call was not released."); return invocation.CreateValueReturn(result.Task.Result); diff --git a/src/Stunts.UnitTests/StuntFactoryTests.cs b/src/Stunts.UnitTests/StuntFactoryTests.cs index 4927e77d..b9e52065 100644 --- a/src/Stunts.UnitTests/StuntFactoryTests.cs +++ b/src/Stunts.UnitTests/StuntFactoryTests.cs @@ -55,16 +55,16 @@ await Task.WhenAll( Task.Run(() => { StuntFactory.LocalDefault = factory1; - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); Assert.Same(factory1, StuntFactory.Default); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); }), Task.Run(() => { StuntFactory.LocalDefault = factory2; - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); Assert.Same(factory2, StuntFactory.Default); - Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(5))); + Assert.True(barrier.SignalAndWait(TimeSpan.FromSeconds(30))); }) ); From a9c08912fcf794fc7bcb1c02247f098669610b58 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sun, 29 Nov 2026 18:18:39 -0300 Subject: [PATCH 5/5] Preserve native-aot check names on ubuntu-latest for branch ruleset Keep Ubuntu Native AOT job names as native-aot-net8.0 and native-aot-net10.0 so the main branch ruleset required check (native-aot-net10.0) continues to match while Windows runs as native-aot-windows-net8.0 and native-aot-windows-net10.0. Co-authored-by: CodeAlta --- .github/workflows/build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a435ac6e..e3923e56 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -80,7 +80,7 @@ jobs: sleet push bin --config none -f --verbose -p "SLEET_FEED_CONTAINER=nuget" -p "SLEET_FEED_CONNECTIONSTRING=$SLEET_CONNECTION" -p "SLEET_FEED_TYPE=azure" || echo "No packages found" native-aot: - name: native-aot-${{ matrix.os }}-${{ matrix.framework }} + name: ${{ matrix.prefix }}-${{ matrix.framework }} runs-on: ${{ matrix.os }} needs: build strategy: @@ -89,9 +89,11 @@ jobs: framework: [net8.0, net10.0] include: - os: ubuntu-latest + prefix: native-aot rid: linux-x64 exe: CompiledAot - os: windows-latest + prefix: native-aot-windows rid: win-x64 exe: CompiledAot.exe steps: