ANcpLua.Roslyn.Utilities.Testing
5.0.0
See the version list below for details.
dotnet add package ANcpLua.Roslyn.Utilities.Testing --version 5.0.0
NuGet\Install-Package ANcpLua.Roslyn.Utilities.Testing -Version 5.0.0
<PackageReference Include="ANcpLua.Roslyn.Utilities.Testing" Version="5.0.0" />
<PackageVersion Include="ANcpLua.Roslyn.Utilities.Testing" Version="5.0.0" />
<PackageReference Include="ANcpLua.Roslyn.Utilities.Testing" />
paket add ANcpLua.Roslyn.Utilities.Testing --version 5.0.0
#r "nuget: ANcpLua.Roslyn.Utilities.Testing, 5.0.0"
#:package ANcpLua.Roslyn.Utilities.Testing@5.0.0
#addin nuget:?package=ANcpLua.Roslyn.Utilities.Testing&version=5.0.0
#tool nuget:?package=ANcpLua.Roslyn.Utilities.Testing&version=5.0.0
ANcpLua.Roslyn.Utilities
A focused utility library for writing Roslyn source generators, analyzers, and code-fix providers. The shape is opinionated: the types here are the ones that make an incremental generator actually cache, a symbol comparison actually readable, and a code emission actually deterministic.
Agent test doubles, MAF conformance suites, and workflow fixtures live in the sibling ANcpLua.Agents package. This repo focuses on Roslyn/MSBuild/OTel-for-analyzer-authors.
The library is the author's own. Use it, improve it (the upstream is this repo), or propose switching directions — don't reinvent locally.
Packages
| Package | Target | What it's for |
|---|---|---|
ANcpLua.Roslyn.Utilities |
netstandard2.0 | Runtime + Roslyn utilities as a normal NuGet reference |
ANcpLua.Roslyn.Utilities.Sources |
source-only | Embeds the utilities as internal source into source generators (generators can't load NuGet DLLs at runtime) |
ANcpLua.Roslyn.Utilities.Polyfills |
source-only | init, required, C# 15 union, Index/Range, nullable & trim attributes for netstandard2.0 |
ANcpLua.Roslyn.Utilities.Testing |
net11.0 | Framework-independent generator/analyzer/codefix test infrastructure and diagnostics helpers |
ANcpLua.Roslyn.Utilities.Testing.Aot |
netstandard2.0 | AOT/trim test attributes ([AotTest], [TrimTest], [AotSafe], [TrimSafe]), TrimAssert, FeatureSwitches, MSBuild orchestration for standalone AOT verification |
The packages are built with the .NET 11 SDK and compiled against Microsoft.CodeAnalysis 5.12 (C# 15). An analyzer or generator that references the ANcpLua.Roslyn.Utilities assembly therefore needs a Roslyn 5.12 host (.NET SDK 11.0.100 or later); the .Sources package still compiles against Microsoft.CodeAnalysis 4.14 and later.
Quickstart — writing a source generator
dotnet add package ANcpLua.Roslyn.Utilities.Sources
A canonical incremental generator is ~25 lines when the utilities do their job — see src/ANcpLua.AotReflection/AotReflectionGenerator.cs in this repo for the reference shape:
[Generator]
public sealed class MyGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var flows = context.SyntaxProvider.ForAttributeWithMetadataName(
"MyNamespace.TracedAttribute",
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, ct) => TypeExtractor.Extract(ctx, ct));
var types = flows.ReportAndStop(context);
var files = types
.Select(static (m, _) => OutputGenerator.Generate(m))
.CollectAsEquatableArray();
files.AddSources(context);
}
}
What the library provides at each step:
ForAttributeWithMetadataName— filter syntax before expensive semantic work (Roslyn built-in; the library wraps for ergonomics)DiagnosticFlow<T>— railway-oriented pipeline carrying value + accumulated diagnostics, value-equatable for incremental cachingReportAndStop— drain the flow intoReportDiagnosticand yield valuesCollectAsEquatableArray/ToEquatableArray/ToEquatableArrayOrDefault— value-equatable collections so the generator cache actually hitsAddSources— emitFileWithNamerecords without boilerplateMatch.Type()/Match.Method()— fluent symbol matching, no string comparisonsIndentedStringBuilder—BeginBlock()/EndBlock()scopes, no hardcoded indentation stringsGeneratedCodeHelpers—<auto-generated/>headers,#nullable enable, pragma helpers
Testing an agent or a MAF workflow
Agent test doubles (FakeChatClient, FakeReplayAgent, ActivityCollector), the provider-agnostic MAF conformance suite (RunTests, RunStreamingTests, ChatClientAgentRunTests, StructuredOutputRunTests), reference fixtures for OpenAI / Azure / Anthropic / Ollama / Gemini / OpenRouter, and the WorkflowFixture<TInput> harness ship in the sibling ANcpLua.Agents package.
What's in the box
Incremental pipeline (generator authors)
DiagnosticFlow<T>+DiagnosticFlowReportingExtensions— railway-oriented flow with value + accumulatedDiagnosticInfoIncrementalValuesProviderExtensions—ReportAndStop,CollectAsEquatableArray,AddSources, and other pipeline verbsSyntaxValueProviderExtensions— ergonomicForAttributeWithMetadataNamewrappersSourceProductionContextExtensions— context helpersEquatableArray<T>+EquatableArrayExtensions(.ToEquatableArray,.ToEquatableArrayOrDefault,.AsEquatableArray) — value equality so the cache actually hitsFileWithName— record for emitted-file payloadDiagnosticInfo+LocationInfo+EquatableMessageArgs— value-equatable diagnostic carriers;IsDefault/IsErrorpredicates let pipeline code skip default sentinels at the boundary instead of NRE'ing inside Roslyn.ToDiagnostic(SyntaxTree?)/ToLocation(SyntaxTree?)rebind the recreatedLocationto a live syntax tree (IDE navigation + squiggles), falling back to the path-based form when the tree is absent or has changed shape.TypeDeclarationInfo+ContainingTypeInfo— cacheable, value-equatable snapshot of a type declaration: namespace, keyword (class/struct/record/record struct/interface), generic clause,partial-ness, and the containing-type chain as per-level declarations — so emitting into a type nested inside a generic orstructcontainer actually compiles (a name-only chain can't get this right).From(INamedTypeSymbol)snapshots in the transform stage;BeginDeclaration(IndentedStringBuilder)emits the full nestedpartialwrapper as a disposable scope;IsFullyPartialis the diagnostic gate before emission;GetHintName()yields the deterministicAddSourcefile name — namespace +--joined nesting chain +(N)arity markers, e.g.Deep.Outer(1)-Middle-Inner(1).g.cs; both markers are characters no identifier can contain, so generic overloads (ResultvsResult<T>), identifier forgeries (Result_1), and namespace-vs-nesting layouts (A.B-CvsA.B.C) never collide.GetFullyQualifiedMetadataName()closes the round-trip (Deep.Outer`1+Middle+Inner`1forCompilation.GetTypeByMetadataNamein later stages), andGetFullyQualifiedName()yields theglobal::Deep.Outer<T>.Middle.Inner<U>reference for emitting self-references inside the generated partial.ResultWithDiagnostics<T>— result payload paired with diagnostics, withHasResultdistinguishing a successfulnullfrom a no-result envelope. Pair withSelectAndCaptureExceptions(side-effect-free) orSelectAndReportExceptions(chains capture + register-source-output) onIncrementalValuesProviderExtensions.
Symbol analysis & matching
Matchfluent DSL —Match.Type()/Match.Method()/Match.Property()/Match.Field()/Match.Parameter()with the per-kind matchers underMatching/(MethodMatcher,TypeMatcher, etc.)Invoke/InvocationMatcher— invocation-shape matchingSymbolExtensions,TypeSymbolExtensions,MethodSymbolExtensions,NamespaceExtensions—IsEqualTo,Implements,InheritsFrom,IsOrImplements,GetMetadataName(overloaded for type and namespace symbols), and the usual suspects. Symbol identity beatsToDisplayString()for predicate hot paths — seeIsSpanType/IsMemoryType/IsTaskTypefor the pattern.AttributeExtensions—GetAttribute,HasAttribute,TryGetAttributewith constructor-arg accessorsInvocationExtensions/OperationExtensions/OperationHelper—IInvocationOperationanalysis helpersSemanticGuard<T>+SemanticGuard— chain semantic predicates with early-exitSemanticModelExtensions/CompilationExtensions/SyntaxExtensions
Code emission
IndentedStringBuilder+IndentScope—BeginBlock()/EndBlock()scopes, no hardcoded indentationGeneratedCodeHelpers—<auto-generated/>header, nullable/pragma directivesValueStringBuilder— stack-allocatedStringBuilderfor hot pathsSyntaxBuilders(Analyzers/) — fluent builders for common code-fix patterns (ExtensionCall,StaticCall,NameOf)
Analyzer authoring
Reusable infrastructure for writing analyzers and code fixes — concrete rules (e.g. AL1313) intentionally ship in ANcpLua.Analyzers.
DiagnosticAnalyzerBase— convention base classDiagnosticCategories/DiagnosticSeverities— category/severity constantsDeprecatedOtelAttributes— 50+ attribute-name mappings synced to OTel GenAI semconv 1.40 (catchesgen_ai.systemand friends during analysis)IncrementalPipelineHelpers— pipeline wiring utilitiesMappingRegistry/TypeCache<TEnum>— cached lookups for analyzer hot paths
Async & time
AsyncSequenceExtensions— LINQ-ish operators overIAsyncEnumerable<T>ParallelAsyncExtensions—SelectParallel(completion order) /SelectParallelOrdered(source order), channel-based fan-out with linked-CTS cancellation so a single selector exception cancels every sibling workerExpiringCache<TKey,TValue>— access-order LRU with single-flight factory invocation viaLazy<TValue?>(no thundering herd on concurrent misses for the same key)TimeConversions— OTel nanosecond helpers
Dictionary & collection ergonomics
DictionaryExtensions—GetOrInsert(key, context, factory)(closure-free, hot-path),GetOrAdd(key)/GetOrAdd(key, factory)(ergonomic),MapIfAbsent(src, dst, transform)(cross-key copy for vendor-adapter telemetry mappers); every helper takes anyIDictionary<TKey, TValue>(SortedDictionaryincluded), and theDictionary<TKey, TValue>overloads stay for binary compatibilityEnumerableExtensions— dedup, partition, chunking,MinBy/MaxByListExtensions— in-place mutation helpersDelta+SetDelta<T>— set difference for incremental "what changed between snapshots" logic.Delta.Difference(first, second)is the relative complementsecond \ first;Delta.Compute(previous, current)returns a value-equatableSetDelta<T>carryingAdded/Removedso a diff flows through the generator cache. Works onImmutableArray<T>andEquatableArray<T>.
Guards & null handling
Guard— null / range / path / type guardsNullableExtensions—Map,Bind,Filter,Or,Matchcombinators forT?(never LINQ names: a bareTreceiver would win overEnumerableon any concrete collection)TryExtensions—TryParseX(every overload pinned toCultureInfo.InvariantCultureso a German dev's"1,5"doesn't silently parse as1.5in production), dictionaryGetOrNull/GetOrDefault/GetOrElse
Models & OTel enums
SpanKind,SpanStatusCode— OTel enumsPagedResult<T>— standard paginated response shape
Polyfills
Language and API backports for netstandard2.0 consumers (via the separate .Polyfills package):
| Polyfill | Enables | Opt-out |
|---|---|---|
Index / Range |
array[^1], array[1..3] |
InjectIndexRangeOnLegacy=false |
IsExternalInit |
record types, init setters |
InjectIsExternalInitOnLegacy=false |
UnionAttribute / IUnion |
C# 15 union declarations before .NET 11 (needs the .NET 11 SDK compiler and LangVersion 15 or latest) |
InjectUnionOnLegacy=false |
| Nullable attributes | [NotNull], [MaybeNull], [MemberNotNull], [NotNullWhen] |
InjectNullabilityAttributesOnLegacy=false |
| Trim/AOT attributes | [RequiresUnreferencedCode], [DynamicallyAccessedMembers] |
InjectTrimAttributesOnLegacy=false |
TimeProvider |
Testable time abstraction | InjectTimeProviderPolyfill=false |
Lock |
System.Threading.Lock |
InjectLockPolyfill=false |
LINQ DistinctBy / SkipLast / TakeLast |
System.Linq operators ns2.0 lacks; modern TFMs bind to the BCL |
InjectLinqPolyfill=false |
required, params collections, CallerArgumentExpression, UnreachableException, StackTraceHidden, ExperimentalAttribute |
C# 11–13 language features on ns2.0 | per-feature MSBuild props |
Disable all at once: <InjectAllPolyfillsOnLegacy>false</InjectAllPolyfillsOnLegacy>
Without Roslyn: a project that does not reference Microsoft.CodeAnalysis sets <InjectRoslynSources>false</InjectRoslynSources> and gets only the Roslyn-free helpers (guards, string comparison, try-parse, dictionary, security, time, text, async). The package sorts its files at pack time: everything that names Microsoft.CodeAnalysis, or a type declared in such a file, ships under Roslyn/. On netstandard2.0 such a project also references System.Collections.Immutable, System.Memory, System.Threading.Channels and Microsoft.Bcl.HashCode, which the framework there lacks.
.Sources embeds the same polyfills, so referencing .Sources and .Polyfills together is supported: the .Sources copy steps aside. An opt-out removes only this package's files, never a consumer's own file of the same name.
Testing packages
ANcpLua.Roslyn.Utilities.Testing (net11.0, like every .Testing.* package below) contains framework-independent Roslyn helpers:
Compile / CompileResult, analyzer/code-fix/refactoring runners, generator cache validation,
DictionaryAnalyzerConfigOptionsProvider, SourceFixture, and RepositoryRoot. The analyzer, code-fix and refactoring
runners compile test code against the .NET 11 reference assemblies unless useNet11References: false selects netstandard2.0.
It does not install xUnit, NUnit, TUnit, bUnit, ASP.NET test hosting, or AI provider clients.
Choose additional packages for the APIs you use:
| Package suffix | APIs and dependencies |
|---|---|
.Testing.MSBuild |
ProjectBuilder, PackageProjectBuilder, BuildResult, SDK/process helpers; no test framework. Output uses Action<string>. |
.Testing.Xunit |
Compilation/build/log assertions, package fixtures, xUnit web lifecycle bases; references core and MSBuild. |
.Testing.NUnit |
NUnit web lifecycle bases. |
.Testing.TUnit |
TUnit web lifecycle bases. |
.Testing.Bunit |
bUnit component-test base with fake logging. |
The split changes assembly ownership; existing namespaces remain. Add the explicit integration
package when migrating a test project. For neutral build output, pass TestContext.WriteLine
or another Action<string> to ProjectBuilder; xUnit callers can pass their output helper's
WriteLine method. BuildOrThrow throws InvalidOperationException with compiler diagnostics.
AOT testing — what ships in .Testing.Aot
Separate package (netstandard2.0, zero runtime deps). Attributes + MSBuild props for verifying AOT/trim behavior.
[AotTest],[AotSafe],[AotUnsafe]— mark methods as AOT-verified or AOT-excluded[TrimTest],[TrimSafe],[TrimUnsafe]— same for IL trimming;TrimModeenum selectsPartial/FullTrimAssert.TypePreserved(...)/TypeTrimmed(...)— runtime assertions against the trimmed binaryFeatureSwitches— constants for common AOT feature switches (e.g.JsonReflection)AotRuntime— runtime AOT/trim detection- MSBuild orchestration (
build/*.props+*.targets+ProjectTemplate.csproj.txt) ships inside the package itself; no external SDK dependency
Separate: AOT reflection generator
This repo also ships ANcpLua.Analyzers.AotReflection — an incremental source generator that replaces runtime typeof(T).GetProperties() with compile-time metadata, making types NativeAOT- and trim-safe. Mark a type [AotReflection] and a generated FooMetadata class appears with strongly-typed getter/setter/invoker delegates. Pair with ANcpLua.Roslyn.Utilities.Testing.Aot to verify the output survives PublishAot=true and PublishTrimmed=true.
Design principles
- Compile-time over runtime reflection.
EquatableArray<T>for generator caching,DiagnosticFlow<T>for pipeline error accumulation,IndentedStringBuilderfor emission — the shape of an incremental generator the compiler cache actually likes. - Allocation-conscious in analyzer hot paths.
ValueStringBuilderfor stack-allocated string building,Boxesfor cached boxed primitives, closure-freeGetOrInsert<TContext>for dictionary inserts. - OTel semconv 1.40 native.
DeprecatedOtelAttributescatchesgen_ai.systemand 50+ other deprecated attribute names during analysis. - Test discipline.
GeneratorCachingReportover hand-rolled cache assertions.Test<TGenerator>fluent runner over hand-rolledCSharpGeneratorDriverplumbing. The shipped-internallyForbiddenTypeAnalyzercatchesISymbol/Compilationsnuck into pipeline models. Agent-specific test doubles live in the siblingANcpLua.Agentspackage. - Source-only delivery for generators. The
.Sourcespackage rewrites the utilities tointernalvia a pack-time MSBuild task in its csproj, because source generators can't load NuGet DLLs at runtime.
Documentation
ancplua.mintlify.app/utilities — full API reference with examples.
Related
- ANcpLua.NET.Sdk — opinionated .NET SDK wrapper built on the same conventions
- ANcpLua.Analyzers — the author's analyzer catalogue, built on these utilities
- ANcpLua.Agents — agent test doubles, MAF conformance, workflow fixtures
License
MIT © Alexander Nachtmann
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- ANcpLua.Roslyn.Utilities (>= 5.0.0)
- AwesomeAssertions (>= 9.4.0)
- Basic.Reference.Assemblies.Net110 (>= 1.8.15)
- Basic.Reference.Assemblies.NetStandard20 (>= 1.8.15)
- Meziantou.Framework.FullPath (>= 3.0.1)
- Microsoft.Bcl.HashCode (>= 6.0.0)
- Microsoft.CodeAnalysis.Analyzer.Testing (>= 1.1.4)
- Microsoft.CodeAnalysis.Analyzers (>= 5.12.0)
- Microsoft.CodeAnalysis.CSharp (>= 5.12.0)
- Microsoft.CodeAnalysis.CSharp.Analyzer.Testing (>= 1.1.4)
- Microsoft.CodeAnalysis.CSharp.CodeFix.Testing (>= 1.1.4)
- Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing (>= 1.1.4)
- Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing (>= 1.1.4)
- Microsoft.CodeAnalysis.CSharp.Workspaces (>= 5.12.0)
- Microsoft.Extensions.Diagnostics.Testing (>= 11.0.1)
- Microsoft.Extensions.Telemetry.Abstractions (>= 11.0.1)
- System.Security.Cryptography.Pkcs (>= 11.0.0)
NuGet packages (5)
Showing the top 5 NuGet packages that depend on ANcpLua.Roslyn.Utilities.Testing:
| Package | Downloads |
|---|---|
|
ANcpLua.Roslyn.Utilities.Testing.MSBuild
Framework-independent project, process, and MSBuild test helpers. |
|
|
ANcpLua.Roslyn.Utilities.Testing.Bunit
Opt-in Bunit integrations for ANcpLua Roslyn testing utilities. |
|
|
ANcpLua.Roslyn.Utilities.Testing.NUnit
Opt-in NUnit integrations for ANcpLua Roslyn testing utilities. |
|
|
ANcpLua.Roslyn.Utilities.Testing.Xunit
Opt-in Xunit integrations for ANcpLua Roslyn testing utilities. |
|
|
ANcpLua.Roslyn.Utilities.Testing.TUnit
Opt-in TUnit integrations for ANcpLua Roslyn testing utilities. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 5.0.1 | 70 | 11/23/2026 |
| 5.0.0 | 68 | 11/23/2026 |
| 5.0.0-preview.1 | 80 | 10/13/2026 |
| 3.0.2 | 373 | 10/19/2026 |
| 3.0.1 | 256 | 10/19/2026 |
| 3.0.0 | 362 | 10/16/2026 |
| 2.2.48 | 241 | 10/13/2026 |
| 2.2.47 | 122 | 10/1/2026 |
| 2.2.46 | 158 | 8/28/2026 |
| 2.2.45 | 140 | 8/28/2026 |
| 2.2.44 | 193 | 8/27/2026 |
| 2.2.43 | 138 | 8/27/2026 |
| 2.2.42 | 163 | 7/21/2026 |
| 2.2.41 | 368 | 7/19/2026 |
| 2.2.40 | 144 | 7/17/2026 |
| 2.2.39 | 205 | 7/16/2026 |
| 2.2.38 | 163 | 7/15/2026 |
| 2.2.37 | 190 | 7/15/2026 |
| 2.2.36 | 151 | 7/7/2026 |
| 2.2.35 | 146 | 7/6/2026 |