From c63169fa9433bbfbefa0feefcb261a0f4e6f2647 Mon Sep 17 00:00:00 2001 From: Agent Driver Date: Thu, 26 Nov 2026 20:55:04 -0500 Subject: [PATCH 1/2] Move the GeneratorTests files A to M to DependencyModules.Specs This commit only moves the files. The next commit converts them to [VerifyTest], so git keeps the history of each file. Co-Authored-By: Claude Opus 5.5 --- .../GeneratorTests/ApplicationModuleCollisionTests.cs | 0 .../GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs | 0 .../GeneratorTests/AttributeModelOutputTests.cs | 0 .../GeneratorTests/AutoModuleDelegationTests.cs | 0 .../GeneratorTests/CodeFixAssemblyTests.cs | 0 .../GeneratorTests/ConfigurationTests.cs | 0 .../GeneratorTests/ConstantArgumentTests.cs | 0 .../GeneratorTests/ConventionContractTests.cs | 0 .../GeneratorTests/ConventionDecoratorTests.cs | 0 .../GeneratorTests/ConventionRegistrationTests.cs | 0 .../GeneratorTests/CrossWireTests.cs | 0 .../GeneratorTests/DeclaredApplicationModuleTests.cs | 0 .../GeneratorTests/DecoratorGenerationTests.cs | 0 .../GeneratorTests/DecoratorImplementationTests.cs | 0 .../GeneratorTests/DiagnosticSuppressionTests.cs | 0 .../GeneratorTests/DiagnosticsTests.cs | 0 .../GeneratorTests/EntryModelUtilTests.cs | 0 .../GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs | 0 .../GeneratorTests/EnvironmentConditionTests.cs | 0 .../GeneratorTests/ExtensionSeamTests.cs | 0 .../GeneratorTests/FileLoggerTests.cs | 0 .../GeneratorTests/FileNameHintTests.cs | 0 .../GeneratorTests/GenerateFactoriesInterceptionTests.cs | 0 .../GeneratorTests/GeneratedBehaviourTests.cs | 0 .../GeneratorTests/GeneratedCodeAccessTests.cs | 0 .../GeneratorTests/GeneratedCodeRobustnessTests.cs | 0 .../GeneratorTests/GeneratedMemberAttributeTests.cs | 0 .../GeneratorTests/GeneratorFailureTests.cs | 0 .../GeneratorTests/GeneratorFeatureTests.cs | 0 .../GeneratorTests/GlueCollectionTests.cs | 0 .../GeneratorTests/GlueFuncTests.cs | 0 .../GeneratorTests/IgnoredDecoratorTests.cs | 0 .../GeneratorTests/IncrementalGenerationTests.cs | 0 .../GeneratorTests/InterceptAttributeSpellingTests.cs | 0 .../GeneratorTests/InterceptedMembersTests.cs | 0 .../GeneratorTests/InterceptionRealmTests.cs | 0 .../GeneratorTests/InterceptionScopeTests.cs | 0 .../GeneratorTests/InterceptorGenerationTests.cs | 0 .../GeneratorTests/InterceptorLifetimeTests.cs | 0 .../GeneratorTests/MockTestExportDiagnosticTests.cs | 0 .../GeneratorTests/ModelComparerTests.cs | 0 .../GeneratorTests/ModelEqualityTests.cs | 0 .../GeneratorTests/ModuleDeclarationTests.cs | 0 .../GeneratorTests/ModuleEqualityDiagnosticTests.cs | 0 .../GeneratorTests/ModuleGenerationSnapshotTests.cs | 0 .../GeneratorTests/ModuleParameterAccessibilityTests.cs | 0 ...ueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt | 0 ...nerationSnapshotTests.GenericServiceRegistrations.verified.txt | 0 ...leGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt | 0 ...rationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt | 0 ...ests.ModuleWithConstructorParametersAndProperties.verified.txt | 0 ...SnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt | 0 ...tionSnapshotTests.ModuleWithEnvironmentConditions.verified.txt | 0 .../ModuleGenerationSnapshotTests.RecordModule.verified.txt | 0 ...eGenerationSnapshotTests.RegistrationTypeVariants.verified.txt | 0 .../ModuleGenerationSnapshotTests.SimpleModule.verified.txt | 0 56 files changed, 0 insertions(+), 0 deletions(-) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ApplicationModuleCollisionTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/AttributeModelOutputTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/AutoModuleDelegationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/CodeFixAssemblyTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ConfigurationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ConstantArgumentTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ConventionContractTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ConventionDecoratorTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ConventionRegistrationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/CrossWireTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/DeclaredApplicationModuleTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/DecoratorGenerationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/DecoratorImplementationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/DiagnosticSuppressionTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/DiagnosticsTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/EntryModelUtilTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/EnvironmentConditionTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ExtensionSeamTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/FileLoggerTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/FileNameHintTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GenerateFactoriesInterceptionTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratedBehaviourTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratedCodeAccessTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratedCodeRobustnessTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratedMemberAttributeTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratorFailureTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GeneratorFeatureTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GlueCollectionTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/GlueFuncTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/IgnoredDecoratorTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/IncrementalGenerationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptAttributeSpellingTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptedMembersTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptionRealmTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptionScopeTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptorGenerationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/InterceptorLifetimeTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/MockTestExportDiagnosticTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModelComparerTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModelEqualityTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModuleDeclarationTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModuleEqualityDiagnosticTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModuleGenerationSnapshotTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/GeneratorTests/ModuleParameterAccessibilityTests.cs (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/GlueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.GenericServiceRegistrations.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.ModuleWithConstructorParametersAndProperties.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.ModuleWithEnvironmentConditions.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.RecordModule.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.RegistrationTypeVariants.verified.txt (100%) rename tests/{DependencyModules.Tests => DependencyModules.Specs}/Snapshots/ModuleGenerationSnapshotTests.SimpleModule.verified.txt (100%) diff --git a/tests/DependencyModules.Tests/GeneratorTests/ApplicationModuleCollisionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ApplicationModuleCollisionTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/AttributeModelOutputTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/AttributeModelOutputTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/AutoModuleDelegationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/AutoModuleDelegationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/CodeFixAssemblyTests.cs b/tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/CodeFixAssemblyTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ConfigurationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ConfigurationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ConstantArgumentTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ConstantArgumentTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ConventionContractTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ConventionContractTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ConventionDecoratorTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ConventionDecoratorTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ConventionRegistrationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ConventionRegistrationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/CrossWireTests.cs b/tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/CrossWireTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/DeclaredApplicationModuleTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/DeclaredApplicationModuleTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/DecoratorGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/DecoratorGenerationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/DecoratorImplementationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/DecoratorImplementationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/DiagnosticSuppressionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/DiagnosticSuppressionTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/DiagnosticsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/DiagnosticsTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/EntryModelUtilTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/EntryModelUtilTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/EnvironmentConditionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/EnvironmentConditionTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ExtensionSeamTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ExtensionSeamTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/FileLoggerTests.cs b/tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/FileLoggerTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/FileNameHintTests.cs b/tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/FileNameHintTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GenerateFactoriesInterceptionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GenerateFactoriesInterceptionTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratedBehaviourTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratedBehaviourTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratedCodeAccessTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratedCodeAccessTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratedCodeRobustnessTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratedCodeRobustnessTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratedMemberAttributeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratedMemberAttributeTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratorFailureTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratorFailureTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GeneratorFeatureTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GeneratorFeatureTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GlueCollectionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GlueCollectionTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/GlueFuncTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/GlueFuncTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/IgnoredDecoratorTests.cs b/tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/IgnoredDecoratorTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/IncrementalGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/IncrementalGenerationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptAttributeSpellingTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptAttributeSpellingTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptedMembersTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptedMembersTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptionRealmTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptionRealmTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptionScopeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptionScopeTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptorGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptorGenerationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/InterceptorLifetimeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/InterceptorLifetimeTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/MockTestExportDiagnosticTests.cs b/tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/MockTestExportDiagnosticTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModelComparerTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModelComparerTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModelEqualityTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModelEqualityTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModuleDeclarationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModuleDeclarationTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModuleEqualityDiagnosticTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModuleEqualityDiagnosticTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModuleGenerationSnapshotTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModuleGenerationSnapshotTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs diff --git a/tests/DependencyModules.Tests/GeneratorTests/ModuleParameterAccessibilityTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs similarity index 100% rename from tests/DependencyModules.Tests/GeneratorTests/ModuleParameterAccessibilityTests.cs rename to tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs diff --git a/tests/DependencyModules.Tests/Snapshots/GlueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt b/tests/DependencyModules.Specs/Snapshots/GlueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/GlueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt rename to tests/DependencyModules.Specs/Snapshots/GlueFuncTests.TheGlueFile_IsTheSameForTheSameSource.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.GenericServiceRegistrations.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.GenericServiceRegistrations.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.GenericServiceRegistrations.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.GenericServiceRegistrations.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.KeyedAndAsRegistrations.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithAllServiceLifetimes.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithConstructorParametersAndProperties.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithConstructorParametersAndProperties.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithConstructorParametersAndProperties.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithConstructorParametersAndProperties.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithCoverageExclusionDisabled.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithEnvironmentConditions.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithEnvironmentConditions.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.ModuleWithEnvironmentConditions.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.ModuleWithEnvironmentConditions.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.RecordModule.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.RecordModule.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.RecordModule.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.RecordModule.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.RegistrationTypeVariants.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.RegistrationTypeVariants.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.RegistrationTypeVariants.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.RegistrationTypeVariants.verified.txt diff --git a/tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.SimpleModule.verified.txt b/tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.SimpleModule.verified.txt similarity index 100% rename from tests/DependencyModules.Tests/Snapshots/ModuleGenerationSnapshotTests.SimpleModule.verified.txt rename to tests/DependencyModules.Specs/Snapshots/ModuleGenerationSnapshotTests.SimpleModule.verified.txt From 15476fefa0b4b09a7d95eff454ab34cc34e57dd5 Mon Sep 17 00:00:00 2001 From: Agent Driver Date: Thu, 26 Nov 2026 21:21:41 -0500 Subject: [PATCH 2/2] Convert the GeneratorTests files A to M to [VerifyTest] [Fact] becomes [VerifyTest], [Theory] with [InlineData] becomes [Row], [MemberData] becomes [RowSource], and the Assert calls become Verify, Single, NotNull and ThrowsExactly. Each test keeps its name, its rows and its checks. The VerificationGlue.Tests runner runs the rows of one test at the same time. Two rows that compiled the same library loaded two copies of it, and the second copy replaced the first in the assembly resolver. So GeneratorTestHarness.CompileLibrary now returns the copy that is already loaded for the same name and source. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 2 +- .../ApplicationModuleCollisionTests.cs | 42 +- ...AssemblyModuleAttributeDiagnosticsTests.cs | 83 ++-- .../AttributeModelOutputTests.cs | 117 ++--- .../AutoModuleDelegationTests.cs | 61 ++- .../GeneratorTests/CodeFixAssemblyTests.cs | 15 +- .../GeneratorTests/ConfigurationTests.cs | 74 ++- .../GeneratorTests/ConstantArgumentTests.cs | 82 ++-- .../GeneratorTests/ConventionContractTests.cs | 45 +- .../ConventionDecoratorTests.cs | 31 +- .../ConventionRegistrationTests.cs | 422 ++++++++-------- .../GeneratorTests/CrossWireTests.cs | 143 +++--- .../DeclaredApplicationModuleTests.cs | 23 +- .../DecoratorGenerationTests.cs | 453 ++++++++---------- .../DecoratorImplementationTests.cs | 37 +- .../DiagnosticSuppressionTests.cs | 259 +++++----- .../GeneratorTests/DiagnosticsTests.cs | 142 +++--- .../GeneratorTests/EntryModelUtilTests.cs | 73 ++- .../EnvironmentAttributesFromSymbolsTests.cs | 41 +- .../EnvironmentConditionTests.cs | 193 ++++---- .../GeneratorTests/ExtensionSeamTests.cs | 31 +- .../GeneratorTests/FileLoggerTests.cs | 79 +-- .../GeneratorTests/FileNameHintTests.cs | 40 +- .../GenerateFactoriesInterceptionTests.cs | 39 +- .../GeneratorTests/GeneratedBehaviourTests.cs | 145 +++--- .../GeneratedCodeAccessTests.cs | 96 ++-- .../GeneratedCodeRobustnessTests.cs | 38 +- .../GeneratedMemberAttributeTests.cs | 61 ++- .../GeneratorTests/GeneratorFailureTests.cs | 40 +- .../GeneratorTests/GeneratorFeatureTests.cs | 107 ++--- .../GeneratorTests/GlueCollectionTests.cs | 270 ++++++----- .../GeneratorTests/GlueFuncTests.cs | 223 +++++---- .../GeneratorTests/IgnoredDecoratorTests.cs | 72 +-- .../IncrementalGenerationTests.cs | 46 +- .../InterceptAttributeSpellingTests.cs | 39 +- .../GeneratorTests/InterceptedMembersTests.cs | 31 +- .../GeneratorTests/InterceptionRealmTests.cs | 59 +-- .../GeneratorTests/InterceptionScopeTests.cs | 61 ++- .../InterceptorGenerationTests.cs | 315 ++++++------ .../InterceptorLifetimeTests.cs | 29 +- .../MockTestExportDiagnosticTests.cs | 57 ++- .../GeneratorTests/ModelComparerTests.cs | 232 +++++---- .../GeneratorTests/ModelEqualityTests.cs | 155 +++--- .../GeneratorTests/ModuleDeclarationTests.cs | 59 +-- .../ModuleEqualityDiagnosticTests.cs | 35 +- .../ModuleGenerationSnapshotTests.cs | 27 +- .../ModuleParameterAccessibilityTests.cs | 51 +- .../Infrastructure/GeneratorTestHarness.cs | 50 +- 48 files changed, 2421 insertions(+), 2404 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de091fc..a34f92e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,7 +24,7 @@ dotnet build DependencyModules.sln --configuration Release The `restore` step needs the `test-tools` feed in `NuGet.config`, which has the Microsoft.Testing.Platform 3 preview that VerificationGlue.Tests uses. No shipping package references VerificationGlue. -The unit tests are in two projects while they move to VerificationGlue.Tests. `tests/DependencyModules.Specs` has the `RuntimeTests` and `ApiTests` folders, and `tests/DependencyModules.Tests` has the other folders. Both projects compile the test harness in `tests/DependencyModules.Specs/Infrastructure`. Each project reads the snapshots in its own `Snapshots` folder. +The unit tests are in two projects while they move to VerificationGlue.Tests. `tests/DependencyModules.Specs` has the `RuntimeTests` and `ApiTests` folders and the `GeneratorTests` files whose names start with A to M. `tests/DependencyModules.Tests` has the other folders and files. Both projects compile the test harness in `tests/DependencyModules.Specs/Infrastructure`. Each project reads the snapshots in its own `Snapshots` folder. To run all tests with code coverage, use the coverage script. The script writes the report to `artifacts/coverage`. If you give a percentage, the script fails when the line coverage is less than that value. diff --git a/tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs index 62b5b33..9860e2c 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ApplicationModuleCollisionTests.cs @@ -2,9 +2,8 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Declaring [DependencyModule] partial class ApplicationModule in a project that already @@ -26,14 +25,14 @@ namespace DependencyModules.Tests.GeneratorTests; /// The variants below are kept as a set on purpose: every one of them was reported as the trigger /// at some point, and only the last is. /// -public class ApplicationModuleCollisionTests +public partial class ApplicationModuleCollisionTests { - [Fact] + [VerifyTest] public void DeclaringApplicationModuleInTheRootNamespace_DoesNotCollide() { var result = Run(DeclaredModule("ConfiguredRoot")); - Assert.Empty(result.DuplicateHintNames); + Verify(result.DuplicateHintNames.Count == 0); result.AssertNoErrors(); } @@ -41,14 +40,15 @@ public void DeclaringApplicationModuleInTheRootNamespace_DoesNotCollide() /// CS8785 is how a duplicate hint name reaches the build, and it is only a warning — which is /// the reason this shipped. Asserted separately from AssertNoErrors for that reason. /// - [Fact] + [VerifyTest] public void DeclaringApplicationModuleInTheRootNamespace_DoesNotWarn() { var result = Run(DeclaredModule("ConfiguredRoot")); - Assert.DoesNotContain( - result.CompilationDiagnostics.Concat(result.GeneratorDiagnostics), - diagnostic => diagnostic.Id == "CS8785" + Verify( + !result + .CompilationDiagnostics.Concat(result.GeneratorDiagnostics) + .Any(diagnostic => diagnostic.Id == "CS8785") ); } @@ -57,35 +57,35 @@ public void DeclaringApplicationModuleInTheRootNamespace_DoesNotWarn() /// add to. Consolidation already preferred a declared module over a generated one wherever it /// recognised the two as the same — this only ever failed to recognise them. /// - [Fact] + [VerifyTest] public void TheDeclaredModuleIsTheOneGenerated() { var result = Run(DeclaredModule("ConfiguredRoot")); var module = result.SourceContaining("ApplicationModule.Module"); - Assert.Contains("namespace ConfiguredRoot", module); + Verify(module.Contains("namespace ConfiguredRoot")); } /// /// The registrations still have to arrive. Merging the two models is only correct if the /// surviving one carries what the project asked for. /// - [Fact] + [VerifyTest] public void TheSurvivingModuleStillRegistersTheProjectsServices() { var result = Run(DeclaredModule("ConfiguredRoot")); - Assert.Contains("Thing", result.SourceContaining("ApplicationModule.Dependencies")); + Verify(result.SourceContaining("ApplicationModule.Dependencies").Contains("Thing")); } /// /// The four shapes that always built cleanly, kept so that a fix cannot quietly change them. /// Each differs from the failing case in exactly one way. /// - [Theory] + [VerifyTest] // A different name never collides with the generated ApplicationModule. - [InlineData( + [Row( "different name", """ namespace ConfiguredRoot; @@ -94,7 +94,7 @@ public partial class CompositionModule; """ )] // A namespace other than RootNamespace produces a different hint name. - [InlineData( + [Row( "different namespace", """ namespace SomewhereElse; @@ -103,7 +103,7 @@ public partial class ApplicationModule; """ )] // The global namespace, likewise. - [InlineData( + [Row( "global namespace", """ [DependencyModules.Runtime.Attributes.DependencyModule] @@ -114,9 +114,9 @@ public void AShapeThatNeverCollided_StillBuildsCleanly(string variant, string de { var result = Run(declaration); - Assert.Empty(result.DuplicateHintNames); + Verify(result.DuplicateHintNames.Count == 0); result.AssertNoErrors(); - Assert.NotEmpty(variant); + Verify(variant.Length != 0); } /// @@ -129,7 +129,7 @@ public void AShapeThatNeverCollided_StillBuildsCleanly(string variant, string de /// left as it is rather than narrowed: a project relying on the generated module today would /// lose it, and this fix makes the shape work either way. /// - [Fact] + [VerifyTest] public void AnExplicitMainWithADeclaredApplicationModule_BuildsCleanly() { var result = GeneratorTestHarness.Run( @@ -149,7 +149,7 @@ public static class Program { OutputKind.ConsoleApplication ); - Assert.Empty(result.DuplicateHintNames); + Verify(result.DuplicateHintNames.Count == 0); result.AssertNoErrors(); } diff --git a/tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs index 6ea1967..6c51b79 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/AssemblyModuleAttributeDiagnosticsTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// DM0016. A module generates its attribute in the module's own namespace, and an assembly-level @@ -12,7 +11,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// running, so it does not exist in the compilation being examined and nothing about it resolves. /// That makes the false positives the interesting cases, and most of these tests are one. /// -public class AssemblyModuleAttributeDiagnosticsTests +public partial class AssemblyModuleAttributeDiagnosticsTests { private const string ModuleInNamespace = """ namespace MyApp.Composition; @@ -21,27 +20,27 @@ namespace MyApp.Composition; public partial class ApplicationModule; """; - [Fact] + [VerifyTest] public void MissingUsing_IsReported() { var result = Run("[assembly: ApplicationModule]"); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); - Assert.Contains("MyApp.Composition", diagnostic.GetMessage()); - Assert.Contains("using MyApp.Composition;", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("MyApp.Composition")); + Verify(diagnostic.GetMessage().Contains("using MyApp.Composition;")); } /// The suffixed spelling names the same module. - [Fact] + [VerifyTest] public void MissingUsing_IsReported_ForTheAttributeSuffixedSpelling() { var result = Run("[assembly: ApplicationModuleAttribute]"); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); } - [Fact] + [VerifyTest] public void TheUsingBeingPresent_IsSilent() { var result = Run( @@ -52,14 +51,14 @@ public void TheUsingBeingPresent_IsSilent() """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } /// /// A global using in any file supplies the namespace everywhere, so reading only the file the /// attribute sits in would report a build that is already correct. /// - [Fact] + [VerifyTest] public void AGlobalUsingInAnotherFile_IsSilent() { var result = GeneratorTestHarness.Run( @@ -71,28 +70,28 @@ public void AGlobalUsingInAnotherFile_IsSilent() } ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } - [Fact] + [VerifyTest] public void AQualifiedUsage_IsSilent() { var result = Run("[assembly: MyApp.Composition.ApplicationModule]"); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } /// An attribute this compilation declares no module for belongs to somebody else. - [Fact] + [VerifyTest] public void AnUnrelatedAssemblyAttribute_IsSilent() { var result = Run("[assembly: System.Reflection.AssemblyMetadata(\"key\", \"value\")]"); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } /// A module in the global namespace has no namespace to import. - [Fact] + [VerifyTest] public void AModuleInTheGlobalNamespace_IsSilent() { var result = GeneratorTestHarness.Run( @@ -106,14 +105,14 @@ public partial class ApplicationModule; } ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } /// /// A using alias imports one name rather than a namespace, so it does not bring the attribute /// into scope under the name written here and the report still stands. /// - [Fact] + [VerifyTest] public void AUsingAlias_DoesNotCountAsTheImport() { var result = Run( @@ -124,7 +123,7 @@ public void AUsingAlias_DoesNotCountAsTheImport() """ ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0016"); } /// @@ -133,7 +132,7 @@ public void AUsingAlias_DoesNotCountAsTheImport() /// they were read by nobody: a clean build, and an InvalidOperationException at the first /// resolve. /// - [Fact] + [VerifyTest] public void AnAssemblyAttributeOutsideTheEntryPointFile_IsReported() { var result = RunWithEntryPoint( @@ -145,34 +144,32 @@ public void AnAssemblyAttributeOutsideTheEntryPointFile_IsReported() program: "System.Console.WriteLine();" ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0019"); - Assert.Contains("ApplicationModule", diagnostic.GetMessage()); - Assert.Contains("Program.cs", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("ApplicationModule")); + Verify(diagnostic.GetMessage().Contains("Program.cs")); } /// /// A qualified name needs no import, so DM0016 cannot apply. The attribute is still read by /// nobody outside the entry point file. /// - [Theory] - [InlineData("[assembly: MyApp.Composition.ApplicationModule]")] - [InlineData("[assembly: MyApp.Composition.ApplicationModuleAttribute]")] - [InlineData("[assembly: global::MyApp.Composition.ApplicationModule]")] - [InlineData( - "using Composition = MyApp.Composition;\n[assembly: Composition.ApplicationModule]" - )] + [VerifyTest] + [Row("[assembly: MyApp.Composition.ApplicationModule]")] + [Row("[assembly: MyApp.Composition.ApplicationModuleAttribute]")] + [Row("[assembly: global::MyApp.Composition.ApplicationModule]")] + [Row("using Composition = MyApp.Composition;\n[assembly: Composition.ApplicationModule]")] public void AQualifiedAssemblyAttributeOutsideTheEntryPointFile_IsReported(string bootstrap) { var result = RunWithEntryPoint(bootstrap, program: "System.Console.WriteLine();"); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0019"); - Assert.Contains("ApplicationModule", diagnostic.GetMessage()); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0016"); + Verify(diagnostic.GetMessage().Contains("ApplicationModule")); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0016")); } - [Fact] + [VerifyTest] public void AQualifiedAssemblyAttributeInTheEntryPointFile_IsSilent() { var result = RunWithEntryPoint( @@ -184,11 +181,11 @@ public void AQualifiedAssemblyAttributeInTheEntryPointFile_IsSilent() """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0019")); } /// A qualified attribute that names no module is somebody else's. - [Fact] + [VerifyTest] public void AQualifiedAttributeThatNamesNoModule_IsSilent() { var result = RunWithEntryPoint( @@ -196,10 +193,10 @@ public void AQualifiedAttributeThatNamesNoModule_IsSilent() program: "System.Console.WriteLine();" ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0019")); } - [Fact] + [VerifyTest] public void AnAssemblyAttributeInTheEntryPointFile_IsSilent() { var result = RunWithEntryPoint( @@ -213,7 +210,7 @@ public void AnAssemblyAttributeInTheEntryPointFile_IsSilent() """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0019")); } /// @@ -222,7 +219,7 @@ public void AnAssemblyAttributeInTheEntryPointFile_IsSilent() /// relative to — and the test integration reads assembly attributes at run time anyway, which is /// what the testing guide shows. /// - [Fact] + [VerifyTest] public void WithNoGeneratedApplicationModule_IsSilent() { var result = Run( @@ -233,7 +230,7 @@ public void WithNoGeneratedApplicationModule_IsSilent() """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0019"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0019")); } private static GeneratorResult Run(string bootstrap) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs index 757ce82..3005da0 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/AttributeModelOutputTests.cs @@ -1,74 +1,75 @@ using CSharpAuthor; using DependencyModules.SourceGenerator.Impl; using DependencyModules.SourceGenerator.Impl.Models; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// AttributeModel turns the values captured from a source attribute back into C# for the generated /// module attribute. Each supported value shape has to round-trip into code that compiles. /// -public class AttributeModelOutputTests +public partial class AttributeModelOutputTests { private static readonly ITypeDefinition SomeType = TypeDefinition.Get("Ns", "SomeType"); - [Fact] + [VerifyTest] public void GetArguments_WithNoArguments_ReturnsNothing() { - Assert.Empty(Attribute().GetArguments()); + Verify(!Attribute().GetArguments().Any()); } - [Fact] + [VerifyTest] public void GetArguments_QuotesStringValues() { var rendered = Render( Attribute(arguments: [new AttributeArgumentValue("name", "hello")]).GetArguments() ); - Assert.Contains("\"hello\"", rendered); + Verify(rendered.Contains("\"hello\"")); } - [Fact] + [VerifyTest] public void GetArguments_WritesTypeValuesAsTypeof() { var rendered = Render( Attribute(arguments: [new AttributeArgumentValue("type", SomeType)]).GetArguments() ); - Assert.Contains("typeof(", rendered); - Assert.Contains("SomeType", rendered); + Verify(rendered.Contains("typeof(")); + Verify(rendered.Contains("SomeType")); } - [Fact] + [VerifyTest] public void GetArguments_WritesPrimitiveValuesVerbatim() { var rendered = Render( Attribute(arguments: [new AttributeArgumentValue("count", 42)]).GetArguments() ); - Assert.Contains("42", rendered); + Verify(rendered.Contains("42")); } - [Fact] + [VerifyTest] public void GetArguments_WritesBooleanValues() { var rendered = Render( Attribute(arguments: [new AttributeArgumentValue("flag", true)]).GetArguments() ); - Assert.Contains("True", rendered, StringComparison.OrdinalIgnoreCase); + Verify(rendered.Contains("True", StringComparison.OrdinalIgnoreCase)); } - [Fact] + [VerifyTest] public void GetArguments_SkipsNullValues() { - Assert.Empty( - Attribute(arguments: [new AttributeArgumentValue("nothing", null)]).GetArguments() + Verify( + !Attribute(arguments: [new AttributeArgumentValue("nothing", null)]) + .GetArguments() + .Any() ); } - [Fact] + [VerifyTest] public void GetArguments_WritesStringArraysAsACollection() { var rendered = Render( @@ -76,14 +77,14 @@ public void GetArguments_WritesStringArraysAsACollection() .GetArguments() ); - Assert.StartsWith("[", rendered); - Assert.EndsWith("]", rendered); - Assert.Contains("\"a\"", rendered); - Assert.Contains("\"b\"", rendered); - Assert.Contains(",", rendered); + Verify(rendered.StartsWith("[")); + Verify(rendered.EndsWith("]")); + Verify(rendered.Contains("\"a\"")); + Verify(rendered.Contains("\"b\"")); + Verify(rendered.Contains(",")); } - [Fact] + [VerifyTest] public void GetArguments_PassesThroughOutputComponents() { var component = CodeOutputComponent.Get("SomeExpression"); @@ -92,10 +93,10 @@ public void GetArguments_PassesThroughOutputComponents() Attribute(arguments: [new AttributeArgumentValue("value", component)]).GetArguments() ); - Assert.Contains("SomeExpression", rendered); + Verify(rendered.Contains("SomeExpression")); } - [Fact] + [VerifyTest] public void GetArguments_PreservesArgumentOrder() { var rendered = Render( @@ -109,36 +110,36 @@ public void GetArguments_PreservesArgumentOrder() .GetArguments() ); - Assert.True( + Verify( rendered.IndexOf("one", StringComparison.Ordinal) < rendered.IndexOf("two", StringComparison.Ordinal), $"Arguments came out in the wrong order: {rendered}" ); } - [Fact] + [VerifyTest] public void PropertyValues_WithNoProperties_ReturnsNothing() { - Assert.Empty(Attribute().PropertyValues()); + Verify(!Attribute().PropertyValues().Any()); } - [Fact] + [VerifyTest] public void PropertyValues_WritesNamedAssignments() { var rendered = Render( Attribute(properties: [new AttributeArgumentValue("Name", "value")]).PropertyValues() ); - Assert.Contains("Name", rendered); - Assert.Contains("=", rendered); - Assert.Contains("\"value\"", rendered); + Verify(rendered.Contains("Name")); + Verify(rendered.Contains("=")); + Verify(rendered.Contains("\"value\"")); } /// /// Property values arrive from the syntax tree already quoted; re-quoting would emit /// a doubly-quoted literal. /// - [Fact] + [VerifyTest] public void PropertyValues_DoesNotDoubleQuoteAnAlreadyQuotedString() { var rendered = Render( @@ -146,64 +147,66 @@ public void PropertyValues_DoesNotDoubleQuoteAnAlreadyQuotedString() .PropertyValues() ); - Assert.DoesNotContain("\"\"", rendered); - Assert.Contains("\"value\"", rendered); + Verify(!rendered.Contains("\"\"")); + Verify(rendered.Contains("\"value\"")); } - [Fact] + [VerifyTest] public void PropertyValues_WritesTypeValuesAsTypeof() { var rendered = Render( Attribute(properties: [new AttributeArgumentValue("As", SomeType)]).PropertyValues() ); - Assert.Contains("typeof(", rendered); + Verify(rendered.Contains("typeof(")); } - [Fact] + [VerifyTest] public void PropertyValues_SkipsNullValues() { - Assert.Empty( - Attribute(properties: [new AttributeArgumentValue("Name", null)]).PropertyValues() + Verify( + !Attribute(properties: [new AttributeArgumentValue("Name", null)]) + .PropertyValues() + .Any() ); } - [Fact] + [VerifyTest] public void CollectionSyntax_WithNoItems_WritesEmptyBrackets() { - Assert.Equal("[]", Render(new CollectionSyntaxDeclaration())); + Verify(Render(new CollectionSyntaxDeclaration()) == "[]"); } - [Fact] + [VerifyTest] public void CollectionSyntax_QuotesStringItems() { var collection = new CollectionSyntaxDeclaration(); collection.Add("value"); - Assert.Equal("[\"value\"]", Render(collection)); + Verify(Render(collection) == "[\"value\"]"); } - [Fact] + [VerifyTest] public void CollectionSyntax_SeparatesItemsWithCommas() { var collection = new CollectionSyntaxDeclaration(); collection.Add("one"); collection.Add("two"); - Assert.Equal("[\"one\", \"two\"]", Render(collection)); + Verify(Render(collection) == "[\"one\", \"two\"]"); } - [Fact] + [VerifyTest] public void CollectionSyntax_WritesNonStringItemsVerbatim() { var collection = new CollectionSyntaxDeclaration(); collection.Add(1); collection.Add(2); - Assert.Equal("[1, 2]", Render(collection)); + Verify(Render(collection) == "[1, 2]"); } - [Fact] + [VerifyTest] public void CollectionSyntax_WithTheSameItems_IsEqual() { var first = new CollectionSyntaxDeclaration(); @@ -212,10 +215,10 @@ public void CollectionSyntax_WithTheSameItems_IsEqual() var second = new CollectionSyntaxDeclaration(); second.Add("a"); - Assert.True(first.Equals(second)); + Verify(first.Equals(second)); } - [Fact] + [VerifyTest] public void CollectionSyntax_WithDifferentItems_IsNotEqual() { var first = new CollectionSyntaxDeclaration(); @@ -224,22 +227,22 @@ public void CollectionSyntax_WithDifferentItems_IsNotEqual() var second = new CollectionSyntaxDeclaration(); second.Add("b"); - Assert.False(first.Equals(second)); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void CollectionSyntax_WithDifferentCounts_IsNotEqual() { var first = new CollectionSyntaxDeclaration(); first.Add("a"); - Assert.False(first.Equals(new CollectionSyntaxDeclaration())); + Verify(!first.Equals(new CollectionSyntaxDeclaration())); } - [Fact] + [VerifyTest] public void CollectionSyntax_IsNotEqualToOtherTypes() { - Assert.False(new CollectionSyntaxDeclaration().Equals("not a collection")); + Verify(!new CollectionSyntaxDeclaration().Equals("not a collection")); } private static AttributeModel Attribute( diff --git a/tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs index 2e55b68..603b6f1 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/AutoModuleDelegationTests.cs @@ -4,9 +4,8 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// A project with a Program.cs gets an ApplicationModule whether or not it declares a @@ -19,9 +18,9 @@ namespace DependencyModules.Tests.GeneratorTests; /// and the runtime loads it. These tests pin both halves - that the duplicate is gone, and that /// AddModule<ApplicationModule>() still registers exactly what it did before. /// -public class AutoModuleDelegationTests +public partial class AutoModuleDelegationTests { - [Fact] + [VerifyTest] public void ApplicationModule_DoesNotRepeatTheRegistrationsOfADeclaredModule() { var result = Run( @@ -40,20 +39,16 @@ public partial class TestModule; result.AssertNoErrors(); - Assert.Contains( - result.GeneratedSources.Keys, - key => key.Contains("TestModule.Dependencies") - ); - Assert.DoesNotContain( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule.Dependencies") + Verify(result.GeneratedSources.Keys.Any(key => key.Contains("TestModule.Dependencies"))); + Verify( + !result.GeneratedSources.Keys.Any(key => key.Contains("ApplicationModule.Dependencies")) ); } /// /// The class is still generated, and still reachable - only its registrations moved. /// - [Fact] + [VerifyTest] public void ApplicationModule_NamesTheModuleItDefersTo() { var result = Run( @@ -71,9 +66,10 @@ public partial class TestModule; ); result.AssertNoErrors(); - Assert.Contains( - "new global::TestNamespace.TestModule()", - result.SourceContaining("ApplicationModule.Module") + Verify( + result + .SourceContaining("ApplicationModule.Module") + .Contains("new global::TestNamespace.TestModule()") ); } @@ -81,7 +77,7 @@ public partial class TestModule; /// Decorations and interceptions travelled with the registrations, so they were duplicated the /// same way and have to stop being duplicated the same way. /// - [Fact] + [VerifyTest] public void ApplicationModule_DoesNotRepeatDecorationsEither() { var result = Run( @@ -103,17 +99,16 @@ public partial class TestModule; result.AssertNoErrors(); - Assert.Contains(result.GeneratedSources.Keys, key => key.Contains("TestModule.Decorators")); - Assert.DoesNotContain( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule.Decorators") + Verify(result.GeneratedSources.Keys.Any(key => key.Contains("TestModule.Decorators"))); + Verify( + !result.GeneratedSources.Keys.Any(key => key.Contains("ApplicationModule.Decorators")) ); } /// /// With nothing to defer to, the auto module carries its own registrations exactly as before. /// - [Fact] + [VerifyTest] public void ApplicationModule_KeepsItsRegistrationsWhenNoModuleIsDeclared() { var result = Run( @@ -128,9 +123,8 @@ public class Thing : IThing; ); result.AssertNoErrors(); - Assert.Contains( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule.Dependencies") + Verify( + result.GeneratedSources.Keys.Any(key => key.Contains("ApplicationModule.Dependencies")) ); } @@ -138,7 +132,7 @@ public class Thing : IThing; /// A realm-restricted module takes only the registrations aimed at it, so deferring to one would /// drop everything else. The auto module keeps its own registrations in that case. /// - [Fact] + [VerifyTest] public void ApplicationModule_KeepsItsRegistrationsWhenTheOnlyModuleIsRealmRestricted() { var result = Run( @@ -156,16 +150,15 @@ public partial class RealmModule; ); result.AssertNoErrors(); - Assert.Contains( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule.Dependencies") + Verify( + result.GeneratedSources.Keys.Any(key => key.Contains("ApplicationModule.Dependencies")) ); } /// /// The point of the whole exercise: what reaches the service collection is unchanged. /// - [Fact] + [VerifyTest] public void ApplicationModule_RegistersTheSameServicesAsTheModuleItDefersTo() { var assembly = Compile( @@ -187,9 +180,9 @@ public partial class TestModule; var thing = assembly.GetType("TestNamespace.IThing")!; - Assert.Equal(Describe(viaDeclaredModule, thing), Describe(viaApplicationModule, thing)); + Verify(Describe(viaApplicationModule, thing) == Describe(viaDeclaredModule, thing)); - Assert.NotNull(viaApplicationModule.BuildServiceProvider().GetService(thing)); + Verify(viaApplicationModule.BuildServiceProvider().GetService(thing) is not null); } /// @@ -197,7 +190,7 @@ public partial class TestModule; /// independent copies of it. The auto module now names the declared one, so the runtime's /// deduplication sees them as one. /// - [Fact] + [VerifyTest] public void LoadingBothModules_RegistersEachServiceOnce() { var assembly = Compile( @@ -222,7 +215,7 @@ public partial class TestModule; var thing = assembly.GetType("TestNamespace.IThing")!; - Assert.Single(both, descriptor => descriptor.ServiceType == thing); + Single(both, descriptor => descriptor.ServiceType == thing); } private static string Describe(IServiceCollection services, Type serviceType) => @@ -270,7 +263,7 @@ private static Assembly Compile(IReadOnlyDictionary sources) using var stream = new MemoryStream(); var emitted = result.Compilation.Emit(stream); - Assert.True( + Verify( emitted.Success, string.Join( Environment.NewLine, diff --git a/tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs b/tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs index fe10794..724b998 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/CodeFixAssemblyTests.cs @@ -2,17 +2,16 @@ using System.Runtime.Loader; using DependencyModules.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The code fix assembly loads the way an IDE loads it from analyzers/dotnet/cs: Roslyn and the /// framework come from the host, and nothing else is there to resolve. /// -public class CodeFixAssemblyTests +public partial class CodeFixAssemblyTests { - [Fact] + [VerifyTest] public void TheCodeFixAssembly_LoadsWithOnlyHostAssemblies() { var context = new HostOnlyLoadContext(); @@ -29,10 +28,10 @@ public void TheCodeFixAssembly_LoadsWithOnlyHostAssemblies() .Select(type => (CodeFixProvider)Activator.CreateInstance(type)!) .ToArray(); - var provider = Assert.Single(providers); - Assert.Equal(new[] { "DM0026" }, provider.FixableDiagnosticIds); - Assert.NotNull(provider.GetFixAllProvider()); - Assert.Empty(context.Refused); + var provider = Single(providers); + Verify(provider.FixableDiagnosticIds.SequenceEqual(new[] { "DM0026" })); + Verify(provider.GetFixAllProvider() is not null); + Verify(context.Refused.Count == 0); } finally { diff --git a/tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs index baee62a..26c07b2 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ConfigurationTests.cs @@ -2,26 +2,25 @@ using DependencyModules.SourceGenerator.Impl.Models; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The generator is configured through MSBuild properties surfaced as CompilerVisibleProperty in /// the packaged build/*.targets. These tests pin the mapping from property value to generated code. /// -public class ConfigurationTests +public partial class ConfigurationTests { - [Fact] + [VerifyTest] public void ExcludeGeneratedCodeFromCoverage_DefaultsToOn() { var result = GeneratorTestHarness.Run(ModuleWithService); result.AssertNoErrors(); - Assert.Contains("ExcludeFromCodeCoverage", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("ExcludeFromCodeCoverage")); } - [Fact] + [VerifyTest] public void ExcludeGeneratedCodeFromCoverage_False_OmitsTheAttribute() { var result = GeneratorTestHarness.Run( @@ -30,10 +29,10 @@ public void ExcludeGeneratedCodeFromCoverage_False_OmitsTheAttribute() ); result.AssertNoErrors(); - Assert.DoesNotContain("ExcludeFromCodeCoverage", result.SourceContaining("Dependencies")); + Verify(!result.SourceContaining("Dependencies").Contains("ExcludeFromCodeCoverage")); } - [Fact] + [VerifyTest] public void ExcludeGeneratedCodeFromCoverage_IsCaseInsensitive() { var result = GeneratorTestHarness.Run( @@ -42,14 +41,14 @@ public void ExcludeGeneratedCodeFromCoverage_IsCaseInsensitive() ); result.AssertNoErrors(); - Assert.DoesNotContain("ExcludeFromCodeCoverage", result.SourceContaining("Dependencies")); + Verify(!result.SourceContaining("Dependencies").Contains("ExcludeFromCodeCoverage")); } /// /// RootNamespace is applied to the ApplicationModule that gets generated for a top-level /// statement Program.cs; explicitly declared modules keep whatever namespace they are written in. /// - [Fact] + [VerifyTest] public void RootNamespace_NamesTheAutoGeneratedApplicationModule() { var result = GeneratorTestHarness.Run( @@ -74,13 +73,12 @@ public class Thing : IThing; ); result.AssertNoErrors(); - Assert.Contains( - "namespace ConfiguredRoot", - result.SourceContaining("ApplicationModule.Module") + Verify( + result.SourceContaining("ApplicationModule.Module").Contains("namespace ConfiguredRoot") ); } - [Fact] + [VerifyTest] public void AutoGenerateModule_False_SuppressesTheApplicationModule() { var result = GeneratorTestHarness.Run( @@ -108,29 +106,26 @@ public partial class TestModule; ); result.AssertNoErrors(); - Assert.DoesNotContain( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule") - ); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("ApplicationModule"))); } - [Theory] - [InlineData("Try", RegistrationType.Try)] - [InlineData("Add", RegistrationType.Add)] - [InlineData("Replace", RegistrationType.Replace)] - [InlineData("TryEnumerable", RegistrationType.TryEnumerable)] - [InlineData("RegistrationType.Try", RegistrationType.Try)] - [InlineData("", RegistrationType.Add)] - [InlineData("nonsense", RegistrationType.Add)] + [VerifyTest] + [Row("Try", RegistrationType.Try)] + [Row("Add", RegistrationType.Add)] + [Row("Replace", RegistrationType.Replace)] + [Row("TryEnumerable", RegistrationType.TryEnumerable)] + [Row("RegistrationType.Try", RegistrationType.Try)] + [Row("", RegistrationType.Add)] + [Row("nonsense", RegistrationType.Add)] public void GetRegistrationType_ParsesKnownValuesAndFallsBackToAdd( string input, RegistrationType expected ) { - Assert.Equal(expected, BaseSourceGenerator.GetRegistrationType(input)); + Verify(BaseSourceGenerator.GetRegistrationType(input) == expected); } - [Fact] + [VerifyTest] public void DependencyModulesRegistrationType_ChangesTheDefaultRegistrationMethod() { var result = GeneratorTestHarness.Run( @@ -139,19 +134,19 @@ public void DependencyModulesRegistrationType_ChangesTheDefaultRegistrationMetho ); result.AssertNoErrors(); - Assert.Contains("TryAdd", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("TryAdd")); } - [Fact] + [VerifyTest] public void GeneratedCodeStyle_DefaultsToAllman() { var result = GeneratorTestHarness.Run(ModuleWithService); result.AssertNoErrors(); - Assert.Contains("services)\n {", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("services)\n {")); } - [Fact] + [VerifyTest] public void GeneratedCodeStyle_KAndR_PutsTheBraceOnTheOpeningLine() { var result = GeneratorTestHarness.Run( @@ -160,14 +155,13 @@ public void GeneratedCodeStyle_KAndR_PutsTheBraceOnTheOpeningLine() ); result.AssertNoErrors(); - Assert.Contains("services) {", result.SourceContaining("Dependencies")); - Assert.Contains( - "public partial class TestModule {", - result.SourceContaining("Dependencies") + Verify(result.SourceContaining("Dependencies").Contains("services) {")); + Verify( + result.SourceContaining("Dependencies").Contains("public partial class TestModule {") ); } - [Fact] + [VerifyTest] public void GeneratedCodeStyle_IsCaseInsensitive() { var result = GeneratorTestHarness.Run( @@ -176,14 +170,14 @@ public void GeneratedCodeStyle_IsCaseInsensitive() ); result.AssertNoErrors(); - Assert.Contains("services) {", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("services) {")); } /// /// An unrecognized value falls back to the default rather than failing the build, the same /// stance DependencyModules_RegistrationType takes. /// - [Fact] + [VerifyTest] public void GeneratedCodeStyle_UnknownValue_FallsBackToAllman() { var result = GeneratorTestHarness.Run( @@ -192,7 +186,7 @@ public void GeneratedCodeStyle_UnknownValue_FallsBackToAllman() ); result.AssertNoErrors(); - Assert.Contains("services)\n {", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("services)\n {")); } private const string ModuleWithService = """ diff --git a/tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs index a419cd1..5835ec6 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ConstantArgumentTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// An attribute or convention argument is read as the value it evaluates to. A constant declared /// elsewhere, a digit separator and a fully qualified enum member all have to give the same result /// as the literal. /// -public class ConstantArgumentTests +public partial class ConstantArgumentTests { private const string Preamble = """ using DependencyModules.Runtime.Attributes; @@ -40,7 +39,7 @@ private static GeneratorResult Run(string source) => private static GeneratedAssembly Compile(string source) => GeneratedAssembly.Create(Preamble + source); - [Fact] + [VerifyTest] public void ServiceOrder_IsReadAsItsValue() { var assembly = Compile( @@ -61,15 +60,19 @@ public partial class TestModule; """ ); - Assert.Equal( - new[] { "LiteralOrderRule", "SeparatorOrderRule", "ConstantOrderRule" }, - assembly.Descriptors("IRule").Select(d => d.ImplementationType!.Name) + Verify( + assembly + .Descriptors("IRule") + .Select(d => d.ImplementationType!.Name) + .SequenceEqual( + new[] { "LiteralOrderRule", "SeparatorOrderRule", "ConstantOrderRule" } + ) ); } - [Theory] - [InlineData("DependencyModules.Runtime.Attributes.RegistrationType.Try")] - [InlineData("Choices.TryIt")] + [VerifyTest] + [Row("DependencyModules.Runtime.Attributes.RegistrationType.Try")] + [Row("Choices.TryIt")] public void ServiceUsing_IsReadAsItsValue(string registrationType) { var assembly = Compile( @@ -87,10 +90,10 @@ public partial class TestModule; """ ); - Assert.Single(assembly.Descriptors("IClock")); + Single(assembly.Descriptors("IClock")); } - [Fact] + [VerifyTest] public void ModuleArguments_AreReadAsTheirValues() { var result = Run( @@ -112,12 +115,12 @@ public partial class TestModule; var registrations = result.SourceContaining("Dependencies"); - Assert.Contains("services.TryAddSingleton(", registrations); - Assert.DoesNotContain("services.AddSingleton(", registrations); - Assert.Contains("new global::TestNamespace.FirstClock()", registrations); + Verify(registrations.Contains("services.TryAddSingleton(")); + Verify(!registrations.Contains("services.AddSingleton(")); + Verify(registrations.Contains("new global::TestNamespace.FirstClock()")); } - [Fact] + [VerifyTest] public void CrossWireLifetime_IsReadAsItsValue() { var assembly = Compile( @@ -132,11 +135,11 @@ public partial class TestModule; """ ); - Assert.Equal(ServiceLifetime.Scoped, assembly.Descriptor("Store").Lifetime); - Assert.Equal(ServiceLifetime.Scoped, assembly.Descriptor("IReader").Lifetime); + Verify(assembly.Descriptor("Store").Lifetime == ServiceLifetime.Scoped); + Verify(assembly.Descriptor("IReader").Lifetime == ServiceLifetime.Scoped); } - [Fact] + [VerifyTest] public void DecoratorOrder_IsReadAsItsValue() { var assembly = Compile( @@ -171,13 +174,15 @@ public partial class TestModule; var greeter = assembly.ResolveRequired("IGreeter"); - Assert.Equal( - "outer(inner(hello))", - greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null) + Verify( + Equals( + greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null), + "outer(inner(hello))" + ) ); } - [Fact] + [VerifyTest] public void InterceptArguments_AreReadAsTheirValues() { var assembly = Compile( @@ -227,22 +232,22 @@ public partial class TestModule; """ ); - Assert.Equal(ServiceLifetime.Scoped, assembly.Descriptor("CountingInterceptor").Lifetime); + Verify(assembly.Descriptor("CountingInterceptor").Lifetime == ServiceLifetime.Scoped); using var scope = assembly.BuildProvider().CreateScope(); var greeterType = assembly.Type("IGreeter"); var greeter = scope.ServiceProvider.GetRequiredService(greeterType); // Order 2000 puts the interception outside the decorator at 1000. - Assert.Equal("Greeter_Intercepted", greeter.GetType().Name); + Verify(greeter.GetType().Name == "Greeter_Intercepted"); greeterType.GetMethod("Hello")!.Invoke(greeter, null); greeterType.GetProperty("Name")!.GetValue(greeter); - Assert.Equal(1, assembly.Type("CountingInterceptor").GetField("Calls")!.GetValue(null)); + Verify(Equals(assembly.Type("CountingInterceptor").GetField("Calls")!.GetValue(null), 1)); } - [Fact] + [VerifyTest] public void ConventionUsing_IsReadAsItsValue() { var result = Run( @@ -264,16 +269,15 @@ public void Conventions(IConventionDefinitions conventions) result.AssertNoErrors(); - Assert.Contains( - "services.TryAddSingleton(", - result.SourceContaining("ConventionDependencies") + Verify( + result.SourceContaining("ConventionDependencies").Contains("services.TryAddSingleton(") ); } - [Theory] - [InlineData("IfEnvironmentValue(Keys.Feature, \"on\")", "'Keys.Feature'")] - [InlineData("WithName(\"Order*\", Keys.InvoicePattern)", "'Keys.InvoicePattern'")] - [InlineData("Using(Keys.Using)", "RegistrationType")] + [VerifyTest] + [Row("IfEnvironmentValue(Keys.Feature, \"on\")", "'Keys.Feature'")] + [Row("WithName(\"Order*\", Keys.InvoicePattern)", "'Keys.InvoicePattern'")] + [Row("Using(Keys.Using)", "RegistrationType")] public void AConventionArgumentThatIsNotAConstant_IsReported(string call, string named) { var result = Run( @@ -300,11 +304,11 @@ public void Conventions(IConventionDefinitions conventions) """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains(named, diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + Verify(diagnostic.GetMessage().Contains(named)); } - [Fact] + [VerifyTest] public void AConstantConventionArgument_IsRead() { var result = Run( @@ -331,7 +335,7 @@ public void Conventions(IConventionDefinitions conventions) result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains("\"FEATURE_X\"", result.SourceContaining("ConventionDependencies")); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0009")); + Verify(result.SourceContaining("ConventionDependencies").Contains("\"FEATURE_X\"")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs index 297113b..2efadc9 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ConventionContractTests.cs @@ -2,10 +2,9 @@ using DependencyModules.Runtime.Conventions; using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; using GeneratorNames = DependencyModules.Conventions.ConventionContractSource; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The generator matches convention declarations by name, and the names live in two places. @@ -22,26 +21,26 @@ namespace DependencyModules.Tests.GeneratorTests; /// registers nothing, which is the failure mode this generator exists to prevent everywhere else. /// /// -public class ConventionContractTests +public partial class ConventionContractTests { - [Fact] + [VerifyTest] public void TheGeneratorLooksForTheNamespaceTheContractsAreDeclaredIn() { - Assert.Equal(GeneratorNames.Namespace, typeof(IConventionModule).Namespace); + Verify(typeof(IConventionModule).Namespace == GeneratorNames.Namespace); } - [Fact] + [VerifyTest] public void TheGeneratorLooksForTheInterfaceTheContractsDeclare() { - Assert.Equal(GeneratorNames.ConventionModule, nameof(IConventionModule)); + Verify(typeof(IConventionModule).Name == GeneratorNames.ConventionModule); } - [Fact] + [VerifyTest] public void TheGeneratorLooksForTheMethodTheInterfaceDeclares() { - var method = Assert.Single(typeof(IConventionModule).GetMethods()); + var method = Single(typeof(IConventionModule).GetMethods()); - Assert.Equal(GeneratorNames.ConventionMethod, method.Name); + Verify(method.Name == GeneratorNames.ConventionMethod); } /// @@ -52,7 +51,7 @@ public void TheGeneratorLooksForTheMethodTheInterfaceDeclares() /// chain, which the fluent form exists to avoid. Asserted because it is the kind of thing a /// hurried addition gets wrong and nothing else would catch. /// - [Fact] + [VerifyTest] public void EveryRegistrationVerbContinuesTheChain() { var breaks = typeof(IConventionRegistration) @@ -61,13 +60,13 @@ public void EveryRegistrationVerbContinuesTheChain() .Select(method => method.Name) .ToArray(); - Assert.Empty(breaks); + Verify(breaks.Length == 0); } /// /// Every entry point produces a registration to continue from. /// - [Fact] + [VerifyTest] public void EveryRegisterAllOverloadStartsTheChain() { var breaks = typeof(IConventionDefinitions) @@ -76,7 +75,7 @@ public void EveryRegisterAllOverloadStartsTheChain() .Select(method => method.Name) .ToArray(); - Assert.Empty(breaks); + Verify(breaks.Length == 0); } private const string Preamble = """ @@ -102,7 +101,7 @@ public class Greeter : IGreeter { public string Greet() => "hello"; } /// The move to DependencyModules.Runtime is what retires that, and this is the assertion /// that it stays retired. /// - [Fact] + [VerifyTest] public void AnImplicitPublicImplementationDeclaresConventions() { var assembly = GeneratedAssembly.Create( @@ -119,16 +118,15 @@ public void Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); - Assert.Equal( - "hello", - ((dynamic)provider.GetRequiredService(assembly.Type("IGreeter"))).Greet() - ); + string greeting = ((dynamic)provider.GetRequiredService(assembly.Type("IGreeter"))).Greet(); + + Verify(greeting == "hello"); } /// /// The explicit form still compiles and still registers, so nobody has to rewrite anything. /// - [Fact] + [VerifyTest] public void TheExplicitImplementationStillDeclaresConventions() { var assembly = GeneratedAssembly.Create( @@ -145,9 +143,8 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); - Assert.Equal( - "hello", - ((dynamic)provider.GetRequiredService(assembly.Type("IGreeter"))).Greet() - ); + string greeting = ((dynamic)provider.GetRequiredService(assembly.Type("IGreeter"))).Greet(); + + Verify(greeting == "hello"); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs index 678838a..77aae1f 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ConventionDecoratorTests.cs @@ -1,8 +1,7 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Conventions and decorators together. @@ -14,7 +13,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// because an open generic registration cannot be decorated. The error blamed the open generic /// limitation, which is a long way from the cause. /// -public class ConventionDecoratorTests +public partial class ConventionDecoratorTests { private const string Preamble = """ using System.Collections.Generic; @@ -60,7 +59,7 @@ private static GeneratedAssembly Compile(string module) => /// One open generic decorator over every handler a convention registered — the ordinary MediatR /// shape, and the reason this combination has to work. /// - [Fact] + [VerifyTest] public void OneDecoratorWrapsEveryConventionRegisteredHandler() { var assembly = Compile( @@ -89,7 +88,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // Every handler resolves as the decorator, not as the implementation. - Assert.Equal("LoggingHandler`2", service.GetType().Name); + Verify(service.GetType().Name == "LoggingHandler`2"); service .GetType() @@ -97,13 +96,13 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Invoke(service, new[] { Activator.CreateInstance(requestType) }); } - Assert.Equal(["handling CreateOrder", "handling RenameOrder"], lines); + Verify(lines.SequenceEqual(["handling CreateOrder", "handling RenameOrder"])); } /// /// The decorator itself is not registered as a service. /// - [Fact] + [VerifyTest] public void ADecoratorIsNotAConventionCandidate() { var assembly = Compile( @@ -119,15 +118,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { // Two handlers, two registrations. The decorator rewrote them in place rather than adding // a third, and never registered itself as an open generic. - Assert.Equal(2, assembly.Services.Count(d => d.ServiceType.Name == "IRequestHandler`2")); + Verify(assembly.Services.Count(d => d.ServiceType.Name == "IRequestHandler`2") == 2); - Assert.DoesNotContain(assembly.Services, d => d.ServiceType.IsGenericTypeDefinition); + Verify(!assembly.Services.Any(d => d.ServiceType.IsGenericTypeDefinition)); } /// /// The exclusion is on the declaration, so it holds however the convention selects. /// - [Fact] + [VerifyTest] public void ADecoratorIsExcludedWhenSelectedByFilterRatherThanInterface() { var assembly = Compile( @@ -141,16 +140,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Contains( - assembly.Services, - d => d.ServiceType == assembly.Type("CreateOrderHandler") - ); - Assert.Contains( - assembly.Services, - d => d.ServiceType == assembly.Type("RenameOrderHandler") - ); + Verify(assembly.Services.Any(d => d.ServiceType == assembly.Type("CreateOrderHandler"))); + Verify(assembly.Services.Any(d => d.ServiceType == assembly.Type("RenameOrderHandler"))); // LoggingHandler ends in "Handler" and would otherwise match. - Assert.DoesNotContain(assembly.Services, d => d.ServiceType.Name == "LoggingHandler`2"); + Verify(!assembly.Services.Any(d => d.ServiceType.Name == "LoggingHandler`2")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs index 0a0f137..ed67059 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ConventionRegistrationTests.cs @@ -2,9 +2,8 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Behavioural tests for convention registration. @@ -14,7 +13,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// source passes happily while the wrong service type is registered, which is exactly the class of /// mistake convention matching is most likely to make. /// -public class ConventionRegistrationTests +public partial class ConventionRegistrationTests { private const string Preamble = """ using System; @@ -40,9 +39,9 @@ private static GeneratorResult Run(string source) => /// convention-matched class has no other route. Ignoring it would put a development-only /// service into production with nothing at the declaration saying why. /// - [Theory] - [InlineData("Development", 2)] - [InlineData("Production", 1)] + [VerifyTest] + [Row("Development", 2)] + [Row("Production", 1)] public void ConventionsHonourEnvironmentConditions(string environmentName, int expected) { const string source = """ @@ -66,16 +65,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(environmentName) ); - Assert.Equal(expected, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == expected); } /// /// A condition declared on the convention itself, gating every match rather than being repeated /// on each class. /// - [Theory] - [InlineData("Development", 2)] - [InlineData("Production", 0)] + [VerifyTest] + [Row("Development", 2)] + [Row("Production", 0)] public void ConventionsCarryTheirOwnEnvironmentCondition(string environmentName, int expected) { const string source = """ @@ -97,7 +96,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(environmentName) ); - Assert.Equal(expected, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == expected); } /// @@ -108,10 +107,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// the other. The environment pins its values, so a variable on the machine running this cannot /// reach REGION. /// - [Theory] - [InlineData("Development", "eu", 2)] - [InlineData("Development", "us", 1)] - [InlineData("Production", "eu", 0)] + [VerifyTest] + [Row("Development", "eu", 2)] + [Row("Development", "us", 1)] + [Row("Production", "eu", 0)] public void ConventionAndClassConditionsCombineWithAnd( string environmentName, string region, @@ -139,12 +138,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(false, environmentName) { { "REGION", region } } ); - Assert.Equal(expected, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == expected); } - [Theory] - [InlineData("on", 1)] - [InlineData("off", 0)] + [VerifyTest] + [Row("on", 1)] + [Row("off", 0)] public void ConventionsCarryValueConditions(string flag, int expected) { const string source = """ @@ -165,12 +164,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(false, "Development") { { "FLAG", flag } } ); - Assert.Equal(expected, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == expected); } - [Theory] - [InlineData("Development", 0)] - [InlineData("Production", 1)] + [VerifyTest] + [Row("Development", 0)] + [Row("Production", 1)] public void ConventionsCarryNegatedConditions(string environmentName, int expected) { const string source = """ @@ -191,7 +190,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(environmentName) ); - Assert.Equal(expected, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == expected); } /// @@ -202,9 +201,9 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// won would gate the other convention's registrations too — so IBar would vanish outside /// Development despite its convention saying nothing about the environment. /// - [Theory] - [InlineData("Development", 1, 1)] - [InlineData("Production", 0, 1)] + [VerifyTest] + [Row("Development", 1, 1)] + [Row("Production", 0, 1)] public void ConventionsWithDifferentConditionsDoNotShareAGuard( string environmentName, int expectedFoo, @@ -231,8 +230,8 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { environment: new ModuleEnvironment(environmentName) ); - Assert.Equal(expectedFoo, assembly.Descriptors("IFoo").Count); - Assert.Equal(expectedBar, assembly.Descriptors("IBar").Count); + Verify(assembly.Descriptors("IFoo").Count == expectedFoo); + Verify(assembly.Descriptors("IBar").Count == expectedBar); } /// @@ -244,7 +243,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// implementation type — read that as one class matched by two conventions. It reported DM0004 /// and registered nothing. One convention, named twice. /// - [Fact] + [VerifyTest] public void APartialClassReachingTheServiceFromTwoPartsIsNotAmbiguous() { const string source = """ @@ -263,17 +262,17 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } """; - Assert.DoesNotContain(Run(source).GeneratorDiagnostics, d => d.Id == "DM0004"); + Verify(!Run(source).GeneratorDiagnostics.Any(d => d.Id == "DM0004")); var assembly = Compile(source); - Assert.Equal(assembly.Type("Foo"), assembly.Descriptor("IFoo").ImplementationType); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Foo")); } /// /// Two parts declaring different interfaces that both reach the scanned one is still one class. /// - [Fact] + [VerifyTest] public void APartialClassDeclaringTheServiceTwiceIsNotAmbiguous() { const string source = """ @@ -291,16 +290,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } """; - Assert.DoesNotContain(Run(source).GeneratorDiagnostics, d => d.Id == "DM0004"); + Verify(!Run(source).GeneratorDiagnostics.Any(d => d.Id == "DM0004")); - Assert.Single(Compile(source).Descriptors("IFoo")); + Single(Compile(source).Descriptors("IFoo")); } /// /// Declaring the interface in any part is a declared match, so the base-class opt-in is not /// needed even when another part reaches the same interface through a base class. /// - [Fact] + [VerifyTest] public void APartDeclaringTheServiceMakesItADeclaredMatch() { const string source = """ @@ -319,7 +318,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } """; - Assert.Single(Compile(source).Descriptors("IFoo")); + Single(Compile(source).Descriptors("IFoo")); } /// @@ -330,7 +329,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// parameter list. Taking the first part's would emit a call to a constructor the type does not /// have, which is a CS error inside generated code. /// - [Fact] + [VerifyTest] public void TheConstructorMayBeDeclaredInAnotherPart() { const string source = """ @@ -360,14 +359,14 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var assembly = Compile(source); - Assert.IsType(assembly.Type("Foo"), assembly.ResolveRequired("IFoo")); + Verify(assembly.ResolveRequired("IFoo").GetType() == assembly.Type("Foo")); } /// /// A type filling two roles registers as both. This is the ordinary shape of a MediatR handler, /// and the two registrations are independently predictable from reading the module. /// - [Fact] + [VerifyTest] public void ATypeMatchedThroughDifferentInterfacesRegistersAsBoth() { const string source = """ @@ -386,12 +385,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } """; - Assert.DoesNotContain(Run(source).GeneratorDiagnostics, d => d.Id == "DM0004"); + Verify(!Run(source).GeneratorDiagnostics.Any(d => d.Id == "DM0004")); var assembly = Compile(source); - Assert.Equal(assembly.Type("Thing"), assembly.Descriptor("IFoo").ImplementationType); - Assert.Equal(assembly.Type("Thing"), assembly.Descriptor("IBar").ImplementationType); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Thing")); + Verify(assembly.Descriptor("IBar").ImplementationType == assembly.Type("Thing")); } /// @@ -399,7 +398,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// different service types are two instances — which is what Scrutor and MediatR both produce. /// Sharing one instance is AsSelfWithInterfaces, and it is opt-in. /// - [Fact] + [VerifyTest] public void EachRoleKeepsItsOwnLifetimeAndItsOwnInstance() { var assembly = Compile( @@ -419,14 +418,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(ServiceLifetime.Singleton, assembly.Descriptor("IFoo").Lifetime); - Assert.Equal(ServiceLifetime.Scoped, assembly.Descriptor("IBar").Lifetime); + Verify(assembly.Descriptor("IFoo").Lifetime == ServiceLifetime.Singleton); + Verify(assembly.Descriptor("IBar").Lifetime == ServiceLifetime.Scoped); var provider = assembly.BuildProvider(); - Assert.NotSame( - provider.GetService(assembly.Type("IFoo")), - provider.GetService(assembly.Type("IBar")) + Verify( + !ReferenceEquals( + provider.GetService(assembly.Type("IFoo")), + provider.GetService(assembly.Type("IBar")) + ) ); } @@ -437,7 +438,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// The MediatR shape. Registering only the first closing left the second silently unregistered: /// green build, no diagnostic, and an event that never fires. /// - [Fact] + [VerifyTest] public void OneConventionRegistersEveryClosingACandidateImplements() { var assembly = Compile( @@ -465,15 +466,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); - Assert.IsType(assembly.Type("OrderEvents"), provider.GetService(placed)); - Assert.IsType(assembly.Type("OrderEvents"), provider.GetService(shipped)); + Verify(provider.GetService(placed)?.GetType() == assembly.Type("OrderEvents")); + Verify(provider.GetService(shipped)?.GetType() == assembly.Type("OrderEvents")); } /// /// Several closings on one type are one implementation with several registrations, not several /// implementations — the shape the attribute path produces and the writer relies on. /// - [Fact] + [VerifyTest] public void SeveralClosingsProduceOneImplementationWithSeveralRegistrations() { var assembly = Compile( @@ -498,7 +499,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Services.Where(d => d.ImplementationType == assembly.Type("Both")) .ToArray(); - Assert.Equal(2, registered.Length); + Verify(registered.Length == 2); } private const string Marker = """ @@ -517,7 +518,7 @@ public class Unmarked : IFoo { } public class MarkedLegacy : IFoo { } """; - [Fact] + [VerifyTest] public void WithAttributeLimitsMatchesToTypesCarryingIt() { var assembly = Compile( @@ -538,13 +539,13 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Select(d => d.ImplementationType) .ToArray(); - Assert.Equal(2, implementations.Length); - Assert.Contains(assembly.Type("Marked"), implementations); - Assert.Contains(assembly.Type("MarkedLegacy"), implementations); - Assert.DoesNotContain(assembly.Type("Unmarked"), implementations); + Verify(implementations.Length == 2); + Verify(implementations.Contains(assembly.Type("Marked"))); + Verify(implementations.Contains(assembly.Type("MarkedLegacy"))); + Verify(!implementations.Contains(assembly.Type("Unmarked"))); } - [Fact] + [VerifyTest] public void WithoutAttributeExcludesTypesCarryingIt() { var assembly = Compile( @@ -565,11 +566,11 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Select(d => d.ImplementationType) .ToArray(); - Assert.Equal(2, implementations.Length); - Assert.DoesNotContain(assembly.Type("MarkedLegacy"), implementations); + Verify(implementations.Length == 2); + Verify(!implementations.Contains(assembly.Type("MarkedLegacy"))); } - [Fact] + [VerifyTest] public void AttributeFiltersCombineWithAnd() { var assembly = Compile( @@ -588,13 +589,13 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(assembly.Type("Marked"), assembly.Descriptor("IFoo").ImplementationType); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Marked")); } /// /// Resolved rather than matched on how it was written, so the qualified form counts. /// - [Fact] + [VerifyTest] public void ANamespaceQualifiedAttributeStillMatches() { var assembly = Compile( @@ -612,15 +613,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(2, assembly.Descriptors("IFoo").Count); + Verify(assembly.Descriptors("IFoo").Count == 2); } - [Theory] - [InlineData("*Repository", 2)] - [InlineData("Order*", 2)] - [InlineData("Order?epository", 1)] - [InlineData("TestNamespace.*Repository", 2)] - [InlineData("*repository", 0)] + [VerifyTest] + [Row("*Repository", 2)] + [Row("Order*", 2)] + [Row("Order?epository", 1)] + [Row("TestNamespace.*Repository", 2)] + [Row("*repository", 0)] public void WithNameMatchesTheGlob(string pattern, int expected) { var result = Run( @@ -641,7 +642,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { // A pattern matching nothing is DM0005 rather than silence. if (expected == 0) { - Assert.Contains(result.GeneratorDiagnostics, d => d.Id == "DM0005"); + Verify(result.GeneratorDiagnostics.Any(d => d.Id == "DM0005")); return; } @@ -662,13 +663,13 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal( - expected, + Verify( assembly.Services.Count(d => d.ImplementationType?.Namespace == "TestNamespace") + == expected ); } - [Fact] + [VerifyTest] public void AsRegistersEveryMatchAsOneNamedService() { var assembly = Compile( @@ -687,11 +688,11 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Empty(assembly.Descriptors("IFoo")); - Assert.Equal(assembly.Type("Foo"), assembly.Descriptor("IMarker").ImplementationType); + Verify(assembly.Descriptors("IFoo").Count == 0); + Verify(assembly.Descriptor("IMarker").ImplementationType == assembly.Type("Foo")); } - [Fact] + [VerifyTest] public void AsMatchingInterfaceRegistersFooAsIFoo() { var assembly = Compile( @@ -712,9 +713,9 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(assembly.Type("Foo"), assembly.Descriptor("IFoo").ImplementationType); - Assert.Equal(assembly.Type("Bar"), assembly.Descriptor("IBar").ImplementationType); - Assert.Empty(assembly.Descriptors("IMarker")); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Foo")); + Verify(assembly.Descriptor("IBar").ImplementationType == assembly.Type("Bar")); + Verify(assembly.Descriptors("IMarker").Count == 0); } /// @@ -724,7 +725,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// Any type whose base implements IDisposable would otherwise become resolvable as IDisposable, /// which is never what "register this as its interfaces" means. /// - [Fact] + [VerifyTest] public void AsSelfWithInterfacesSkipsSystemInterfaces() { var assembly = Compile( @@ -746,12 +747,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Single(assembly.Descriptors("IMarker")); + Single(assembly.Descriptors("IMarker")); - Assert.DoesNotContain(assembly.Services, d => d.ServiceType == typeof(IDisposable)); + Verify(!assembly.Services.Any(d => d.ServiceType == typeof(IDisposable))); } - [Fact] + [VerifyTest] public void AsSelfWithInterfacesSkipsGenericSystemInterfaces() { var assembly = Compile( @@ -778,19 +779,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // The validator interface survives; the enumerable ones do not. - Assert.Single(assembly.Services, d => d.ServiceType.Name == "IValidator`1"); + Single(assembly.Services, d => d.ServiceType.Name == "IValidator`1"); - Assert.DoesNotContain( - assembly.Services, - d => d.ServiceType.Namespace?.StartsWith("System") == true - ); + Verify(!assembly.Services.Any(d => d.ServiceType.Namespace?.StartsWith("System") == true)); } /// /// The filter is scoped to the expansion. A service type the developer named is honoured /// whatever namespace it lives in — refusing that is a different kind of wrong. /// - [Fact] + [VerifyTest] public void ANamedSystemServiceTypeIsStillRegistered() { var assembly = Compile( @@ -808,13 +806,13 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Single(assembly.Services, d => d.ServiceType == typeof(IDisposable)); + Single(assembly.Services, d => d.ServiceType == typeof(IDisposable)); } /// /// Filtering everything away degrades to AsSelf rather than to nothing. /// - [Fact] + [VerifyTest] public void ATypeReachingOnlySystemInterfacesRegistersItself() { var assembly = Compile( @@ -836,7 +834,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { // Nothing to assert beyond the module compiling and registering something; the shape that // matters is covered by AsSelfWithInterfacesSkipsSystemInterfaces. - Assert.NotEmpty(assembly.Services); + Verify(assembly.Services.Any()); } private const string Validators = """ @@ -857,7 +855,7 @@ public class FooValidator : AbstractValidator { } /// /// The FluentValidation shape: registered as the matched interface and as the concrete type. /// - [Fact] + [VerifyTest] public void AlsoAsSelfRegistersTheInterfaceAndTheType() { var assembly = Compile( @@ -873,15 +871,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Contains(assembly.Services, d => d.ServiceType.Name == "IValidator`1"); - Assert.Contains(assembly.Services, d => d.ServiceType == assembly.Type("FooValidator")); + Verify(assembly.Services.Any(d => d.ServiceType.Name == "IValidator`1")); + Verify(assembly.Services.Any(d => d.ServiceType == assembly.Type("FooValidator"))); } /// /// Cross-wired, so both routes give one instance per scope. FluentValidation registers the pair /// independently and hands you two; this is a deliberate difference. /// - [Fact] + [VerifyTest] public void AlsoAsSelfSharesOneInstance() { var assembly = Compile( @@ -904,16 +902,18 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Services.First(d => d.ServiceType.Name == "IValidator`1") .ServiceType; - Assert.Same( - scope.ServiceProvider.GetService(validatorInterface), - scope.ServiceProvider.GetService(assembly.Type("FooValidator")) + Verify( + ReferenceEquals( + scope.ServiceProvider.GetService(validatorInterface), + scope.ServiceProvider.GetService(assembly.Type("FooValidator")) + ) ); } /// /// Only the interfaces the convention matched, not everything the type can reach. /// - [Fact] + [VerifyTest] public void AlsoAsSelfDoesNotPullInUnmatchedInterfaces() { var assembly = Compile( @@ -930,14 +930,11 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // IValidator and the enumerable interfaces are reachable but were not matched. - Assert.DoesNotContain(assembly.Services, d => d.ServiceType == assembly.Type("IValidator")); - Assert.DoesNotContain( - assembly.Services, - d => d.ServiceType.Namespace?.StartsWith("System") == true - ); + Verify(!assembly.Services.Any(d => d.ServiceType == assembly.Type("IValidator"))); + Verify(!assembly.Services.Any(d => d.ServiceType.Namespace?.StartsWith("System") == true)); } - [Fact] + [VerifyTest] public void AsSelfAndAlsoAsSelfTogetherIsRefused() { var result = Run( @@ -954,14 +951,14 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); } /// /// A handler closing two messages asks for the self registration twice and means it once. One /// convention repeating itself is not an ambiguity. /// - [Fact] + [VerifyTest] public void AlsoAsSelfRegistersTheTypeOnceAcrossSeveralClosings() { var result = Run( @@ -982,7 +979,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0004"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0004")); var assembly = Compile( """ @@ -1002,11 +999,11 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Single(assembly.Services, d => d.ServiceType == assembly.Type("Both")); - Assert.Equal(2, assembly.Services.Count(d => d.ServiceType.Name == "IHandler`1")); + Single(assembly.Services, d => d.ServiceType == assembly.Type("Both")); + Verify(assembly.Services.Count(d => d.ServiceType.Name == "IHandler`1") == 2); } - [Fact] + [VerifyTest] public void UsingChoosesHowTheRegistrationIsAdded() { var assembly = Compile( @@ -1025,10 +1022,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // Try registers the service type once and skips the second match. - Assert.Single(assembly.Descriptors("IFoo")); + Single(assembly.Descriptors("IFoo")); } - [Fact] + [VerifyTest] public void WithKeyRegistersUnderAServiceKey() { var assembly = Compile( @@ -1047,12 +1044,14 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var descriptor = assembly.Descriptor("IFoo"); - Assert.True(descriptor.IsKeyedService); - Assert.Equal("primary", descriptor.ServiceKey); + Verify(descriptor.IsKeyedService); + Verify(Equals(descriptor.ServiceKey, "primary")); - Assert.IsType( - assembly.Type("Foo"), - assembly.BuildProvider().GetRequiredKeyedService(assembly.Type("IFoo"), "primary") + Verify( + assembly + .BuildProvider() + .GetRequiredKeyedService(assembly.Type("IFoo"), "primary") + .GetType() == assembly.Type("Foo") ); } @@ -1060,7 +1059,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// The case DM0004 exists for: one service type claimed twice, so one lifetime has to win and /// the source does not say which. /// - [Fact] + [VerifyTest] public void TwoConventionsRegisteringOneServiceTypeIsAmbiguous() { var result = Run( @@ -1080,17 +1079,17 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0004"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0004"); - Assert.Contains("different lifetimes", diagnostic.GetMessage()); - Assert.Contains("IFoo", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("different lifetimes")); + Verify(diagnostic.GetMessage().Contains("IFoo")); } /// /// Equal lifetimes are still an error. The outcome is predictable, but the declaration is /// redundant and collapsing it silently is the failure mode this codebase avoids. /// - [Fact] + [VerifyTest] public void ADuplicatedConventionIsAmbiguousEvenWithEqualLifetimes() { var result = Run( @@ -1109,12 +1108,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0004"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0004"); - Assert.Contains("duplicated", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("duplicated")); } - [Fact] + [VerifyTest] public void AsSelfRegistersTheConcreteTypeRatherThanTheService() { var assembly = Compile( @@ -1131,15 +1130,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Empty(assembly.Descriptors("IFoo")); - Assert.Single(assembly.Descriptors("Foo")); + Verify(assembly.Descriptors("IFoo").Count == 0); + Single(assembly.Descriptors("Foo")); } /// /// AsSelfWithInterfaces promises one instance reachable through the type and every interface, /// which is why it emits the cross-wire shape rather than two independent registrations. /// - [Fact] + [VerifyTest] public void AsSelfWithInterfacesSharesOneInstance() { var assembly = Compile( @@ -1163,15 +1162,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var asIFoo = provider.GetService(assembly.Type("IFoo")); var asIBar = provider.GetService(assembly.Type("IBar")); - Assert.NotNull(asFoo); - Assert.Same(asFoo, asIFoo); - Assert.Same(asFoo, asIBar); + Verify(asFoo is not null); + Verify(ReferenceEquals(asFoo, asIFoo)); + Verify(ReferenceEquals(asFoo, asIBar)); } /// /// The hole this closes: a concrete class implementing nothing, selected by namespace. /// - [Fact] + [VerifyTest] public void AConcreteTypeWithNoInterfaceRegistersByNamespace() { var assembly = Compile( @@ -1188,11 +1187,11 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Single(assembly.Descriptors("OrderCalculator")); - Assert.Single(assembly.Descriptors("OrderValidator")); + Single(assembly.Descriptors("OrderCalculator")); + Single(assembly.Descriptors("OrderValidator")); } - [Fact] + [VerifyTest] public void NamespaceFiltersNarrowAnAssignabilityConvention() { var result = Run( @@ -1210,10 +1209,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // Filtered out entirely, which is DM0005 rather than silence. - Assert.Contains(result.GeneratorDiagnostics, d => d.Id == "DM0005"); + Verify(result.GeneratorDiagnostics.Any(d => d.Id == "DM0005")); } - [Fact] + [VerifyTest] public void NotInNamespacesExcludesAfterInclusions() { var assembly = Compile( @@ -1230,10 +1229,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Empty(assembly.Descriptors("IFoo")); + Verify(assembly.Descriptors("IFoo").Count == 0); } - [Fact] + [VerifyTest] public void RegisterAllWithNoServiceTypeNeedsAShape() { var result = Run( @@ -1249,15 +1248,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains("AsSelf", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("AsSelf")); } /// /// Without a filter it would match every class in the compilation, so it is refused. /// - [Fact] + [VerifyTest] public void RegisterAllWithNoServiceTypeAndNoFilterIsRefused() { var result = Run( @@ -1273,12 +1272,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains("every class", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("every class")); } - [Fact] + [VerifyTest] public void RegistersEveryTypeDeclaringTheServiceInterface() { var assembly = Compile( @@ -1300,13 +1299,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var descriptors = assembly.Descriptors("IFoo"); - Assert.Equal(2, descriptors.Count); - Assert.All(descriptors, d => Assert.Equal(ServiceLifetime.Singleton, d.Lifetime)); - Assert.Contains(descriptors, d => d.ImplementationType == assembly.Type("FooOne")); - Assert.Contains(descriptors, d => d.ImplementationType == assembly.Type("FooTwo")); + Verify(descriptors.Count == 2); + foreach (var d in descriptors) + { + Verify(d.Lifetime == ServiceLifetime.Singleton); + } + Verify(descriptors.Any(d => d.ImplementationType == assembly.Type("FooOne"))); + Verify(descriptors.Any(d => d.ImplementationType == assembly.Type("FooTwo"))); } - [Fact] + [VerifyTest] public void RegisteredServiceResolves() { var assembly = Compile( @@ -1323,15 +1325,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.IsType(assembly.Type("Foo"), assembly.ResolveRequired("IFoo")); - Assert.Equal(ServiceLifetime.Scoped, assembly.Descriptor("IFoo").Lifetime); + Verify(assembly.ResolveRequired("IFoo").GetType() == assembly.Type("Foo")); + Verify(assembly.Descriptor("IFoo").Lifetime == ServiceLifetime.Scoped); } /// /// An interface declaring that it extends another is a deliberate statement of substitutability, /// so a convention naming the base interface matches by declaration. /// - [Fact] + [VerifyTest] public void MatchesThroughInterfaceInheritance() { var assembly = Compile( @@ -1350,7 +1352,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(assembly.Type("Thing"), assembly.Descriptor("IFoo").ImplementationType); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Thing")); } /// @@ -1358,7 +1360,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// and every subclass added later would join the convention with nobody revisiting it. So it /// takes an explicit opt-in. /// - [Fact] + [VerifyTest] public void DoesNotMatchThroughABaseClassByDefault() { var result = Run( @@ -1377,10 +1379,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ); // Nothing matched, which is DM0005 rather than silence. - Assert.Contains(result.GeneratorDiagnostics, d => d.Id == "DM0005"); + Verify(result.GeneratorDiagnostics.Any(d => d.Id == "DM0005")); } - [Fact] + [VerifyTest] public void MatchesThroughABaseClassWhenAskedTo() { var assembly = Compile( @@ -1398,14 +1400,14 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal(assembly.Type("Thing"), assembly.Descriptor("IFoo").ImplementationType); + Verify(assembly.Descriptor("IFoo").ImplementationType == assembly.Type("Thing")); } /// /// The make-or-break behaviour for open generics: the match registers the closed construction it /// actually implements, not the open definition. /// - [Fact] + [VerifyTest] public void ClosesAnOpenGenericAgainstEachImplementation() { var assembly = Compile( @@ -1438,15 +1440,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); - Assert.IsType(assembly.Type("CreateOrderHandler"), provider.GetService(createOrder)); - Assert.IsType(assembly.Type("RenameHandler"), provider.GetService(rename)); + Verify(provider.GetService(createOrder)?.GetType() == assembly.Type("CreateOrderHandler")); + Verify(provider.GetService(rename)?.GetType() == assembly.Type("RenameHandler")); } /// /// A closed convention registers only that construction. Without this, /// RegisterAll<IHandler<A,B>>() would pick up every other closing too. /// - [Fact] + [VerifyTest] public void AClosedGenericConventionMatchesOnlyThatConstruction() { var assembly = Compile( @@ -1467,15 +1469,15 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var repo = assembly.Type("IRepo`1"); var provider = assembly.BuildProvider(); - Assert.IsType( - assembly.Type("IntRepo"), - provider.GetService(repo.MakeGenericType(typeof(int))) + Verify( + provider.GetService(repo.MakeGenericType(typeof(int)))?.GetType() + == assembly.Type("IntRepo") ); - Assert.Null(provider.GetService(repo.MakeGenericType(typeof(string)))); + Verify(provider.GetService(repo.MakeGenericType(typeof(string))) is null); } - [Fact] + [VerifyTest] public void AnExplicitServiceAttributeBeatsTheConvention() { var assembly = Compile( @@ -1504,18 +1506,18 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .Where(d => d.ImplementationType == assembly.Type("Attributed")) .ToArray(); - Assert.Single(attributed); - Assert.Equal(ServiceLifetime.Singleton, attributed[0].Lifetime); + Single(attributed); + Verify(attributed[0].Lifetime == ServiceLifetime.Singleton); var byConvention = descriptors .Where(d => d.ImplementationType == assembly.Type("ByConvention")) .ToArray(); - Assert.Single(byConvention); - Assert.Equal(ServiceLifetime.Transient, byConvention[0].Lifetime); + Single(byConvention); + Verify(byConvention[0].Lifetime == ServiceLifetime.Transient); } - [Fact] + [VerifyTest] public void OmittingTheLifetimeIsRefused() { var result = Run( @@ -1532,9 +1534,9 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains("lifetime", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("lifetime")); } /// @@ -1542,14 +1544,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// has no meaning. Refused rather than skipped: dropping it would lose registrations while the /// build stayed green. /// - [Theory] - [InlineData( - "foreach (var t in new Type[0]) { conventions.RegisterAll().AsSingleton(); }" - )] - [InlineData("if (DateTime.Now.Day > 1) { conventions.RegisterAll().AsSingleton(); }")] - [InlineData("var x = 5;")] - [InlineData("Helper(conventions);")] - [InlineData("conventions.RegisterAll().AsSingleton().AsScoped();")] + [VerifyTest] + [Row("foreach (var t in new Type[0]) { conventions.RegisterAll().AsSingleton(); }")] + [Row("if (DateTime.Now.Day > 1) { conventions.RegisterAll().AsSingleton(); }")] + [Row("var x = 5;")] + [Row("Helper(conventions);")] + [Row("conventions.RegisterAll().AsSingleton().AsScoped();")] public void UnreadableStatementsAreRefused(string statement) { var result = Run( @@ -1568,7 +1568,7 @@ private static void Helper(IConventionDefinitions c) { } """ ); - Assert.Contains(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + Verify(result.GeneratorDiagnostics.Any(d => d.Id == "DM0009")); } // TwoConventionsMatchingOneTypeIsAmbiguous lived here. It asserted DM0004 for a type matched @@ -1577,7 +1577,7 @@ private static void Helper(IConventionDefinitions c) { } // registers rather than that it refuses. TwoConventionsRegisteringOneServiceTypeIsAmbiguous // keeps DM0004 honest for the case it exists for. - [Fact] + [VerifyTest] public void AConcreteTypeWithNoAccessibleConstructorIsReported() { var result = Run( @@ -1597,16 +1597,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); - Assert.Contains("Hidden", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("Hidden")); } /// /// The class carries no attribute saying it is registered, so this is the only thing at the /// declaration that explains why it is in the container. /// - [Fact] + [VerifyTest] public void ReportsWhatEachClassIsExposedAs() { var result = Run( @@ -1628,14 +1628,16 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var exposures = result.GeneratorDiagnostics.Where(d => d.Id == "DM0010").ToArray(); - Assert.Equal(2, exposures.Length); - Assert.All(exposures, d => Assert.Equal(DiagnosticSeverity.Info, d.Severity)); + Verify(exposures.Length == 2); + foreach (var d in exposures) + { + Verify(d.Severity == DiagnosticSeverity.Info); + } // The indirect match names the hop, which is what keeps it from reading as luck. - Assert.Contains(exposures, d => d.GetMessage() == "Exposed as IFoo in TestModule"); - Assert.Contains( - exposures, - d => d.GetMessage() == "Exposed as IFoo in TestModule (via IFooPrime)" + Verify(exposures.Any(d => d.GetMessage() == "Exposed as IFoo in TestModule")); + Verify( + exposures.Any(d => d.GetMessage() == "Exposed as IFoo in TestModule (via IFooPrime)") ); } @@ -1644,7 +1646,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// directly in an incremental model — a Location pins its SyntaxTree — so it is rebuilt from /// primitives at output. This asserts the rebuild lands on the right line. /// - [Fact] + [VerifyTest] public void ExposureIsReportedOnTheClassItself() { const string body = """ @@ -1662,21 +1664,21 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { var result = Run(body); - var exposure = Assert.Single(result.GeneratorDiagnostics.Where(d => d.Id == "DM0010")); + var exposure = Single(result.GeneratorDiagnostics.Where(d => d.Id == "DM0010")); var span = exposure.Location.GetLineSpan(); - Assert.EndsWith("Test.cs", span.Path); + Verify(span.Path.EndsWith("Test.cs")); var lines = (Preamble + body).Replace("\r\n", "\n").Split('\n'); - Assert.Contains("class Foo", lines[span.StartLinePosition.Line]); + Verify(lines[span.StartLinePosition.Line].Contains("class Foo")); } /// /// A type implementing IConventionModule that is not a module registers nothing at all, so it is /// reported rather than left to fail silently. /// - [Fact] + [VerifyTest] public void ConventionsOnANonModuleAreReported() { var result = Run( @@ -1695,12 +1697,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0009"); - Assert.Contains("NotAModule", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("NotAModule")); } - [Fact] + [VerifyTest] public void EditingAnUnrelatedMethodBodyReusesTheCachedOutput() { const string template = """ @@ -1728,8 +1730,12 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { new Dictionary { ["Test.cs"] = template.Replace("VALUE", "2") } ); - Assert.Equal(result.FirstRun, result.SecondRun); - Assert.True( + Verify(result.SecondRun.Count == result.FirstRun.Count); + foreach (var (hintName, source) in result.FirstRun) + { + Verify(result.SecondRun.TryGetValue(hintName, out var second) && second == source); + } + Verify( result.AllOutputsCached, "editing a method body cannot change any registration, so every output should be cached" ); diff --git a/tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs b/tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs index 5e17e18..fefedd3 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/CrossWireTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// A cross-wired class is registered once, and each interface it declares resolves that one /// registration. These tests build the generated code and resolve from it, because the defects /// were in code that did not compile or that threw when the module was applied. /// -public class CrossWireTests +public partial class CrossWireTests { private const string Preamble = """ using System; @@ -30,7 +29,7 @@ private static GeneratedAssembly Compile(string source) => private static GeneratorResult Run(string source) => GeneratorTestHarness.Run(Preamble + source); - [Fact] + [VerifyTest] public void AKeyedClass_SharesOneInstanceUnderItsKey() { var assembly = Compile( @@ -46,11 +45,21 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var store = provider.GetRequiredKeyedService(assembly.Type("Store"), "store"); - Assert.Same(store, provider.GetRequiredKeyedService(assembly.Type("IReader"), "store")); - Assert.Same(store, provider.GetRequiredKeyedService(assembly.Type("IWriter"), "store")); + Verify( + ReferenceEquals( + store, + provider.GetRequiredKeyedService(assembly.Type("IReader"), "store") + ) + ); + Verify( + ReferenceEquals( + store, + provider.GetRequiredKeyedService(assembly.Type("IWriter"), "store") + ) + ); } - [Fact] + [VerifyTest] public void AKeyedConventionWithAlsoAsSelf_SharesOneInstanceUnderItsKey() { var assembly = Compile( @@ -70,19 +79,21 @@ public void Conventions(IConventionDefinitions conventions) var provider = assembly.BuildProvider(); - Assert.Same( - provider.GetRequiredKeyedService(assembly.Type("Store"), "rules"), - provider.GetRequiredKeyedService(assembly.Type("IReader"), "rules") + Verify( + ReferenceEquals( + provider.GetRequiredKeyedService(assembly.Type("Store"), "rules"), + provider.GetRequiredKeyedService(assembly.Type("IReader"), "rules") + ) ); } - [Theory] - [InlineData("[CrossWireService(Using = RegistrationType.Try)]", "[DependencyModule]")] - [InlineData("[CrossWireService(Using = RegistrationType.TryEnumerable)]", "[DependencyModule]")] - [InlineData("[CrossWireService(Using = RegistrationType.Replace)]", "[DependencyModule]")] - [InlineData("[CrossWireService]", "[DependencyModule(Using = RegistrationType.Try)]")] - [InlineData("[CrossWireService]", "[DependencyModule(Using = RegistrationType.TryEnumerable)]")] - [InlineData( + [VerifyTest] + [Row("[CrossWireService(Using = RegistrationType.Try)]", "[DependencyModule]")] + [Row("[CrossWireService(Using = RegistrationType.TryEnumerable)]", "[DependencyModule]")] + [Row("[CrossWireService(Using = RegistrationType.Replace)]", "[DependencyModule]")] + [Row("[CrossWireService]", "[DependencyModule(Using = RegistrationType.Try)]")] + [Row("[CrossWireService]", "[DependencyModule(Using = RegistrationType.TryEnumerable)]")] + [Row( "[CrossWireService]", "[DependencyModule(Using = RegistrationType.TryEnumerable, GenerateFactories = true)]" )] @@ -101,12 +112,12 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var store = provider.GetRequiredService(assembly.Type("Store")); - Assert.Same(store, provider.GetRequiredService(assembly.Type("IReader"))); - Assert.Same(store, provider.GetRequiredService(assembly.Type("IWriter"))); - Assert.Single(assembly.Descriptors("Store")); + Verify(ReferenceEquals(store, provider.GetRequiredService(assembly.Type("IReader")))); + Verify(ReferenceEquals(store, provider.GetRequiredService(assembly.Type("IWriter")))); + Single(assembly.Descriptors("Store")); } - [Fact] + [VerifyTest] public void TheClassRegistration_UsesTheRegistrationTypeOfTheModule() { var result = Run( @@ -123,15 +134,15 @@ public partial class TestModule; var registrations = result.SourceContaining("Dependencies"); - Assert.Contains("services.TryAddSingleton(", registrations); - Assert.Contains("services.TryAdd(new", registrations); - Assert.DoesNotContain("services.Add(new", registrations); + Verify(registrations.Contains("services.TryAddSingleton(")); + Verify(registrations.Contains("services.TryAdd(new")); + Verify(!registrations.Contains("services.Add(new")); } /// /// TryAddEnumerable identifies a factory registration by the return type of its delegate. /// - [Fact] + [VerifyTest] public void TryEnumerable_KeepsOneRegistrationOfEachInterface() { var assembly = Compile( @@ -149,11 +160,11 @@ public partial class TestModule; module.InternalApplyServices(assembly.Services); - Assert.Single(assembly.Descriptors("IReader")); - Assert.Single(assembly.Descriptors("Store")); + Single(assembly.Descriptors("IReader")); + Single(assembly.Descriptors("Store")); } - [Fact] + [VerifyTest] public void AGeneratedFactoryWithTryEnumerable_CanBeApplied() { var assembly = Compile( @@ -166,12 +177,12 @@ public partial class TestModule; """ ); - Assert.Equal("Reader", assembly.ResolveRequired("IReader").GetType().Name); + Verify(assembly.ResolveRequired("IReader").GetType().Name == "Reader"); } - [Theory] - [InlineData("AlsoAsSelf()")] - [InlineData("AsSelfWithInterfaces()")] + [VerifyTest] + [Row("AlsoAsSelf()")] + [Row("AsSelfWithInterfaces()")] public void AConventionThatCrossWiresAGenericClass_IsReported(string shape) { var result = Run( @@ -197,14 +208,14 @@ public void Conventions(IConventionDefinitions conventions) result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0014"); - Assert.Contains("'Repository'", diagnostic.GetMessage()); - Assert.Contains("the convention registering", diagnostic.GetMessage()); - Assert.DoesNotContain("Repository<>", result.SourceContaining("ConventionDependencies")); - Assert.Contains("Plain", result.SourceContaining("ConventionDependencies")); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0014"); + Verify(diagnostic.GetMessage().Contains("'Repository'")); + Verify(diagnostic.GetMessage().Contains("the convention registering")); + Verify(!result.SourceContaining("ConventionDependencies").Contains("Repository<>")); + Verify(result.SourceContaining("ConventionDependencies").Contains("Plain")); } - [Fact] + [VerifyTest] public void AClassThatInheritsItsInterfaces_IsRegistered_AndReported() { var result = Run( @@ -221,16 +232,16 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0024"); - Assert.Contains("'Store'", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0024"); + Verify(diagnostic.GetMessage().Contains("'Store'")); var registrations = result.SourceContaining("Dependencies"); - Assert.Contains("typeof(global::TestNamespace.Store)", registrations); - Assert.DoesNotContain("IReader", registrations); + Verify(registrations.Contains("typeof(global::TestNamespace.Store)")); + Verify(!registrations.Contains("IReader")); } - [Fact] + [VerifyTest] public void AClassWithNoInterface_IsRegistered_WithoutAWarning() { var assembly = Compile( @@ -243,22 +254,22 @@ public partial class TestModule; """ ); - Assert.Equal("Store", assembly.ResolveRequired("Store").GetType().Name); - Assert.DoesNotContain( - Run( - """ - [CrossWireService] - public class Store { } + Verify(assembly.ResolveRequired("Store").GetType().Name == "Store"); - [DependencyModule] - public partial class TestModule; - """ - ).GeneratorDiagnostics, - d => d.Id == "DM0024" - ); + var diagnostics = Run( + """ + [CrossWireService] + public class Store { } + + [DependencyModule] + public partial class TestModule; + """ + ).GeneratorDiagnostics; + + Verify(!diagnostics.Any(d => d.Id == "DM0024")); } - [Fact] + [VerifyTest] public void AnInterfaceOnAnotherPartialDeclaration_IsCrossWired() { var assembly = Compile( @@ -275,13 +286,15 @@ public partial class TestModule; var provider = assembly.BuildProvider(); - Assert.Same( - provider.GetRequiredService(assembly.Type("Store")), - provider.GetRequiredService(assembly.Type("IReader")) + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("Store")), + provider.GetRequiredService(assembly.Type("IReader")) + ) ); } - [Fact] + [VerifyTest] public void AFactoryMethod_RegistersItsReturnTypeAndTheInterfacesItDeclares() { var assembly = Compile( @@ -307,12 +320,12 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var store = provider.GetRequiredService(assembly.Type("Store")); - Assert.Same(store, provider.GetRequiredService(assembly.Type("IReader"))); - Assert.Same(store, provider.GetRequiredService(assembly.Type("IWriter"))); - Assert.Equal(1, assembly.Type("Store").GetField("Created")!.GetValue(null)); + Verify(ReferenceEquals(store, provider.GetRequiredService(assembly.Type("IReader")))); + Verify(ReferenceEquals(store, provider.GetRequiredService(assembly.Type("IWriter")))); + Verify(Equals(assembly.Type("Store").GetField("Created")!.GetValue(null), 1)); } - [Fact] + [VerifyTest] public void AFactoryMethodThatReturnsAnInterface_RegistersIt() { var assembly = Compile( @@ -330,6 +343,6 @@ public partial class TestModule; """ ); - Assert.Equal("Reader", assembly.ResolveRequired("IReader").GetType().Name); + Verify(assembly.ResolveRequired("IReader").GetType().Name == "Reader"); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs index 34a150e..cbe86ac 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/DeclaredApplicationModuleTests.cs @@ -4,9 +4,8 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Program.cs names modules with assembly attributes and with calls to their static methods. @@ -14,7 +13,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// ApplicationModule in the root namespace, the declared module takes the place of the /// generated one, so it has to load them too. /// -public class DeclaredApplicationModuleTests +public partial class DeclaredApplicationModuleTests { private const string LibrarySource = """ using DependencyModules.Runtime.Attributes; @@ -58,16 +57,16 @@ namespace WebShop; public partial class ApplicationModule; """; - [Fact] + [VerifyTest] public void TheGeneratedModule_LoadsTheModulesThatProgramNames() { var services = Apply(new Dictionary { ["Program.cs"] = Program }); - Assert.True(Registered(services, "Catalog.ICatalog")); - Assert.True(Registered(services, "Catalog.IPricing")); + Verify(Registered(services, "Catalog.ICatalog")); + Verify(Registered(services, "Catalog.IPricing")); } - [Fact] + [VerifyTest] public void ADeclaredModule_LoadsTheModulesThatProgramNames() { var services = Apply( @@ -78,15 +77,15 @@ public void ADeclaredModule_LoadsTheModulesThatProgramNames() } ); - Assert.True(Registered(services, "Catalog.ICatalog")); - Assert.True(Registered(services, "Catalog.IPricing")); + Verify(Registered(services, "Catalog.ICatalog")); + Verify(Registered(services, "Catalog.IPricing")); } /// /// A module that the project declares itself. Its attribute is written by the same run of the /// generator. /// - [Fact] + [VerifyTest] public void ADeclaredModule_LoadsALocalModuleThatProgramNames() { var services = Apply( @@ -116,7 +115,7 @@ public partial class StockModule; } ); - Assert.True(Registered(services, "WebShop.Parts.IStock")); + Verify(Registered(services, "WebShop.Parts.IStock")); } private static int _counter; @@ -144,7 +143,7 @@ private static IServiceCollection Apply(Dictionary sources) using var stream = new MemoryStream(); var emitted = result.Compilation.Emit(stream); - Assert.True( + Verify( emitted.Success, string.Join( Environment.NewLine, diff --git a/tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs index 6ba19ed..2f42c06 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/DecoratorGenerationTests.cs @@ -2,17 +2,16 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Decoration verified by resolving from a real container built from generated code, rather than by /// matching the generated text. The registrations are the point; their shape is not. /// -public class DecoratorGenerationTests +public partial class DecoratorGenerationTests { - [Fact] + [VerifyTest] public void Decorator_WrapsTheRegisteredImplementation() { var generated = GeneratedAssembly.Create( @@ -26,10 +25,10 @@ public class LoudGreeter(IGreeter inner) : IGreeter { ) ); - Assert.Equal("HELLO", Greet(generated)); + Verify(Greet(generated) == "HELLO"); } - [Fact] + [VerifyTest] public void Decorator_PreservesTheServiceLifetime() { var generated = GeneratedAssembly.Create( @@ -43,13 +42,13 @@ public class LoudGreeter(IGreeter inner) : IGreeter { ) ); - Assert.Equal(ServiceLifetime.Singleton, generated.Descriptor("IGreeter").Lifetime); + Verify(generated.Descriptor("IGreeter").Lifetime == ServiceLifetime.Singleton); } /// /// Lower order sits closer to the implementation, so the higher-order decorator is outermost. /// - [Fact] + [VerifyTest] public void Decorators_NestByAscendingOrder() { var generated = GeneratedAssembly.Create( @@ -68,10 +67,10 @@ public class OuterGreeter(IGreeter inner) : IGreeter { ) ); - Assert.Equal("outer(inner(hello))", Greet(generated)); + Verify(Greet(generated) == "outer(inner(hello))"); } - [Fact] + [VerifyTest] public void Decorator_ReceivesItsOwnDependencies() { var generated = GeneratedAssembly.Create( @@ -90,10 +89,10 @@ public class PrefixedGreeter(IGreeter inner, IPrefix prefix) : IGreeter { ) ); - Assert.Equal("pre-hello", Greet(generated)); + Verify(Greet(generated) == "pre-hello"); } - [Fact] + [VerifyTest] public void OpenGenericDecorator_WrapsEveryClosedRegistration() { var generated = GeneratedAssembly.Create( @@ -123,13 +122,13 @@ public partial class TestModule; var provider = generated.BuildProvider(); var handler = generated.Type("IHandler`1"); - Assert.Equal( - "validated(string)", + Verify( Invoke(provider.GetService(handler.MakeGenericType(typeof(string)))!, "Handle") + == "validated(string)" ); - Assert.Equal( - "validated(int)", + Verify( Invoke(provider.GetService(handler.MakeGenericType(typeof(int)))!, "Handle") + == "validated(int)" ); } @@ -147,7 +146,7 @@ public partial class TestModule; /// as one, so there is nothing to emit and nothing to refuse at composition either. /// /// - [Fact] + [VerifyTest] public void OpenGenericRegistration_IsNotDecorated() { var result = GeneratorTestHarness.Run( @@ -173,18 +172,19 @@ public partial class TestModule; // Nothing is emitted for it, so the registration stands undecorated rather than the // provider throwing when it is built. - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); - Assert.DoesNotContain( - result.GeneratedSources, - source => source.Key.Contains("Decorators") && source.Value.Contains("LoggingRepo") + Verify( + !result.GeneratedSources.Any(source => + source.Key.Contains("Decorators") && source.Value.Contains("LoggingRepo") + ) ); } /// /// The way through, end to end: a closed construction of the generic service is decorated. /// - [Fact] + [VerifyTest] public void ClosedConstructionOfAGenericService_IsDecorated() { var generated = GeneratedAssembly.Create( @@ -215,10 +215,10 @@ public partial class TestModule; generated.Type("IRepo`1").MakeGenericType(typeof(string)) )!; - Assert.Equal("logged(repo)", Invoke(resolved, "Name")); + Verify(Invoke(resolved, "Name") == "logged(repo)"); } - [Fact] + [VerifyTest] public void ModuleLevelDecorate_WrapsAServiceTheModuleDoesNotDeclare() { var generated = GeneratedAssembly.Create( @@ -242,10 +242,10 @@ public partial class TestModule; """ ); - Assert.Equal("HELLO", Greet(generated)); + Verify(Greet(generated) == "HELLO"); } - [Fact] + [VerifyTest] public void Decorator_WithExplicitService_UsesIt() { var generated = GeneratedAssembly.Create( @@ -259,21 +259,21 @@ public class LoudGreeter(IGreeter inner) : IGreeter { ) ); - Assert.Equal("HELLO", Greet(generated)); + Verify(Greet(generated) == "HELLO"); } - [Fact] + [VerifyTest] public void NoDecorator_LeavesTheServiceAlone() { var generated = GeneratedAssembly.Create(Module("")); - Assert.Equal("hello", Greet(generated)); + Verify(Greet(generated) == "hello"); } /// /// Two decorators of one service with the same order would nest in an order nobody declared. /// - [Fact] + [VerifyTest] public void DecoratorsSharingAnOrder_ReportDM0007() { var result = GeneratorTestHarness.Run( @@ -292,13 +292,13 @@ public class SecondGreeter(IGreeter inner) : IGreeter { ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0007"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0007"); - Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); - Assert.Contains("IGreeter", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Error); + Verify(diagnostic.GetMessage().Contains("IGreeter")); } - [Fact] + [VerifyTest] public void DecoratorsWithDistinctOrders_ReportNothing() { var result = GeneratorTestHarness.Run( @@ -318,7 +318,7 @@ public class SecondGreeter(IGreeter inner) : IGreeter { ); result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0007"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0007")); } /// @@ -328,9 +328,9 @@ public class SecondGreeter(IGreeter inner) : IGreeter { /// The attribute compiled and read as intentional while doing nothing at all — decoration never /// looked at conditions, so a Development-only decorator wrapped the service in production too. /// - [Theory] - [InlineData("Development", "HELLO")] - [InlineData("Production", "hello")] + [VerifyTest] + [Row("Development", "HELLO")] + [Row("Production", "hello")] public void Decorator_AppliesOnlyWhenItsEnvironmentConditionHolds( string environmentName, string expected @@ -349,12 +349,12 @@ public class LoudGreeter(IGreeter inner) : IGreeter { environment: new ModuleEnvironment(environmentName) ); - Assert.Equal(expected, Greet(generated)); + Verify(Greet(generated) == expected); } - [Theory] - [InlineData("on", "HELLO")] - [InlineData("off", "hello")] + [VerifyTest] + [Row("on", "HELLO")] + [Row("off", "hello")] public void Decorator_HonoursValueConditions(string flag, string expected) { var generated = GeneratedAssembly.Create( @@ -370,13 +370,13 @@ public class LoudGreeter(IGreeter inner) : IGreeter { environment: new ModuleEnvironment(false, "Development") { { "LOUD", flag } } ); - Assert.Equal(expected, Greet(generated)); + Verify(Greet(generated) == expected); } /// /// A condition changes whether a decorator applies, never where it sits in the nesting. /// - [Fact] + [VerifyTest] public void Decorator_ConditionDoesNotDisturbOrdering() { var generated = GeneratedAssembly.Create( @@ -397,14 +397,14 @@ public class Outer(IGreeter inner) : IGreeter { environment: new ModuleEnvironment("Development") ); - Assert.Equal("outer(inner(hello))", Greet(generated)); + Verify(Greet(generated) == "outer(inner(hello))"); } /// /// The unconditional decorator still applies when the conditional one drops out, rather than /// the whole chain going with it. /// - [Fact] + [VerifyTest] public void Decorator_UnconditionalOneSurvivesWhenAConditionalOneDoesNot() { var generated = GeneratedAssembly.Create( @@ -425,7 +425,7 @@ public class Outer(IGreeter inner) : IGreeter { environment: new ModuleEnvironment("Production") ); - Assert.Equal("outer(hello)", Greet(generated)); + Verify(Greet(generated) == "outer(hello)"); } private static string Greet(GeneratedAssembly generated) => @@ -474,7 +474,7 @@ public partial class TestModule; /// dependency contributes, because a type check would pass either way. /// /// - [Fact] + [VerifyTest] public void Decorator_ResolvesAKeyedDependencyFromTheKeyItDeclares() { var assembly = GeneratedAssembly.Create( @@ -514,13 +514,13 @@ public partial class TestModule; var greeter = assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")); // "hello?" is what ignoring the key produces: the right type, the wrong instance, no error. - Assert.Equal("hello.", ((dynamic)greeter).Greet()); + Verify((string)((dynamic)greeter).Greet() == "hello."); } /// /// A nullable dependency the container does not have resolves to null rather than throwing. /// - [Fact] + [VerifyTest] public void Decorator_ResolvesAnOptionalDependencyToNull() { var assembly = GeneratedAssembly.Create( @@ -548,7 +548,7 @@ public partial class TestModule; var greeter = assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")); - Assert.Equal("hello (unaudited)", ((dynamic)greeter).Greet()); + Verify((string)((dynamic)greeter).Greet() == "hello (unaudited)"); } /// @@ -564,7 +564,7 @@ public partial class TestModule; /// generated new proves the constructor was actually read, and only the key proves each /// parameter was resolved on the terms it declares. /// - [Fact] + [VerifyTest] public void ModuleLevelDecorate_ConstructsTheDecoratorFromItsResolvedConstructor() { var assembly = GeneratedAssembly.Create( @@ -602,7 +602,7 @@ public partial class TestModule; var greeter = assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")); - Assert.Equal("hello.", ((dynamic)greeter).Greet()); + Verify((string)((dynamic)greeter).Greet() == "hello."); } /// @@ -613,7 +613,7 @@ public partial class TestModule; /// emit. The alternative was a reflective call that resolved under a JIT and threw in a /// published application. /// - [Fact] + [VerifyTest] public void ModuleLevelDecorate_WithNoPublicConstructor_IsNotDecorated() { var result = GeneratorTestHarness.Run( @@ -641,11 +641,12 @@ public partial class TestModule; // Generated code constructs the decorator, so a private constructor means there is nothing // to emit. The build stays green and the service resolves undecorated. - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); - Assert.DoesNotContain( - result.GeneratedSources, - source => source.Value.Contains("new global::TestNamespace.HiddenGreeter") + Verify( + !result.GeneratedSources.Any(source => + source.Value.Contains("new global::TestNamespace.HiddenGreeter") + ) ); } @@ -687,7 +688,7 @@ public class CountHandler : IHandler { /// The parameter attributes have to survive that rebuild, and losing them is silent: the /// decorator resolves the unkeyed registration, which is the right type and the wrong instance. /// - [Fact] + [VerifyTest] public void GenericDecorator_KeyedDependencySurvivesTypeSubstitution() { var assembly = GeneratedAssembly.Create( @@ -732,13 +733,13 @@ public partial class TestModule; var lines = (System.Collections.Generic.List) assembly.Type("Log").GetField("Lines")!.GetValue(null)!; - Assert.Equal(["."], lines); + Verify(lines.SequenceEqual(["."])); } /// /// A generic decorator's optional dependency resolves to null rather than throwing. /// - [Fact] + [VerifyTest] public void GenericDecorator_OptionalDependencyResolvesToNull() { var assembly = GeneratedAssembly.Create( @@ -768,7 +769,7 @@ public partial class TestModule; handler.MakeGenericType(assembly.Type("Create"), assembly.Type("Id")) ); - Assert.False((bool)resolved.GetType().GetProperty("Audited")!.GetValue(resolved)!); + Verify(!(bool)resolved.GetType().GetProperty("Audited")!.GetValue(resolved)!); } /// @@ -779,7 +780,7 @@ public partial class TestModule; /// only the top-level parameter types and not their arguments produces code that does not /// compile, which is the failure this pins. /// - [Fact] + [VerifyTest] public void GenericDecorator_ClosesADependencyOverItsOwnTypeParameters() { var assembly = GeneratedAssembly.Create( @@ -813,7 +814,9 @@ public partial class TestModule; handler.MakeGenericType(assembly.Type("Create"), assembly.Type("Id")) ); - Assert.Equal("create", resolved.GetType().GetProperty("ValidatorName")!.GetValue(resolved)); + Verify( + Equals(resolved.GetType().GetProperty("ValidatorName")!.GetValue(resolved), "create") + ); } /// @@ -824,7 +827,7 @@ public partial class TestModule; /// open-generic runtime call had to go. Under a JIT it passes either way, so this asserts the /// shape rather than the outcome: the emitted call must name the closed decorator. /// - [Fact] + [VerifyTest] public void GenericDecorator_ClosesOverAValueTypeArgument() { var result = GeneratorTestHarness.Run( @@ -842,28 +845,29 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); - var decorators = Assert - .Single(result.GeneratedSources, source => source.Key.Contains("Decorators")) - .Value; + var decorators = Single( + result.GeneratedSources, + source => source.Key.Contains("Decorators") + ).Value; // One closed call per registration, each naming the decorator closed over the same // arguments — including the value-type one, which is the instantiation Native AOT cannot // produce at run time and the reason the open-generic call had to go. - Assert.True( + Verify( System.Text.RegularExpressions.Regex.Matches(decorators, "Decorate<").Count == 2, "expected one closed Decorate call per registration, got:\n" + decorators ); // Nothing is closed at run time any more. - Assert.DoesNotContain("IHandler<,>", decorators); + Verify(!decorators.Contains("IHandler<,>")); } /// /// Two generic decorators over one service nest in their declared order. /// - [Fact] + [VerifyTest] public void GenericDecorators_StackInOrder() { var assembly = GeneratedAssembly.Create( @@ -902,7 +906,7 @@ public partial class TestModule; assembly.Type("Log").GetField("Lines")!.GetValue(null)!; // Higher order wraps further out, so it runs first. - Assert.Equal(["outer", "inner"], lines); + Verify(lines.SequenceEqual(["outer", "inner"])); } /// @@ -915,7 +919,7 @@ public partial class TestModule; /// implementation behind it is wrapped twice — two log lines per call, no exception, nothing in /// the build. /// - [Fact] + [VerifyTest] public void GenericDecorator_RegisteredByBothPaths_IsAppliedOnce() { var assembly = GeneratedAssembly.Create( @@ -973,7 +977,7 @@ public void Conventions(IConventionDefinitions conventions) { assembly.Type("Log").GetField("Lines")!.GetValue(null)!; // Two registrations, one decoration each — not two each. - Assert.Equal(2, lines.Count); + Verify(lines.Count == 2); } // ------------------------------------------------------------------------------------------ @@ -990,7 +994,7 @@ public void Conventions(IConventionDefinitions conventions) { /// well. Picking the greediest instead compiles and resolves — it just builds the decorator a /// different way than the author asked for, which nothing would report. /// - [Fact] + [VerifyTest] public void Decorator_HonoursTheConstructorItMarked() { var assembly = GeneratedAssembly.Create( @@ -1026,9 +1030,9 @@ public partial class TestModule; """ ); - Assert.Equal( - "hello:marked", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "hello:marked" ); } @@ -1039,7 +1043,7 @@ public partial class TestModule; /// An IServiceProvider parameter is the provider, not something to resolve from it. /// Resolving it would work by accident on Microsoft's container and is wrong in principle. /// - [Fact] + [VerifyTest] public void Decorator_TakingTheProviderGetsTheProvider() { var assembly = GeneratedAssembly.Create( @@ -1069,9 +1073,9 @@ public partial class TestModule; """ ); - Assert.Equal( - "hello!", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "hello!" ); } @@ -1083,7 +1087,7 @@ public partial class TestModule; /// unresolvable under the name it was registered with — while an unkeyed resolution starts /// working, which looks like the service moved rather than broke. /// - [Fact] + [VerifyTest] public void Decorator_KeyedRegistrationKeepsItsKey() { var assembly = GeneratedAssembly.Create( @@ -1111,11 +1115,8 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var greeter = assembly.Type("IGreeter"); - Assert.Equal( - "GOOD DAY", - Invoke(provider.GetRequiredKeyedService(greeter, "formal"), "Greet") - ); - Assert.Null(provider.GetService(greeter)); + Verify(Invoke(provider.GetRequiredKeyedService(greeter, "formal"), "Greet") == "GOOD DAY"); + Verify(provider.GetService(greeter) is null); } /// @@ -1126,7 +1127,7 @@ public partial class TestModule; /// argument, not over its outer shape. Substituting only the top level emits a type argument /// that does not compile, which is the failure mode this pins. /// - [Fact] + [VerifyTest] public void GenericDecorator_ClosesOverANestedTypeArgument() { var assembly = GeneratedAssembly.Create( @@ -1167,7 +1168,7 @@ public partial class TestModule; var resolved = assembly.BuildProvider().GetRequiredService(handler); - Assert.Equal("LoggingHandler`2", resolved.GetType().Name); + Verify(resolved.GetType().Name == "LoggingHandler`2"); } /// @@ -1177,7 +1178,7 @@ public partial class TestModule; /// A generic decorator is not "every possible construction" — it is one decoration per /// registration. Emitting for a construction nothing registers would be dead code at best. /// - [Fact] + [VerifyTest] public void GenericDecorator_DecoratesOnlyTheRegisteredClosings() { var result = GeneratorTestHarness.Run( @@ -1206,20 +1207,21 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); - var decorators = Assert - .Single(result.GeneratedSources, source => source.Key.Contains("Decorators")) - .Value; + var decorators = Single( + result.GeneratedSources, + source => source.Key.Contains("Decorators") + ).Value; - Assert.Contains("Registered", decorators); - Assert.DoesNotContain("NeverRegistered", decorators); + Verify(decorators.Contains("Registered")); + Verify(!decorators.Contains("NeverRegistered")); } /// /// A generic decorator keeps the lifetime each registration declared. /// - [Fact] + [VerifyTest] public void GenericDecorator_PreservesEachRegistrationsLifetime() { var assembly = GeneratedAssembly.Create( @@ -1251,18 +1253,18 @@ public partial class TestModule; var handler = assembly.Type("IHandler`1"); - var singleton = Assert.Single( + var singleton = Single( assembly.Services, d => d.ServiceType == handler.MakeGenericType(assembly.Type("A")) ); - var transient = Assert.Single( + var transient = Single( assembly.Services, d => d.ServiceType == handler.MakeGenericType(assembly.Type("B")) ); - Assert.Equal(ServiceLifetime.Singleton, singleton.Lifetime); - Assert.Equal(ServiceLifetime.Transient, transient.Lifetime); + Verify(singleton.Lifetime == ServiceLifetime.Singleton); + Verify(transient.Lifetime == ServiceLifetime.Transient); } /// @@ -1273,7 +1275,7 @@ public partial class TestModule; /// displaced registration is created from a rebuilt model rather than the one the transform /// produced. /// - [Fact] + [VerifyTest] public void GenericDecorator_LeavesTheInnerOwnedByTheContainer() { var assembly = GeneratedAssembly.Create( @@ -1310,16 +1312,16 @@ public partial class TestModule; using (var scope = provider.CreateScope()) { - Assert.Equal("a", Invoke(scope.ServiceProvider.GetRequiredService(handler), "Handle")); + Verify(Invoke(scope.ServiceProvider.GetRequiredService(handler), "Handle") == "a"); } - Assert.Equal(1, (int)assembly.Type("Log").GetField("Disposals")!.GetValue(null)!); + Verify((int)assembly.Type("Log").GetField("Disposals")!.GetValue(null)! == 1); } /// /// A decorator scoped to a realm decorates only that module's registrations. /// - [Fact] + [VerifyTest] public void Decorator_ScopedToARealm_DecoratesOnlyThatModule() { var assembly = GeneratedAssembly.Create( @@ -1347,9 +1349,9 @@ public partial class PlainModule; moduleName: "DecoratedModule" ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } @@ -1361,9 +1363,9 @@ public partial class PlainModule; /// never run and the service resolves undecorated — rather than being wrapped by something that /// re-tests the environment on every call. /// - [Theory] - [InlineData("Development", "HELLO")] - [InlineData("Production", "hello")] + [VerifyTest] + [Row("Development", "HELLO")] + [Row("Production", "hello")] public void Decorator_WithAnEnvironmentCondition_AppliesOnlyWhenItHolds( string environment, string expected @@ -1392,16 +1394,16 @@ public partial class TestModule; environment: new ModuleEnvironment(environment) ); - Assert.Equal( - expected, + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == expected ); } /// /// Every implementation behind one service is decorated, not just the last registered. /// - [Fact] + [VerifyTest] public void Decorator_WrapsEveryImplementationOfTheService() { var assembly = GeneratedAssembly.Create( @@ -1436,7 +1438,7 @@ public partial class TestModule; .Select(service => Invoke(service, "Greet")) .ToArray(); - Assert.Equal(["HELLO", "BONJOUR"], all); + Verify(all.SequenceEqual(["HELLO", "BONJOUR"])); } /// @@ -1447,7 +1449,7 @@ public partial class TestModule; /// replacing the other. Worth pinning: they are emitted by different writers and nothing else /// asserts that the second sees what the first produced. /// - [Fact] + [VerifyTest] public void Decorator_AndInterceptor_BothWrapTheService() { var assembly = GeneratedAssembly.Create( @@ -1491,9 +1493,9 @@ public partial class TestModule; var lines = (System.Collections.Generic.List) assembly.Type("Log").GetField("Lines")!.GetValue(null)!; - Assert.Equal("HELLO", greeted); - Assert.Contains("decorated", lines); - Assert.Contains("intercepted", lines); + Verify(greeted == "HELLO"); + Verify(lines.Contains("decorated")); + Verify(lines.Contains("intercepted")); } /// @@ -1504,7 +1506,7 @@ public partial class TestModule; /// name the concrete class rather than an interface. Nothing else covers a decoration whose /// service type is the implementation. /// - [Fact] + [VerifyTest] public void Decorator_OverAConventionRegisteredAsSelf() { var assembly = GeneratedAssembly.Create( @@ -1532,9 +1534,9 @@ public void Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal( - "WORK", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("Worker")), "Work") + == "WORK" ); } @@ -1554,7 +1556,7 @@ public void Conventions(IConventionDefinitions conventions) { /// from the compilation rather than read from a declaration. /// /// - [Fact] + [VerifyTest] public void ModuleLevelDecorate_CanNameAGenericDecorator() { var assembly = GeneratedAssembly.Create( @@ -1588,19 +1590,17 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var handler = assembly.Type("IHandler`1"); - Assert.Equal( - "A", + Verify( Invoke( provider.GetRequiredService(handler.MakeGenericType(assembly.Type("A"))), "Handle" - ) + ) == "A" ); - Assert.Equal( - "B", + Verify( Invoke( provider.GetRequiredService(handler.MakeGenericType(assembly.Type("B"))), "Handle" - ) + ) == "B" ); } @@ -1609,7 +1609,7 @@ public partial class TestModule; // ------------------------------------------------------------------------------------------ /// The wrapped service does not have to be the first constructor parameter. - [Fact] + [VerifyTest] public void Decorator_InnerParameterNeedNotComeFirst() { var assembly = GeneratedAssembly.Create( @@ -1636,14 +1636,14 @@ public partial class TestModule; """ ); - Assert.Equal( - "hello!", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "hello!" ); } /// A record decorator is constructed through its primary constructor. - [Fact] + [VerifyTest] public void Decorator_DeclaredAsARecord() { var assembly = GeneratedAssembly.Create( @@ -1667,14 +1667,14 @@ public partial class TestModule; """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } /// A decorator nested inside another type is named correctly in the emitted new. - [Fact] + [VerifyTest] public void Decorator_NestedInsideAnotherType() { var assembly = GeneratedAssembly.Create( @@ -1700,9 +1700,9 @@ public partial class TestModule; """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } @@ -1712,7 +1712,7 @@ public partial class TestModule; /// does not. Matching them without normalising means no parameter looks like the service, and /// the decoration is dropped with nothing said. /// - [Fact] + [VerifyTest] public void Decorator_WithANullableInnerParameter() { var assembly = GeneratedAssembly.Create( @@ -1736,9 +1736,9 @@ public partial class TestModule; """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } @@ -1751,7 +1751,7 @@ public partial class TestModule; /// that cannot be closed by position. Guessing would emit a new with the arguments the /// wrong way round, which compiles whenever the two types happen to be compatible. /// - [Fact] + [VerifyTest] public void GenericDecorator_WithReorderedTypeParameters_IsNotEmitted() { var result = GeneratorTestHarness.Run( @@ -1782,18 +1782,19 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); - Assert.DoesNotContain( - result.GeneratedSources, - source => source.Value.Contains("new global::TestNamespace.Swapped") + Verify( + !result.GeneratedSources.Any(source => + source.Value.Contains("new global::TestNamespace.Swapped") + ) ); } /// /// A generic decorator with fewer type parameters than the service has arguments is not emitted. /// - [Fact] + [VerifyTest] public void GenericDecorator_WithMismatchedArity_IsNotEmitted() { var result = GeneratorTestHarness.Run( @@ -1821,11 +1822,11 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); } /// A cross-wired registration is a factory descriptor, and decorates like one. - [Fact] + [VerifyTest] public void Decorator_OverACrossWiredRegistration() { var assembly = GeneratedAssembly.Create( @@ -1851,23 +1852,17 @@ public partial class TestModule; var provider = assembly.BuildProvider(); - Assert.Equal( - "HELLO", - Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") - ); + Verify(Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") == "HELLO"); // The implementation stays resolvable as itself, undecorated — that is what cross-wiring is. - Assert.Equal( - "hello", - Invoke(provider.GetRequiredService(assembly.Type("Greeter")), "Greet") - ); + Verify(Invoke(provider.GetRequiredService(assembly.Type("Greeter")), "Greet") == "hello"); } /// /// A decorator whose own dependency is generic in the service's arguments and comes from a /// convention. /// - [Fact] + [VerifyTest] public void GenericDecorator_OverConventionRegistrations_WithAGenericDependency() { var assembly = GeneratedAssembly.Create( @@ -1904,10 +1899,7 @@ public void Conventions(IConventionDefinitions conventions) { var handler = assembly.Type("IHandler`1").MakeGenericType(assembly.Type("A")); - Assert.Equal( - "[A]a", - Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") - ); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") == "[A]a"); } /// @@ -1919,7 +1911,7 @@ public void Conventions(IConventionDefinitions conventions) { /// same one — so without the guard the implementation is wrapped twice, which shows up as a /// decorator's side effects happening twice per call and nothing else. /// - [Fact] + [VerifyTest] public void Decorator_WithTwoModulesInTheCompilation_IsAppliedOnce() { var assembly = GeneratedAssembly.Create( @@ -1950,7 +1942,7 @@ public partial class OtherModule; Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet"); - Assert.Equal(1, (int)assembly.Type("Log").GetField("Applied")!.GetValue(null)!); + Verify((int)assembly.Type("Log").GetField("Applied")!.GetValue(null)! == 1); } /// Two decorators of one service sharing an order are still refused. @@ -1958,7 +1950,7 @@ public partial class OtherModule; /// The check moved when decoration collapsed into one stage. It is the only thing standing /// between two decorators and a nesting order nobody declared. /// - [Fact] + [VerifyTest] public void Decorators_SharingAnOrder_AreReported() { var result = GeneratorTestHarness.Run( @@ -1983,10 +1975,10 @@ public partial class TestModule; """ ); - var reported = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0007"); + var reported = Single(result.GeneratorDiagnostics, d => d.Id == "DM0007"); - Assert.Contains("First", reported.GetMessage()); - Assert.Contains("Second", reported.GetMessage()); + Verify(reported.GetMessage().Contains("First")); + Verify(reported.GetMessage().Contains("Second")); } /// @@ -1996,7 +1988,7 @@ public partial class TestModule; /// They arrive at the writer from different routes — one expanded per registration, one passed /// through — so this pins that the ordering applies across both rather than within each. /// - [Fact] + [VerifyTest] public void GenericAndNonGenericDecorators_NestByOrder() { var assembly = GeneratedAssembly.Create( @@ -2036,11 +2028,11 @@ public partial class TestModule; var lines = (System.Collections.Generic.List) assembly.Type("Log").GetField("Lines")!.GetValue(null)!; - Assert.Equal(["specific", "generic"], lines); + Verify(lines.SequenceEqual(["specific", "generic"])); } /// An unscoped decorator does not reach a realm-only module. - [Fact] + [VerifyTest] public void Decorator_Unscoped_DoesNotReachARealmOnlyModule() { var assembly = GeneratedAssembly.Create( @@ -2065,14 +2057,14 @@ public partial class RealmModule; moduleName: "RealmModule" ); - Assert.Equal( - "hello", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "hello" ); } /// A convention registering matches under a key is decorated under that key. - [Fact] + [VerifyTest] public void Decorator_OverAKeyedConventionRegistration() { var assembly = GeneratedAssembly.Create( @@ -2104,8 +2096,8 @@ public void Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); var greeter = assembly.Type("IGreeter"); - Assert.Equal("HELLO", Invoke(provider.GetRequiredKeyedService(greeter, "loud"), "Greet")); - Assert.Null(provider.GetService(greeter)); + Verify(Invoke(provider.GetRequiredKeyedService(greeter, "loud"), "Greet") == "HELLO"); + Verify(provider.GetService(greeter) is null); } /// @@ -2116,7 +2108,7 @@ public void Conventions(IConventionDefinitions conventions) { /// implementation, so the decorated descriptor is a factory and the shared instance the contract /// promises has to survive the rewrite. /// - [Fact] + [VerifyTest] public void Decorator_OverAConventionRegisteredAsSelfWithInterfaces() { var assembly = GeneratedAssembly.Create( @@ -2146,20 +2138,14 @@ public void Conventions(IConventionDefinitions conventions) { var provider = assembly.BuildProvider(); - Assert.Equal( - "HELLO", - Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") - ); + Verify(Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") == "HELLO"); // The implementation itself stays undecorated, which is what cross-wiring means. - Assert.Equal( - "hello", - Invoke(provider.GetRequiredService(assembly.Type("Greeter")), "Greet") - ); + Verify(Invoke(provider.GetRequiredService(assembly.Type("Greeter")), "Greet") == "hello"); } /// A decorator with no matching registration emits nothing and breaks nothing. - [Fact] + [VerifyTest] public void Decorator_WithNothingToDecorate_EmitsNothing() { var result = GeneratorTestHarness.Run( @@ -2180,7 +2166,7 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); } /// @@ -2192,7 +2178,7 @@ public partial class TestModule; /// new Logging<int>(…), which violates the constraint — CS0453, in generated code, /// for two declarations that are each perfectly legal. /// - [Fact] + [VerifyTest] public void GenericDecorator_ConstrainedToReferenceTypes_SkipsValueTypeClosings() { var result = GeneratorTestHarness.Run( @@ -2221,13 +2207,13 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); } /// /// A constraint the closing does satisfy still emits. /// - [Fact] + [VerifyTest] public void GenericDecorator_ConstrainedToAnInterface_EmitsForSatisfyingClosings() { var assembly = GeneratedAssembly.Create( @@ -2257,10 +2243,7 @@ public partial class TestModule; var handler = assembly.Type("IHandler`1").MakeGenericType(assembly.Type("Thing")); - Assert.Equal( - "THING", - Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") - ); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") == "THING"); } /// @@ -2271,7 +2254,7 @@ public partial class TestModule; /// is arbitrary when there are two. Service = is the way to say which, and this pins that /// it wins over inference rather than being one more candidate. /// - [Fact] + [VerifyTest] public void Decorator_WithAnExplicitService_DecoratesThatOne() { var assembly = GeneratedAssembly.Create( @@ -2302,17 +2285,14 @@ public partial class TestModule; var provider = assembly.BuildProvider(); - Assert.Equal("BYE", Invoke(provider.GetRequiredService(assembly.Type("IFarewell")), "Bye")); + Verify(Invoke(provider.GetRequiredService(assembly.Type("IFarewell")), "Bye") == "BYE"); // The other interface it implements is not decorated. - Assert.Equal( - "hello", - Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") - ); + Verify(Invoke(provider.GetRequiredService(assembly.Type("IGreeter")), "Greet") == "hello"); } /// A registration declared with Try is still decorated. - [Fact] + [VerifyTest] public void Decorator_OverATryRegistration() { var assembly = GeneratedAssembly.Create( @@ -2336,9 +2316,9 @@ public partial class TestModule; """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } @@ -2347,7 +2327,7 @@ public partial class TestModule; /// Inference reads the base list, which here names a class rather than the interface. If only /// directly-written interfaces count, this stops being recognised and is silently not applied. /// - [Fact] + [VerifyTest] public void Decorator_ImplementingTheServiceThroughABaseClass() { var result = GeneratorTestHarness.Run( @@ -2373,13 +2353,13 @@ public partial class TestModule; """ ); - Assert.Empty(result.Errors); + Verify(!result.Errors.Any()); } /// An environment condition guards every closed call a generic decorator produces. - [Theory] - [InlineData("Development", "A")] - [InlineData("Production", "a")] + [VerifyTest] + [Row("Development", "A")] + [Row("Production", "a")] public void GenericDecorator_WithAnEnvironmentCondition_GuardsEachClosing( string environment, string expected @@ -2416,10 +2396,7 @@ public partial class TestModule; var handler = assembly.Type("IHandler`1").MakeGenericType(assembly.Type("A")); - Assert.Equal( - expected, - Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") - ); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") == expected); } /// Two closings of one generic service each get their own decoration. @@ -2427,7 +2404,7 @@ public partial class TestModule; /// The decorator must close over each construction separately rather than over whichever was /// seen first. /// - [Fact] + [VerifyTest] public void GenericDecorator_OverTwoClosingsOfOneService() { var assembly = GeneratedAssembly.Create( @@ -2460,24 +2437,22 @@ public partial class TestModule; var provider = assembly.BuildProvider(); var handler = assembly.Type("IHandler`1"); - Assert.Equal( - "MULTI", + Verify( Invoke( provider.GetRequiredService(handler.MakeGenericType(assembly.Type("A"))), "Handle" - ) + ) == "MULTI" ); - Assert.Equal( - "MULTI", + Verify( Invoke( provider.GetRequiredService(handler.MakeGenericType(assembly.Type("B"))), "Handle" - ) + ) == "MULTI" ); } /// A deeply nested type argument is substituted at every level. - [Fact] + [VerifyTest] public void GenericDecorator_ClosesOverADeeplyNestedTypeArgument() { var assembly = GeneratedAssembly.Create( @@ -2514,14 +2489,11 @@ public partial class TestModule; ) ); - Assert.Equal( - "DEEP", - Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") - ); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") == "DEEP"); } /// Three type parameters are substituted in order. - [Fact] + [VerifyTest] public void GenericDecorator_WithThreeTypeParameters() { var assembly = GeneratedAssembly.Create( @@ -2553,11 +2525,11 @@ public partial class TestModule; .Type("IPipe`3") .MakeGenericType(assembly.Type("In"), assembly.Type("Via"), assembly.Type("Out")); - Assert.Equal("PIPE", Invoke(assembly.BuildProvider().GetRequiredService(pipe), "Run")); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(pipe), "Run") == "PIPE"); } /// A keyed registration with a keyed dependency on the decorator. - [Fact] + [VerifyTest] public void Decorator_KeyedRegistrationAndKeyedDependency() { var assembly = GeneratedAssembly.Create( @@ -2592,19 +2564,18 @@ public partial class TestModule; """ ); - Assert.Equal( - "good day.", + Verify( Invoke( assembly .BuildProvider() .GetRequiredKeyedService(assembly.Type("IGreeter"), "formal"), "Greet" - ) + ) == "good day." ); } /// A decorator can depend on the module environment. - [Fact] + [VerifyTest] public void Decorator_DependingOnTheModuleEnvironment() { var assembly = GeneratedAssembly.Create( @@ -2631,14 +2602,14 @@ public partial class TestModule; environment: new ModuleEnvironment("Staging") ); - Assert.Equal( - "hello:env", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "hello:env" ); } /// A TryEnumerable registration is decorated. - [Fact] + [VerifyTest] public void Decorator_OverATryEnumerableRegistration() { var assembly = GeneratedAssembly.Create( @@ -2662,14 +2633,14 @@ public partial class TestModule; """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } /// A convention reaching the interface through a base class is decorated. - [Fact] + [VerifyTest] public void Decorator_OverAConventionUsingIncludeBaseClasses() { var assembly = GeneratedAssembly.Create( @@ -2699,14 +2670,14 @@ public void Conventions(IConventionDefinitions conventions) { """ ); - Assert.Equal( - "HELLO", + Verify( Invoke(assembly.BuildProvider().GetRequiredService(assembly.Type("IGreeter")), "Greet") + == "HELLO" ); } /// Interception over a closed construction of a generic service. - [Fact] + [VerifyTest] public void Interceptor_OverAClosedGenericService() { var assembly = GeneratedAssembly.Create( @@ -2741,7 +2712,7 @@ public partial class TestModule; var handler = assembly.Type("IHandler`1").MakeGenericType(assembly.Type("A")); - Assert.Equal("a", Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle")); - Assert.Equal(1, (int)assembly.Type("Log").GetField("Calls")!.GetValue(null)!); + Verify(Invoke(assembly.BuildProvider().GetRequiredService(handler), "Handle") == "a"); + Verify((int)assembly.Type("Log").GetField("Calls")!.GetValue(null)! == 1); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs index da71a01..3db99d3 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/DecoratorImplementationTests.cs @@ -1,9 +1,8 @@ using System.Collections.Generic; using System.Linq; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// [Decorator(Implementation = typeof(X))] — decorating one implementation rather than every @@ -19,50 +18,50 @@ namespace DependencyModules.Tests.GeneratorTests; /// implementation type and skips descriptors built from anything else, which is the overload /// interception uses. Only the attribute could not say so. /// -public class DecoratorImplementationTests +public partial class DecoratorImplementationTests { /// /// The default, unchanged: no Implementation named, so every registration of the service is /// wrapped. /// - [Fact] + [VerifyTest] public void WithNoImplementationNamed_EveryRegistrationIsWrapped() { var resolved = Resolve("[Decorator]"); - Assert.Equal(["Logged", "Logged"], resolved.Select(Outer)); + Verify(resolved.Select(Outer).SequenceEqual(["Logged", "Logged"])); } - [Fact] + [VerifyTest] public void NamingAnImplementation_WrapsOnlyThatOne() { var resolved = Resolve("[Decorator(Implementation = typeof(Loud))]"); - Assert.Equal(["Logged", "Quiet"], resolved.Select(Outer)); + Verify(resolved.Select(Outer).SequenceEqual(["Logged", "Quiet"])); } /// /// And the one it wrapped is still the one it wrapped — the decorator holds the named /// implementation, not whichever registration happened to be first. /// - [Fact] + [VerifyTest] public void TheWrappedInstance_IsTheNamedImplementation() { var resolved = Resolve("[Decorator(Implementation = typeof(Loud))]"); - var logged = Assert.Single(resolved, greeter => Outer(greeter) == "Logged"); + var logged = Single(resolved, greeter => Outer(greeter) == "Logged"); - Assert.Equal("loud", Greet(logged)); + Verify(Greet(logged) == "loud"); } - [Fact] + [VerifyTest] public void TheUnnamedImplementation_IsUntouched() { var resolved = Resolve("[Decorator(Implementation = typeof(Loud))]"); - var quiet = Assert.Single(resolved, greeter => Outer(greeter) == "Quiet"); + var quiet = Single(resolved, greeter => Outer(greeter) == "Quiet"); - Assert.Equal("quiet", Greet(quiet)); + Verify(Greet(quiet) == "quiet"); } /// @@ -70,19 +69,19 @@ public void TheUnnamedImplementation_IsUntouched() /// wrapping everything — the failure mode that would make a typo silently behave like the /// default. /// - [Fact] + [VerifyTest] public void NamingAnImplementationThatIsNotRegistered_WrapsNothing() { var resolved = Resolve("[Decorator(Implementation = typeof(Unregistered))]"); - Assert.Equal(["Loud", "Quiet"], resolved.Select(Outer)); + Verify(resolved.Select(Outer).SequenceEqual(["Loud", "Quiet"])); } /// /// A factory from DependencyModules_GenerateFactories is typed to return its class, so /// the decorator tells the registrations apart as it does without the property. /// - [Fact] + [VerifyTest] public void NamingAnImplementationUnderGenerateFactories_WrapsOnlyThatOne() { var resolved = Resolve( @@ -90,15 +89,15 @@ public void NamingAnImplementationUnderGenerateFactories_WrapsOnlyThatOne() generateFactories: true ); - Assert.Equal(["Logged", "Quiet"], resolved.Select(Outer)); + Verify(resolved.Select(Outer).SequenceEqual(["Logged", "Quiet"])); } - [Fact] + [VerifyTest] public void NamingNoImplementationUnderGenerateFactories_WrapsEveryRegistration() { var resolved = Resolve("[Decorator]", generateFactories: true); - Assert.Equal(["Logged", "Logged"], resolved.Select(Outer)); + Verify(resolved.Select(Outer).SequenceEqual(["Logged", "Logged"])); } private static string Outer(object greeter) => greeter.GetType().Name; diff --git a/tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs index 3703589..0e2a9a8 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticSuppressionTests.cs @@ -2,9 +2,8 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Whether a DM diagnostic can be silenced where it is written. @@ -28,17 +27,17 @@ namespace DependencyModules.Tests.GeneratorTests; /// because a generator that failed has nothing to point at. Adding a code without adding it here /// means shipping one more diagnostic nobody can turn off where they wrote it. /// -public class DiagnosticSuppressionTests +public partial class DiagnosticSuppressionTests { - [Theory] - [MemberData(nameof(Triggers))] + [VerifyTest] + [RowSource(nameof(Triggers))] public void ADiagnostic_IsReportedAgainstASyntaxTree(string code, string source) { var result = GeneratorTestHarness.Run(source); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == code); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == code); - Assert.True( + Verify( diagnostic.Location.SourceTree != null, $"{code} was reported at {diagnostic.Location.Kind} with no syntax tree, so neither " + ".editorconfig nor #pragma can silence it. Location: " @@ -46,15 +45,15 @@ public void ADiagnostic_IsReportedAgainstASyntaxTree(string code, string source) ); } - [Theory] - [MemberData(nameof(Triggers))] + [VerifyTest] + [RowSource(nameof(Triggers))] public void ADiagnostic_IsReportedInTheFileThatCausedIt(string code, string source) { var result = GeneratorTestHarness.Run(source); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == code); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == code); - Assert.Equal("Test.cs", System.IO.Path.GetFileName(diagnostic.Location.GetLineSpan().Path)); + Verify(System.IO.Path.GetFileName(diagnostic.Location.GetLineSpan().Path) == "Test.cs"); } /// @@ -63,10 +62,9 @@ public void ADiagnostic_IsReportedInTheFileThatCausedIt(string code, string sour /// because they are the two that were never moved and already carry a real location — they are /// covered by AssemblyModuleAttributeDiagnosticsTests. /// - public static IEnumerable Triggers() + public static IEnumerable<(string Code, string Source)> Triggers() { - yield return - [ + yield return ( "DM0002", Module( """ @@ -74,22 +72,20 @@ public interface IThing; [SingletonService] public abstract class Thing : IThing; """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0003", """ - using DependencyModules.Runtime.Attributes; - namespace TestNamespace; - [DependencyModule] - public class NotPartialModule; - """, - ]; + using DependencyModules.Runtime.Attributes; + namespace TestNamespace; + [DependencyModule] + public class NotPartialModule; + """ + ); - yield return - [ + yield return ( "DM0012", Module( """ @@ -98,11 +94,10 @@ public interface IThing; [IfEnvironment] public class Thing : IThing; """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0014", Module( """ @@ -110,24 +105,22 @@ public interface IThing; [CrossWireService] public class Thing : IThing; """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0017", """ - using DependencyModules.Runtime.Attributes; - namespace TestNamespace; - public static class Outer { - [DependencyModule] - public partial class NestedModule; - } - """, - ]; + using DependencyModules.Runtime.Attributes; + namespace TestNamespace; + public static class Outer { + [DependencyModule] + public partial class NestedModule; + } + """ + ); - yield return - [ + yield return ( "DM0004", Convention( """ @@ -142,11 +135,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0005", Convention( """ @@ -157,11 +149,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0006", Convention( """ @@ -175,11 +166,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0009", Convention( """ @@ -193,31 +183,29 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0021", """ - using DependencyModules.Runtime.Attributes; - using DependencyModules.Testing.Attributes; + using DependencyModules.Runtime.Attributes; + using DependencyModules.Testing.Attributes; - namespace TestNamespace; + namespace TestNamespace; - public interface IThing; + public interface IThing; - public class RealThing : IThing; + public class RealThing : IThing; - public class Fixture { - [TestExport(typeof(IThing), Implementation = typeof(RealThing))] - public void Conflicting([Mock] IThing thing) { } - } - """, - ]; + public class Fixture { + [TestExport(typeof(IThing), Implementation = typeof(RealThing))] + public void Conflicting([Mock] IThing thing) { } + } + """ + ); - yield return - [ + yield return ( "DM0020", Convention( """ @@ -239,11 +227,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0010", Convention( """ @@ -257,11 +244,10 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0011", Module( """ @@ -270,66 +256,63 @@ public interface IThing; [IfEnvironment("Development")] public class Thing : IThing; """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0007", """ - using DependencyModules.Runtime.Attributes; + using DependencyModules.Runtime.Attributes; - namespace TestNamespace; + namespace TestNamespace; - public interface IThing { string Read(); } + public interface IThing { string Read(); } - [SingletonService] - public class Thing : IThing { - public string Read() => ""; - } + [SingletonService] + public class Thing : IThing { + public string Read() => ""; + } - [Decorator(Order = 1)] - public class FirstDecorator(IThing inner) : IThing { - public string Read() => inner.Read(); - } + [Decorator(Order = 1)] + public class FirstDecorator(IThing inner) : IThing { + public string Read() => inner.Read(); + } - [Decorator(Order = 1)] - public class SecondDecorator(IThing inner) : IThing { - public string Read() => inner.Read(); - } + [Decorator(Order = 1)] + public class SecondDecorator(IThing inner) : IThing { + public string Read() => inner.Read(); + } - [DependencyModule] - public partial class TestModule; - """, - ]; + [DependencyModule] + public partial class TestModule; + """ + ); - yield return - [ + yield return ( "DM0013", """ - using DependencyModules.Runtime.Attributes; + using DependencyModules.Runtime.Attributes; - namespace TestNamespace; + namespace TestNamespace; - public interface IStore { string Read(T key); } + public interface IStore { string Read(T key); } - [SingletonService] - public class Store : IStore { - public string Read(T key) => ""; - } + [SingletonService] + public class Store : IStore { + public string Read(T key) => ""; + } - [Decorator] - public class LoggingStore(IStore inner) : IStore { - public string Read(T key) => inner.Read(key); - } + [Decorator] + public class LoggingStore(IStore inner) : IStore { + public string Read(T key) => inner.Read(key); + } - [DependencyModule] - public partial class TestModule; - """, - ]; + [DependencyModule] + public partial class TestModule; + """ + ); - yield return - [ + yield return ( "DM0008", Intercepted( """ @@ -343,11 +326,10 @@ public class Awkward : IAwkward { public bool TryGet(string key, out string value) { value = key; return true; } } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0015", Intercepted( """ @@ -361,21 +343,20 @@ public class AsyncOnly : IAsyncOnly { public Task GetAsync(string key) => Task.FromResult(key); } """ - ), - ]; + ) + ); - yield return - [ + yield return ( "DM0018", """ - using DependencyModules.Runtime.Attributes; - namespace TestNamespace; - [DependencyModule] - public partial class TestModule { - public int SizeLimit { get; set; } - } - """, - ]; + using DependencyModules.Runtime.Attributes; + namespace TestNamespace; + [DependencyModule] + public partial class TestModule { + public int SizeLimit { get; set; } + } + """ + ); } private static string Convention(string body) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs index 354a5d5..3f815b1 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/DiagnosticsTests.cs @@ -1,46 +1,45 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The generator's job is to move failures from run time to build time. Each of these covers a /// mistake that previously produced either a crash when the container was built or, worse, a /// successful build that quietly registered nothing. /// -public class DiagnosticsTests +public partial class DiagnosticsTests { /// /// An abstract implementation used to be registered anyway, and the resulting /// AddSingleton(typeof(IThing), typeof(AbstractThing)) threw when the provider was built, /// a long way from the declaration responsible. /// - [Fact] + [VerifyTest] public void AbstractService_ReportsDM0002() { var result = GeneratorTestHarness.Run( Module("[SingletonService] public abstract class Thing : IThing;") ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0002"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0002"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("Thing", diagnostic.GetMessage()); - Assert.Contains("abstract", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("Thing")); + Verify(diagnostic.GetMessage().Contains("abstract")); } - [Fact] + [VerifyTest] public void AbstractService_IsNotRegistered() { var result = GeneratorTestHarness.Run( Module("[SingletonService] public abstract class Thing : IThing;") ); - Assert.DoesNotContain(result.GeneratedSources.Keys, key => key.Contains("Dependencies")); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("Dependencies"))); } - [Fact] + [VerifyTest] public void StaticService_ReportsDM0002() { var result = GeneratorTestHarness.Run( @@ -57,16 +56,16 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0002"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0002"); - Assert.Contains("static", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("static")); } /// /// A concrete service alongside an unconstructable one must still be registered; reporting the /// bad one should not discard the good ones. /// - [Fact] + [VerifyTest] public void ConcreteServices_AreStillRegisteredAlongsideARejectedOne() { var generated = GeneratedAssembly.Create( @@ -89,15 +88,15 @@ public partial class TestModule; var provider = generated.BuildProvider(); - Assert.NotNull(provider.GetService(generated.Type("IThing"))); - Assert.Null(provider.GetService(generated.Type("IAbstract"))); + Verify(provider.GetService(generated.Type("IThing")) is not null); + Verify(provider.GetService(generated.Type("IAbstract")) is null); } /// /// The compiler reports CS0260 once the generated half arrives, but that describes the symptom. /// DM0003 names the fix, and generation is skipped so it is the only error shown. /// - [Fact] + [VerifyTest] public void NonPartialModule_ReportsDM0003() { var result = GeneratorTestHarness.Run( @@ -115,14 +114,14 @@ public class NotPartialModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0003"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0003"); - Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); - Assert.Contains("NotPartialModule", diagnostic.GetMessage()); - Assert.Contains("partial", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Error); + Verify(diagnostic.GetMessage().Contains("NotPartialModule")); + Verify(diagnostic.GetMessage().Contains("partial")); } - [Fact] + [VerifyTest] public void NonPartialModule_DoesNotGenerateAConflictingDeclaration() { var result = GeneratorTestHarness.Run( @@ -137,14 +136,11 @@ public class NotPartialModule; ); // Emitting the module half would add CS0260 on top of DM0003 and point at the wrong thing. - Assert.DoesNotContain( - result.GeneratedSources.Keys, - key => key.Contains("NotPartialModule.Module") - ); - Assert.DoesNotContain(result.CompilationDiagnostics, d => d.Id == "CS0260"); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("NotPartialModule.Module"))); + Verify(!result.CompilationDiagnostics.Any(d => d.Id == "CS0260")); } - [Fact] + [VerifyTest] public void PartialModule_ReportsNothing() { var result = GeneratorTestHarness.Run( @@ -152,10 +148,10 @@ public void PartialModule_ReportsNothing() ); result.AssertNoErrors(); - Assert.Empty(result.GeneratorDiagnostics); + Verify(!result.GeneratorDiagnostics.Any()); } - [Fact] + [VerifyTest] public void AbstractFactoryHost_IsAllowedBecauseTheFactorySuppliesTheInstance() { // The declaring type is never constructed, so an abstract host is legitimate here. @@ -177,7 +173,7 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0002"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0002")); } /// @@ -185,7 +181,7 @@ public partial class TestModule; /// expansion has no closed construction to close over, so the declaration used to disappear with /// a green build — a decorator in the source that never ran. /// - [Fact] + [VerifyTest] public void GenericDecoratorOverOpenGenericRegistration_ReportsDM0013() { var result = GeneratorTestHarness.Run( @@ -199,18 +195,18 @@ public class LoggingStore(IStore inner) : IStore { ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("IStore", diagnostic.GetMessage()); - Assert.Contains("LoggingStore", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("IStore")); + Verify(diagnostic.GetMessage().Contains("LoggingStore")); } /// /// The same service, decorated from the module instead. Both declaration forms reach the same /// expansion, so both have to report. /// - [Fact] + [VerifyTest] public void ModuleDeclaredDecoratorOverOpenGenericRegistration_ReportsDM0013() { var result = GeneratorTestHarness.Run( @@ -224,7 +220,7 @@ public class LoggingStore(IStore inner) : IStore { ) ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); } /// @@ -232,7 +228,7 @@ public class LoggingStore(IStore inner) : IStore { /// expansion, so nothing caught it and it reached emission still carrying IStore<> — /// which is CS7003 in generated code. /// - [Fact] + [VerifyTest] public void NonGenericDecoratorOverOpenGenericRegistration_ReportsDM0013() { var result = GeneratorTestHarness.Run( @@ -246,14 +242,14 @@ public class StringStoreDecorator(IStore inner) : IStore { ) ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0013"); } /// /// And the generated code compiles, which it did not before: GeneratedAssembly.Create /// asserts the compilation is clean and emits. /// - [Fact] + [VerifyTest] public void NonGenericDecoratorOverOpenGenericRegistration_StillCompiles() { var generated = GeneratedAssembly.Create( @@ -267,14 +263,14 @@ public class StringStoreDecorator(IStore inner) : IStore { ) ); - Assert.Contains(generated.Services, d => d.ServiceType == generated.Type("IStore`1")); + Verify(generated.Services.Any(d => d.ServiceType == generated.Type("IStore`1"))); } /// /// The case that must keep working: closed registrations, which a generic decorator is expanded /// across. This is the shape a MediatR-style pipeline is built from. /// - [Fact] + [VerifyTest] public void GenericDecoratorOverClosedRegistrations_DoesNotReportDM0013() { var result = GeneratorTestHarness.Run( @@ -298,7 +294,7 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0013"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0013")); } /// @@ -306,7 +302,7 @@ public partial class TestModule; /// service someone else registers is what [Decorate] is for, so reporting here would fire /// on the feature's primary use. /// - [Fact] + [VerifyTest] public void DecoratorForAServiceThisCompilationDoesNotRegister_DoesNotReportDM0013() { var result = GeneratorTestHarness.Run( @@ -327,7 +323,7 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0013"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0013")); } /// @@ -336,34 +332,34 @@ public partial class TestModule; /// parameter leaked into typeof(ILedger<T>) beside /// GetRequiredService<Ledger<>>(). /// - [Fact] + [VerifyTest] public void CrossWiredGenericType_ReportsDM0014() { var result = GeneratorTestHarness.Run( CrossWiredLedger("public class Ledger : ILedger, IAudit;") ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0014"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0014"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("Ledger", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("Ledger")); } - [Fact] + [VerifyTest] public void CrossWiredGenericType_IsNotRegistered() { var result = GeneratorTestHarness.Run( CrossWiredLedger("public class Ledger : ILedger, IAudit;") ); - Assert.DoesNotContain(result.GeneratedSources.Keys, key => key.Contains("Dependencies")); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("Dependencies"))); } /// /// Cross-wiring a non-generic type is untouched, and still shares one instance across both /// interfaces. /// - [Fact] + [VerifyTest] public void CrossWiredNonGenericType_StillRegisters() { var generated = GeneratedAssembly.Create( @@ -373,9 +369,11 @@ public void CrossWiredNonGenericType_StillRegisters() var provider = generated.BuildProvider(); // The point of cross-wiring: both interfaces answer with the one instance. - Assert.Same( - provider.GetService(generated.Type("ILedger`1").MakeGenericType(typeof(int))), - provider.GetService(generated.Type("IAudit`1").MakeGenericType(typeof(int))) + Verify( + ReferenceEquals( + provider.GetService(generated.Type("ILedger`1").MakeGenericType(typeof(int))), + provider.GetService(generated.Type("IAudit`1").MakeGenericType(typeof(int))) + ) ); } @@ -384,7 +382,7 @@ public void CrossWiredNonGenericType_StillRegisters() /// all async. It never runs, and the build used to be green — the model was ignored before /// anything could report on it. /// - [Fact] + [VerifyTest] public void InterceptorThatServesNoMember_ReportsDM0015() { var result = GeneratorTestHarness.Run( @@ -403,19 +401,19 @@ public class AsyncOnly : IAsyncOnly { ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0015"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0015"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("SyncOnlyInterceptor", diagnostic.GetMessage()); - Assert.Contains("IAsyncInterceptor", diagnostic.GetMessage()); - Assert.Contains("GetAsync", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("SyncOnlyInterceptor")); + Verify(diagnostic.GetMessage().Contains("IAsyncInterceptor")); + Verify(diagnostic.GetMessage().Contains("GetAsync")); } /// /// The partial case: the interceptor serves the sync members and is quietly absent from the async /// one, which is how an argument-rewriting interceptor stops rewriting halfway through a service. /// - [Fact] + [VerifyTest] public void InterceptorThatServesSomeMembers_ReportsDM0015ForTheRest() { var result = GeneratorTestHarness.Run( @@ -436,16 +434,16 @@ public class Mixed : IMixed { ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0015"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0015"); - Assert.Contains("CountAsync", diagnostic.GetMessage()); - Assert.DoesNotContain("'Count'", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("CountAsync")); + Verify(!diagnostic.GetMessage().Contains("'Count'")); } /// /// An interceptor covering every shape the service uses says nothing. /// - [Fact] + [VerifyTest] public void InterceptorThatServesEveryMember_DoesNotReportDM0015() { var result = GeneratorTestHarness.Run( @@ -464,14 +462,14 @@ public class SyncOnly : ISyncOnly { ) ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0015"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0015")); } /// /// DM0008 drops the whole wrapper, not only the member it names, and the message has to say so — /// the guide read as though the other members were still intercepted. /// - [Fact] + [VerifyTest] public void UnsupportedMember_ReportsThatNoMemberIsIntercepted() { var result = GeneratorTestHarness.Run( @@ -492,10 +490,10 @@ public class Awkward : IAwkward { ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Contains("none of its members are intercepted", diagnostic.GetMessage()); - Assert.Contains("TryGet", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("none of its members are intercepted")); + Verify(diagnostic.GetMessage().Contains("TryGet")); } private static string Intercepted(string body) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs index 876b13b..cc65c41 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/EntryModelUtilTests.cs @@ -3,41 +3,40 @@ using DependencyModules.SourceGenerator.Impl.Models; using DependencyModules.SourceGenerator.Impl.Utilities; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// EntryModelUtil decides the generated file names and which entry points survive consolidation. /// Getting consolidation wrong either drops a module's registrations or emits duplicate files. /// -public class EntryModelUtilTests +public partial class EntryModelUtilTests { - [Fact] + [VerifyTest] public void GenerateFileName_CombinesNamespaceTypeAndSuffix() { var model = ModelFactory.EntryPoint( entryPointType: TypeDefinition.Get("My.Namespace", "MyModule") ); - Assert.Equal( - "My.Namespace.MyModule.Dependencies.g.cs", + Verify( EntryModelUtil.GenerateFileName(model, "Dependencies") + == "My.Namespace.MyModule.Dependencies.g.cs" ); } - [Fact] + [VerifyTest] public void GenerateFileName_ForTheGlobalNamespace_UsesAPlaceholder() { var model = ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("", "MyModule")); - Assert.Equal( - "blank-namespace.MyModule.Module.g.cs", + Verify( EntryModelUtil.GenerateFileName(model, "Module") + == "blank-namespace.MyModule.Module.g.cs" ); } - [Fact] + [VerifyTest] public void EnsureNamespace_GivesAutoGeneratedModulesTheRootNamespace() { var model = ModelFactory.EntryPoint( @@ -50,10 +49,10 @@ public void EnsureNamespace_GivesAutoGeneratedModulesTheRootNamespace() ModelFactory.Configuration(rootNamespace: "ConfiguredRoot") ); - Assert.Equal("ConfiguredRoot", result.EntryPointType.Namespace); + Verify(result.EntryPointType.Namespace == "ConfiguredRoot"); } - [Fact] + [VerifyTest] public void EnsureNamespace_LeavesAutoGeneratedModulesThatAlreadyHaveANamespace() { var model = ModelFactory.EntryPoint( @@ -66,10 +65,10 @@ public void EnsureNamespace_LeavesAutoGeneratedModulesThatAlreadyHaveANamespace( ModelFactory.Configuration(rootNamespace: "ConfiguredRoot") ); - Assert.Equal("Existing", result.EntryPointType.Namespace); + Verify(result.EntryPointType.Namespace == "Existing"); } - [Fact] + [VerifyTest] public void EnsureNamespace_LeavesExplicitlyDeclaredModulesAlone() { var model = ModelFactory.EntryPoint( @@ -81,20 +80,20 @@ public void EnsureNamespace_LeavesExplicitlyDeclaredModulesAlone() ModelFactory.Configuration(rootNamespace: "ConfiguredRoot") ); - Assert.Equal("", result.EntryPointType.Namespace); + Verify(result.EntryPointType.Namespace == ""); } - [Fact] + [VerifyTest] public void Consolidate_KeepsADeclaredModule() { var model = ModelFactory.EntryPoint(); var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(model)); - Assert.Same(model, Assert.Single(entryPoints)); + Verify(ReferenceEquals(Single(entryPoints), model)); } - [Fact] + [VerifyTest] public void Consolidate_KeepsAnAutoGeneratedModuleDeclaredInTheProjectsProgramFile() { var model = ModelFactory.EntryPoint( @@ -104,13 +103,13 @@ public void Consolidate_KeepsAnAutoGeneratedModuleDeclaredInTheProjectsProgramFi var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(model)); - Assert.Single(entryPoints); + Single(entryPoints); } /// /// A Program.cs belonging to a referenced project must not generate an ApplicationModule here. /// - [Fact] + [VerifyTest] public void Consolidate_DropsAnAutoGeneratedModuleFromAnotherProject() { var model = ModelFactory.EntryPoint( @@ -120,10 +119,10 @@ public void Consolidate_DropsAnAutoGeneratedModuleFromAnotherProject() var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(model)); - Assert.Empty(entryPoints); + Verify(entryPoints.Count == 0); } - [Fact] + [VerifyTest] public void Consolidate_WithAutoGenerateDisabled_DropsAutoGeneratedModules() { var model = ModelFactory.EntryPoint( @@ -135,10 +134,10 @@ public void Consolidate_WithAutoGenerateDisabled_DropsAutoGeneratedModules() Input(model, ModelFactory.Configuration(autoGenerateEntry: false)) ); - Assert.Empty(entryPoints); + Verify(entryPoints.Count == 0); } - [Fact] + [VerifyTest] public void Consolidate_WithAutoGenerateDisabled_KeepsDeclaredModules() { var model = ModelFactory.EntryPoint(); @@ -147,10 +146,10 @@ public void Consolidate_WithAutoGenerateDisabled_KeepsDeclaredModules() Input(model, ModelFactory.Configuration(autoGenerateEntry: false)) ); - Assert.Single(entryPoints); + Single(entryPoints); } - [Fact] + [VerifyTest] public void Consolidate_GroupsModelsSharingANamespaceAndName() { var first = ModelFactory.EntryPoint(fileLocation: "/project/A.cs"); @@ -158,14 +157,14 @@ public void Consolidate_GroupsModelsSharingANamespaceAndName() var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(first, second)); - Assert.Single(entryPoints); + Single(entryPoints); } /// /// A partial module declared alongside an auto-generated one wins: the developer's declaration /// carries the configuration. /// - [Fact] + [VerifyTest] public void Consolidate_PrefersTheDeclaredModuleOverTheAutoGeneratedOne() { var auto = ModelFactory.EntryPoint( @@ -179,10 +178,10 @@ public void Consolidate_PrefersTheDeclaredModuleOverTheAutoGeneratedOne() var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(auto, declared)); - Assert.Same(declared, Assert.Single(entryPoints)); + Verify(ReferenceEquals(Single(entryPoints), declared)); } - [Fact] + [VerifyTest] public void Consolidate_KeepsDistinctModulesSeparate() { var first = ModelFactory.EntryPoint( @@ -194,10 +193,10 @@ public void Consolidate_KeepsDistinctModulesSeparate() var (entryPoints, _) = EntryModelUtil.ConsolidateEntryPointModels(Input(first, second)); - Assert.Equal(2, entryPoints.Count); + Verify(entryPoints.Count == 2); } - [Fact] + [VerifyTest] public void Consolidate_ReturnsTheConfigurationItWasGiven() { var configuration = ModelFactory.Configuration(rootNamespace: "SomeRoot"); @@ -206,19 +205,19 @@ public void Consolidate_ReturnsTheConfigurationItWasGiven() Input(ModelFactory.EntryPoint(), configuration) ); - Assert.Same(configuration, returned); + Verify(ReferenceEquals(returned, configuration)); } - [Fact] + [VerifyTest] public void UniqueId_IsStableForTheSameType() { var first = ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("A.B", "Module")); var second = ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("A.B", "Module")); - Assert.Equal(first.UniqueId(), second.UniqueId()); + Verify(Equals(first.UniqueId(), second.UniqueId())); } - [Fact] + [VerifyTest] public void UniqueId_DiffersBetweenTypes() { var first = ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("A.B", "ModuleOne")); @@ -226,7 +225,7 @@ public void UniqueId_DiffersBetweenTypes() entryPointType: TypeDefinition.Get("A.B", "ModuleTwo") ); - Assert.NotEqual(first.UniqueId(), second.UniqueId()); + Verify(!Equals(first.UniqueId(), second.UniqueId())); } private static ImmutableArray<( diff --git a/tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs index 928c07b..e3f4cf9 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentAttributesFromSymbolsTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Runtime; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The environment attributes of a class that the generator reads as a symbol, not as a /// declaration: a decorator that [Decorate] names, and a class that a convention finds in a /// referenced assembly with InAssemblyOf<T>(). /// -public class EnvironmentAttributesFromSymbolsTests +public partial class EnvironmentAttributesFromSymbolsTests { private const string PluginLibrary = """ using DependencyModules.Runtime.Attributes; @@ -66,9 +65,9 @@ private static string Greet(GeneratedAssembly assembly) return (string)greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null)!; } - [Theory] - [InlineData("Production", null, "AlwaysPlugin, NoFeaturePlugin, NotDevelopmentPlugin")] - [InlineData("Development", "on", "AlwaysPlugin, DevelopmentPlugin, FeaturePlugin")] + [VerifyTest] + [Row("Production", null, "AlwaysPlugin, NoFeaturePlugin, NotDevelopmentPlugin")] + [Row("Development", "on", "AlwaysPlugin, DevelopmentPlugin, FeaturePlugin")] public void AClassFromAReferencedAssembly_KeepsItsEnvironmentAttributes( string environment, string? featureX, @@ -91,12 +90,12 @@ string expected .Select(d => d.ImplementationType!.Name) .OrderBy(name => name, StringComparer.Ordinal); - Assert.Equal(expected, string.Join(", ", registered)); + Verify(string.Join(", ", registered) == expected); } - [Theory] - [InlineData("Production", "hello")] - [InlineData("Development", "HELLO")] + [VerifyTest] + [Row("Production", "hello")] + [Row("Development", "HELLO")] public void ADecoratorThatDecorateNames_KeepsItsEnvironmentAttribute( string environment, string expected @@ -132,12 +131,12 @@ public partial class TestModule; environment: Environment(environment) ); - Assert.Equal(expected, Greet(assembly)); + Verify(Greet(assembly) == expected); } - [Theory] - [InlineData("Production", "hello")] - [InlineData("Development", "HELLO")] + [VerifyTest] + [Row("Production", "hello")] + [Row("Development", "HELLO")] public void ADecoratorFromAReferencedAssembly_KeepsItsEnvironmentAttribute( string environment, string expected @@ -192,7 +191,7 @@ public partial class TestModule; .BuildProvider() .GetService(library.Assembly.GetType("DecoratorPackage.IGreeter")!)!; - Assert.Equal(expected, greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null)); + Verify(Equals(greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null), expected)); } /// @@ -200,7 +199,7 @@ public partial class TestModule; /// environment. A class declared in the project gets DM0012 for this, so one read from metadata /// gets it too. /// - [Fact] + [VerifyTest] public void AnEmptyConditionOnAClassFromAReferencedAssembly_IsReported() { var library = GeneratorTestHarness.CompileLibrary( @@ -227,11 +226,11 @@ public class EmptyKeyPlugin : IPlugin { } result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); - Assert.Contains("EmptyKeyPlugin", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); + Verify(diagnostic.GetMessage().Contains("EmptyKeyPlugin")); } - [Fact] + [VerifyTest] public void AnEmptyConditionOnADecoratorThatDecorateNames_IsReported() { var result = GeneratorTestHarness.Run( @@ -265,7 +264,7 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); - Assert.Contains("LoudGreeter", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); + Verify(diagnostic.GetMessage().Contains("LoudGreeter")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs index 4ed1d11..64acf1c 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/EnvironmentConditionTests.cs @@ -1,9 +1,8 @@ using DependencyModules.Runtime; using DependencyModules.Runtime.Interfaces; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Behavioural tests for environment-conditional registration. @@ -13,7 +12,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// actually in the collection. A condition emitted into the wrong branch still produces plausible /// generated text, so text assertions would pass while the service registered in production. /// -public class EnvironmentConditionTests +public partial class EnvironmentConditionTests { private const string Preamble = """ using System; @@ -52,12 +51,12 @@ public class FakeEmailSender : IEmailSender { } public partial class TestModule; """; - [Theory] - [InlineData("Development", true)] - [InlineData("Staging", true)] - [InlineData("development", true)] - [InlineData("Production", false)] - [InlineData("", false)] + [VerifyTest] + [Row("Development", true)] + [Row("Staging", true)] + [Row("development", true)] + [Row("Production", false)] + [Row("", false)] public void IfEnvironmentRegistersOnlyInTheNamedEnvironments( string environmentName, bool expected @@ -65,10 +64,10 @@ bool expected { var assembly = Compile(NameGated + Module, Env(environmentName)); - Assert.Equal(expected, assembly.Descriptors("IEmailSender").Count == 1); + Verify((assembly.Descriptors("IEmailSender").Count == 1) == expected); } - [Fact] + [VerifyTest] public void IfNotEnvironmentRegistersEverywhereElse() { const string source = """ @@ -79,11 +78,11 @@ public interface IProfiler { } public class RequestProfiler : IProfiler { } """; - Assert.Single(Compile(source + Module, Env("Development")).Descriptors("IProfiler")); - Assert.Empty(Compile(source + Module, Env("Production")).Descriptors("IProfiler")); + Single(Compile(source + Module, Env("Development")).Descriptors("IProfiler")); + Verify(Compile(source + Module, Env("Production")).Descriptors("IProfiler").Count == 0); } - [Fact] + [VerifyTest] public void IfEnvironmentValueTestsPresenceWhenGivenOnlyAKey() { const string source = """ @@ -94,20 +93,20 @@ public interface IBilling { } public class Billing : IBilling { } """; - Assert.Single( + Single( Compile(source + Module, Env("Any", ("FEATURE_BILLING", "anything"))) .Descriptors("IBilling") ); // Set to empty is still set; only absence is absence. - Assert.Single( + Single( Compile(source + Module, Env("Any", ("FEATURE_BILLING", ""))).Descriptors("IBilling") ); - Assert.Empty(Compile(source + Module, Env("Any")).Descriptors("IBilling")); + Verify(Compile(source + Module, Env("Any")).Descriptors("IBilling").Count == 0); } - [Fact] + [VerifyTest] public void IfEnvironmentValueComparesTheValueExactly() { const string source = """ @@ -118,14 +117,18 @@ public interface IBilling { } public class Billing : IBilling { } """; - Assert.Single(Compile(source + Module, Env("Any", ("MODE", "on"))).Descriptors("IBilling")); + Single(Compile(source + Module, Env("Any", ("MODE", "on"))).Descriptors("IBilling")); // Values are data, so unlike environment names they are compared ordinally. - Assert.Empty(Compile(source + Module, Env("Any", ("MODE", "On"))).Descriptors("IBilling")); - Assert.Empty(Compile(source + Module, Env("Any", ("MODE", "off"))).Descriptors("IBilling")); + Verify( + Compile(source + Module, Env("Any", ("MODE", "On"))).Descriptors("IBilling").Count == 0 + ); + Verify( + Compile(source + Module, Env("Any", ("MODE", "off"))).Descriptors("IBilling").Count == 0 + ); } - [Fact] + [VerifyTest] public void ConditionsOfDifferentKindsCombineWithAnd() { const string source = """ @@ -137,18 +140,19 @@ public interface IThing { } public class Thing : IThing { } """; - Assert.Single( - Compile(source + Module, Env("Development", ("MODE", "on"))).Descriptors("IThing") - ); - Assert.Empty( - Compile(source + Module, Env("Development", ("MODE", "off"))).Descriptors("IThing") + Single(Compile(source + Module, Env("Development", ("MODE", "on"))).Descriptors("IThing")); + Verify( + Compile(source + Module, Env("Development", ("MODE", "off"))) + .Descriptors("IThing") + .Count == 0 ); - Assert.Empty( - Compile(source + Module, Env("Production", ("MODE", "on"))).Descriptors("IThing") + Verify( + Compile(source + Module, Env("Production", ("MODE", "on"))).Descriptors("IThing").Count + == 0 ); } - [Fact] + [VerifyTest] public void SeveralValueConditionsAllHaveToHold() { const string source = """ @@ -160,10 +164,8 @@ public interface IThing { } public class Thing : IThing { } """; - Assert.Single( - Compile(source + Module, Env("Any", ("A", "1"), ("B", "2"))).Descriptors("IThing") - ); - Assert.Empty(Compile(source + Module, Env("Any", ("A", "1"))).Descriptors("IThing")); + Single(Compile(source + Module, Env("Any", ("A", "1"), ("B", "2"))).Descriptors("IThing")); + Verify(Compile(source + Module, Env("Any", ("A", "1"))).Descriptors("IThing").Count == 0); } /// @@ -178,7 +180,7 @@ public class Thing : IThing { } /// The names are deliberate. Service models are emitted in name order, so "Fake" sorts before /// "Smtp" and the default would land last and win in every environment. /// - [Fact] + [VerifyTest] public void AConditionalRegistrationOverridesAnUnconditionalDefault() { const string source = """ @@ -195,21 +197,21 @@ public class FakeEmailSender : IEmailSender { } var development = Compile(source + Module, Env("Development")); var production = Compile(source + Module, Env("Production")); - Assert.Equal( - development.Type("FakeEmailSender"), + Verify( development.BuildProvider().GetService(development.Type("IEmailSender"))!.GetType() + == development.Type("FakeEmailSender") ); - Assert.Equal( - production.Type("SmtpEmailSender"), + Verify( production.BuildProvider().GetService(production.Type("IEmailSender"))!.GetType() + == production.Type("SmtpEmailSender") ); } /// /// The motivating case: one service type, two implementations, exactly one registered. /// - [Fact] + [VerifyTest] public void TwoImplementationsOfOneServiceSelectByEnvironment() { const string source = """ @@ -227,17 +229,17 @@ public class SmtpEmailSender : IEmailSender { public string Name => "smtp"; } var development = Compile(source + Module, Env("Development")); var production = Compile(source + Module, Env("Production")); - Assert.Equal( - development.Type("FakeEmailSender"), + Verify( development.Descriptor("IEmailSender").ImplementationType + == development.Type("FakeEmailSender") ); - Assert.Equal( - production.Type("SmtpEmailSender"), + Verify( production.Descriptor("IEmailSender").ImplementationType + == production.Type("SmtpEmailSender") ); } - [Fact] + [VerifyTest] public void UnconditionalServicesInTheSameModuleAreUnaffected() { const string source = """ @@ -254,16 +256,16 @@ public class Sometimes : ISometimes { } var production = Compile(source + Module, Env("Production")); - Assert.Single(production.Descriptors("IAlways")); - Assert.Empty(production.Descriptors("ISometimes")); + Single(production.Descriptors("IAlways")); + Verify(production.Descriptors("ISometimes").Count == 0); } - [Fact] + [VerifyTest] public void ModuleEnvironmentNoneRegistersNothingConditional() { var assembly = Compile(NameGated + Module, ModuleEnvironment.None); - Assert.Empty(assembly.Descriptors("IEmailSender")); + Verify(assembly.Descriptors("IEmailSender").Count == 0); } /// @@ -274,15 +276,14 @@ public void ModuleEnvironmentNoneRegistersNothingConditional() /// that this does not depend on what the variables happen to be while the suite runs — which /// ModuleEnvironmentDefaultNameTests moves on purpose. /// - [Fact] + [VerifyTest] public void NoEnvironmentSuppliedUsesTheProcessEnvironment() { var supplied = Compile(NameGated + Module, ModuleEnvironment.CreateDefault()); var omitted = Compile(NameGated + Module, environment: null); - Assert.Equal( - supplied.Descriptors("IEmailSender").Count, - omitted.Descriptors("IEmailSender").Count + Verify( + omitted.Descriptors("IEmailSender").Count == supplied.Descriptors("IEmailSender").Count ); } @@ -300,9 +301,9 @@ public void NoEnvironmentSuppliedUsesTheProcessEnvironment() /// A condition says "instead of my other registration, here". It does not say "instead of /// yours". /// - [Theory] - [InlineData("Development")] - [InlineData("Production")] + [VerifyTest] + [Row("Development")] + [Row("Production")] public void AReferencedModuleConditionalDoesNotOverrideTheReferencingModule( string environmentName ) @@ -327,9 +328,9 @@ public partial class TestModule; var assembly = Compile(source, Env(environmentName)); - Assert.Equal( - assembly.Type("ApplicationOwn"), + Verify( assembly.BuildProvider().GetService(assembly.Type("IEmailSender"))!.GetType() + == assembly.Type("ApplicationOwn") ); } @@ -337,9 +338,9 @@ public partial class TestModule; /// The direction that has to work: a referenced module registers the default, and the /// application conditionally overrides it. /// - [Theory] - [InlineData("Development", "ApplicationFake")] - [InlineData("Production", "LibrarySmtp")] + [VerifyTest] + [Row("Development", "ApplicationFake")] + [Row("Production", "LibrarySmtp")] public void AnApplicationConditionalOverridesAReferencedModuleDefault( string environmentName, string expected @@ -365,9 +366,9 @@ public partial class TestModule; var assembly = Compile(source, Env(environmentName)); - Assert.Equal( - assembly.Type(expected), + Verify( assembly.BuildProvider().GetService(assembly.Type("IEmailSender"))!.GetType() + == assembly.Type(expected) ); } @@ -375,7 +376,7 @@ public partial class TestModule; /// A conditional registration is additive: it shadows the default for a single resolve, and /// both are still in the enumerable. /// - [Fact] + [VerifyTest] public void AConditionalOverrideLeavesTheDefaultInTheEnumerable() { const string source = """ @@ -391,14 +392,14 @@ public class FakeEmailSender : IEmailSender { } var assembly = Compile(source + Module, Env("Development")); - Assert.Equal(2, assembly.Descriptors("IEmailSender").Count); + Verify(assembly.Descriptors("IEmailSender").Count == 2); } /// /// "When" and "how" are separate. A condition says when a registration happens; Using says what /// kind of registration it is, and the two compose. /// - [Fact] + [VerifyTest] public void AConditionCombinesWithReplace() { const string source = """ @@ -415,30 +416,30 @@ public class FakeEmailSender : IEmailSender { } var development = Compile(source + Module, Env("Development")); var production = Compile(source + Module, Env("Production")); - Assert.Single(development.Descriptors("IEmailSender")); - Assert.Equal( - development.Type("FakeEmailSender"), + Single(development.Descriptors("IEmailSender")); + Verify( development.Descriptor("IEmailSender").ImplementationType + == development.Type("FakeEmailSender") ); - Assert.Single(production.Descriptors("IEmailSender")); - Assert.Equal( - production.Type("SmtpEmailSender"), + Single(production.Descriptors("IEmailSender")); + Verify( production.Descriptor("IEmailSender").ImplementationType + == production.Type("SmtpEmailSender") ); } - [Fact] + [VerifyTest] public void ConditionsAreReportedAtBuildTime() { var result = GeneratorTestHarness.Run(Preamble + NameGated + Module); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0011"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0011"); - Assert.Contains("Development or Staging", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("Development or Staging")); } - [Fact] + [VerifyTest] public void UnconditionalServicesReportNothing() { const string source = """ @@ -450,13 +451,13 @@ public class Thing : IThing { } var result = GeneratorTestHarness.Run(Preamble + source + Module); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id is "DM0011" or "DM0012"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id is "DM0011" or "DM0012")); } - [Theory] - [InlineData("[IfEnvironment]", "environment name")] - [InlineData("[IfNotEnvironment]", "environment name")] - [InlineData("[IfEnvironmentValue(\"\")]", "key")] + [VerifyTest] + [Row("[IfEnvironment]", "environment name")] + [Row("[IfNotEnvironment]", "environment name")] + [Row("[IfEnvironmentValue(\"\")]", "key")] public void AConditionThatTestsNothingIsRefused(string attribute, string expectedKind) { var source = $$""" @@ -469,19 +470,19 @@ public class Thing : IThing { } var result = GeneratorTestHarness.Run(Preamble + source + Module); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); - Assert.Contains(expectedKind, diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains(expectedKind)); // Reported, not silently dropped: the service still registers rather than vanishing. - Assert.Single( + Single( GeneratedAssembly .Create(Preamble + source + Module, environment: ModuleEnvironment.None) .Descriptors("IThing") ); } - [Fact] + [VerifyTest] public void AConditionThatTestsNothingOnAConventionClassIsRefused() { var result = GeneratorTestHarness.Run( @@ -507,12 +508,12 @@ public void Conventions(IConventionDefinitions conventions) """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); - Assert.Contains("EmptyRule", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("EmptyRule")); } - [Fact] + [VerifyTest] public void AConditionThatTestsNothingOnADecoratorIsRefused() { var result = GeneratorTestHarness.Run( @@ -530,16 +531,16 @@ public class LoggingThing(IThing inner) : IThing { } + Module ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0012"); - Assert.Contains("LoggingThing", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("LoggingThing")); } /// /// A const rather than a literal has to read as the string it evaluates to, or a codebase that /// keeps its environment names in one place would silently never match. /// - [Fact] + [VerifyTest] public void ConditionArgumentsMayBeConstants() { const string source = """ @@ -554,8 +555,8 @@ public interface IThing { } public class Thing : IThing { } """; - Assert.Single(Compile(source + Module, Env("Development")).Descriptors("IThing")); - Assert.Empty(Compile(source + Module, Env("Production")).Descriptors("IThing")); + Single(Compile(source + Module, Env("Development")).Descriptors("IThing")); + Verify(Compile(source + Module, Env("Production")).Descriptors("IThing").Count == 0); } /// @@ -563,7 +564,7 @@ public class Thing : IThing { } /// A namespace-qualified usage silently matching nothing is a bug this generator has had once /// already, and here it would register a development service in production. /// - [Fact] + [VerifyTest] public void ANamespaceQualifiedConditionStillApplies() { const string source = """ @@ -574,7 +575,7 @@ public interface IThing { } public class Thing : IThing { } """; - Assert.Single(Compile(source + Module, Env("Development")).Descriptors("IThing")); - Assert.Empty(Compile(source + Module, Env("Production")).Descriptors("IThing")); + Single(Compile(source + Module, Env("Development")).Descriptors("IThing")); + Verify(Compile(source + Module, Env("Production")).Descriptors("IThing").Count == 0); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs index ccdbe25..15670e0 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ExtensionSeamTests.cs @@ -2,16 +2,15 @@ using DependencyModules.SourceGenerator.Impl; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The seam a framework builds on: its own module attribute through ModuleAttributeTypes(), /// its own attribute generators through AttributeSourceGenerators(). Both of these pin /// behaviour a framework only finds out about in a consuming application, which is too late. /// -public class ExtensionSeamTests +public partial class ExtensionSeamTests { private const string FrameworkAttribute = """ namespace Test.Framework; @@ -52,7 +51,7 @@ public static IServiceCollection Compose() => /// no module emitted this compilation fails, exactly as the consuming application did while /// SetupRootGenerator was empty by default and easy to miss. /// - [Fact] + [VerifyTest] public void FrameworkGenerator_EmitsTheModule_WithoutOverridingSetupRootGenerator() { var result = GeneratorTestHarness.Run( @@ -68,13 +67,13 @@ public void FrameworkGenerator_EmitsTheModule_WithoutOverridingSetupRootGenerato ); result.AssertNoErrors(); - Assert.Contains("IDependencyModule", result.SourceContaining("AppModule.Module")); + Verify(result.SourceContaining("AppModule.Module").Contains("IDependencyModule")); } /// /// A generator that only contributes providers opts out, and then nothing declares the module. /// - [Fact] + [VerifyTest] public void FrameworkGenerator_OptingOut_EmitsNoModule() { var result = GeneratorTestHarness.Run( @@ -86,10 +85,7 @@ public void FrameworkGenerator_OptingOut_EmitsNoModule() generators: new ISourceGenerator[] { new ProvidersOnlyGenerator().AsSourceGenerator() } ); - Assert.DoesNotContain( - result.GeneratedSources.Keys, - key => key.Contains("AppModule.Module") - ); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("AppModule.Module"))); } /// @@ -102,7 +98,7 @@ public void FrameworkGenerator_OptingOut_EmitsNoModule() /// extension seam, and a console application is the ordinary shape of a consumer, so the two /// have to work together. /// - [Fact] + [VerifyTest] public void StackedGenerators_OverAConsoleApplication_EmitOneApplicationModule() { var result = GeneratorTestHarness.Run( @@ -124,11 +120,8 @@ public void StackedGenerators_OverAConsoleApplication_EmitOneApplicationModule() result.AssertNoErrors(); - Assert.Empty(result.DuplicateHintNames); - Assert.Single( - result.GeneratedSources.Keys, - key => key.Contains("ApplicationModule.Module") - ); + Verify(result.DuplicateHintNames.Count == 0); + Single(result.GeneratedSources.Keys, key => key.Contains("ApplicationModule.Module")); } /// @@ -136,7 +129,7 @@ public void StackedGenerators_OverAConsoleApplication_EmitOneApplicationModule() /// modules rather than declaring modules of its own. Those partials belong to the generator /// this package ships, and writing them from both declares every module twice. /// - [Fact] + [VerifyTest] public void ThirdPartyGenerator_OnTheDefaultModuleAttribute_WritesNoModuleOfItsOwn() { var source = """ @@ -171,8 +164,8 @@ public static IServiceCollection Compose() => result.AssertNoErrors(); - Assert.Empty(result.DuplicateHintNames); - Assert.Single(result.GeneratedSources.Keys, key => key.Contains("AppModule.Module")); + Verify(result.DuplicateHintNames.Count == 0); + Single(result.GeneratedSources.Keys, key => key.Contains("AppModule.Module")); } /// diff --git a/tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs b/tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs index 5c1729d..45a4f74 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/FileLoggerTests.cs @@ -1,14 +1,13 @@ using DependencyModules.SourceGenerator.Impl.Models; using DependencyModules.SourceGenerator.Impl.Utilities; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// FileLogger backs the DependencyModules_LogOutputDirectory build property. It runs inside the /// compiler, so it must be inert unless explicitly switched on and must never fail a build. /// -public class FileLoggerTests : IDisposable +public partial class FileLoggerTests : IDisposable { private readonly string _outputFolder = Path.Combine( Path.GetTempPath(), @@ -16,7 +15,7 @@ public class FileLoggerTests : IDisposable Guid.NewGuid().ToString("n") ); - [Fact] + [VerifyTest] public void WithNoOutputFolder_WritesNothing() { var before = Directory.GetCurrentDirectory(); @@ -28,14 +27,14 @@ public void WithNoOutputFolder_WritesNothing() logger.Error("a problem"); } - Assert.Equal(filesBefore.Length, Directory.GetFiles(before).Length); + Verify(Directory.GetFiles(before).Length == filesBefore.Length); } /// /// Regression test: logs used to land in the compiler's working directory, ignoring the /// configured folder entirely. /// - [Fact] + [VerifyTest] public void WithAnOutputFolder_WritesIntoThatFolder() { using (var logger = new FileLogger(Configuration(_outputFolder), "generator")) @@ -45,25 +44,25 @@ public void WithAnOutputFolder_WritesIntoThatFolder() var written = Directory.GetFiles(_outputFolder); - var file = Assert.Single(written); - Assert.StartsWith("generator.", Path.GetFileName(file)); - Assert.EndsWith(".txt", file); + var file = Single(written); + Verify(Path.GetFileName(file).StartsWith("generator.")); + Verify(file.EndsWith(".txt")); } - [Fact] + [VerifyTest] public void WithAnOutputFolder_CreatesTheFolderIfMissing() { - Assert.False(Directory.Exists(_outputFolder)); + Verify(!Directory.Exists(_outputFolder)); using (var logger = new FileLogger(Configuration(_outputFolder), "generator")) { logger.Info("a message"); } - Assert.True(Directory.Exists(_outputFolder)); + Verify(Directory.Exists(_outputFolder)); } - [Fact] + [VerifyTest] public void RecordsLevelsAndMessages() { using (var logger = new FileLogger(Configuration(_outputFolder), "generator")) @@ -75,19 +74,19 @@ public void RecordsLevelsAndMessages() var content = File.ReadAllText(Directory.GetFiles(_outputFolder).Single()); - Assert.Contains("INFO: an info message", content); - Assert.Contains("ERROR: an error message", content); - Assert.Contains("the data", content); + Verify(content.Contains("INFO: an info message")); + Verify(content.Contains("ERROR: an error message")); + Verify(content.Contains("the data")); } /// /// With no reporter the exception must escape, so Roslyn reports its own generator failure. /// Swallowing it produced a successful build with no registrations and no message at all. /// - [Fact] + [VerifyTest] public void Wrap_WithoutAReporter_RethrowsSoTheFailureIsVisible() { - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => FileLogger.Wrap( "generator", Configuration(_outputFolder), @@ -95,10 +94,10 @@ public void Wrap_WithoutAReporter_RethrowsSoTheFailureIsVisible() ) ); - Assert.Equal("generator blew up", exception.Message); + Verify(exception.Message == "generator blew up"); } - [Fact] + [VerifyTest] public void Wrap_WithAReporter_HandsItTheExceptionInsteadOfPropagating() { Exception? reported = null; @@ -110,11 +109,10 @@ public void Wrap_WithAReporter_HandsItTheExceptionInsteadOfPropagating() exception => reported = exception ); - Assert.NotNull(reported); - Assert.Equal("generator blew up", reported!.Message); + Verify(NotNull(reported).Message == "generator blew up"); } - [Fact] + [VerifyTest] public void Wrap_RecordsTheExceptionInTheLog() { FileLogger.Wrap( @@ -126,16 +124,16 @@ public void Wrap_RecordsTheExceptionInTheLog() var content = File.ReadAllText(Directory.GetFiles(_outputFolder).Single()); - Assert.Contains("ERROR", content); - Assert.Contains("generator blew up", content); + Verify(content.Contains("ERROR")); + Verify(content.Contains("generator blew up")); } - [Fact] + [VerifyTest] public void Wrap_LetsCancellationThrough() { var reported = false; - Assert.Throws(() => + ThrowsExactly(() => FileLogger.Wrap( "generator", Configuration(_outputFolder), @@ -144,13 +142,13 @@ public void Wrap_LetsCancellationThrough() ) ); - Assert.False(reported); + Verify(!reported); } /// /// Loggers with one name, disposed together, usually get the same millisecond. /// - [Fact] + [VerifyTest] public void LoggersWithOneName_EachWriteTheirOwnFile() { for (var i = 0; i < 10; i++) @@ -164,10 +162,10 @@ public void LoggersWithOneName_EachWriteTheirOwnFile() .Select(file => File.ReadAllText(file).Trim()) .OrderBy(content => content, StringComparer.Ordinal); - Assert.Equal(Enumerable.Range(0, 10).Select(i => $"INFO: logger {i}"), contents); + Verify(contents.SequenceEqual(Enumerable.Range(0, 10).Select(i => $"INFO: logger {i}"))); } - [Fact] + [VerifyTest] public void Wrap_RunsTheCallbackAndDisposesTheLogger() { var ran = false; @@ -182,11 +180,11 @@ public void Wrap_RunsTheCallbackAndDisposesTheLogger() } ); - Assert.True(ran); - Assert.Contains("inside", File.ReadAllText(Directory.GetFiles(_outputFolder).Single())); + Verify(ran); + Verify(File.ReadAllText(Directory.GetFiles(_outputFolder).Single()).Contains("inside")); } - [Fact] + [VerifyTest] public void AnUnwritableOutputFolder_DoesNotThrow() { // A path whose parent is a file cannot be created; logging must still not fail the build. @@ -198,9 +196,18 @@ public void AnUnwritableOutputFolder_DoesNotThrow() var logger = new FileLogger(Configuration(Path.Combine(file, "nested")), "generator"); logger.Info("a message"); - var exception = Record.Exception(() => logger.Dispose()); + Exception? exception = null; - Assert.Null(exception); + try + { + logger.Dispose(); + } + catch (Exception caught) + { + exception = caught; + } + + Verify(exception is null); } finally { diff --git a/tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs b/tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs index 70fb228..8011be6 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/FileNameHintTests.cs @@ -2,39 +2,37 @@ using DependencyModules.SourceGenerator.Impl.Utilities; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The hint name of a generated file. Roslyn refuses a second file with the same name, and the run /// then gives CS8785 and no generated code at all. /// -public class FileNameHintTests +public partial class FileNameHintTests { - [Theory] - [InlineData("App", "FooModule.Module.g.cs")] - [InlineData("App.Sub", "Sub.FooModule.Module.g.cs")] - [InlineData("App.global", "global.FooModule.Module.g.cs")] - [InlineData("Sub", "global-Sub.FooModule.Module.g.cs")] - [InlineData("Application", "global-Application.FooModule.Module.g.cs")] - [InlineData("", "global-FooModule.Module.g.cs")] + [VerifyTest] + [Row("App", "FooModule.Module.g.cs")] + [Row("App.Sub", "Sub.FooModule.Module.g.cs")] + [Row("App.global", "global.FooModule.Module.g.cs")] + [Row("Sub", "global-Sub.FooModule.Module.g.cs")] + [Row("Application", "global-Application.FooModule.Module.g.cs")] + [Row("", "global-FooModule.Module.g.cs")] public void WithARootNamespace(string typeNamespace, string expected) { - Assert.Equal( - expected, + Verify( TypeDefinition.Get(typeNamespace, "FooModule").GetFileNameHint("App", "Module") + == expected ); } - [Theory] - [InlineData("Sub", "Sub.FooModule.Module.g.cs")] - [InlineData("", "FooModule.Module.g.cs")] + [VerifyTest] + [Row("Sub", "Sub.FooModule.Module.g.cs")] + [Row("", "FooModule.Module.g.cs")] public void WithoutARootNamespace_TheFullNameIsUsed(string typeNamespace, string expected) { - Assert.Equal( - expected, - TypeDefinition.Get(typeNamespace, "FooModule").GetFileNameHint("", "Module") + Verify( + TypeDefinition.Get(typeNamespace, "FooModule").GetFileNameHint("", "Module") == expected ); } @@ -42,7 +40,7 @@ public void WithoutARootNamespace_TheFullNameIsUsed(string typeNamespace, string /// With the root namespace App removed, App.Sub.FooModule has the name of /// Sub.FooModule. /// - [Fact] + [VerifyTest] public void ModulesThatDifferOnlyByTheRootNamespace_BothGetTheirCode() { var result = GeneratorTestHarness.Run( @@ -84,7 +82,7 @@ public partial class OtherModule; ); result.AssertNoErrors(); - Assert.Contains("Sub.FooModule.Module.g.cs", result.GeneratedSources.Keys); - Assert.Contains("global-Sub.FooModule.Module.g.cs", result.GeneratedSources.Keys); + Verify(result.GeneratedSources.ContainsKey("Sub.FooModule.Module.g.cs")); + Verify(result.GeneratedSources.ContainsKey("global-Sub.FooModule.Module.g.cs")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs index b68cc4b..1e15b96 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GenerateFactoriesInterceptionTests.cs @@ -2,9 +2,8 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Interception under DependencyModules_GenerateFactories. @@ -24,7 +23,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// property's whole contract — it is meant to change how a service is constructed, not what is /// registered or what wraps it. /// -public class GenerateFactoriesInterceptionTests +public partial class GenerateFactoriesInterceptionTests { private const string Interceptor = """ public sealed class CountingInterceptor : IInterceptor { @@ -35,9 +34,9 @@ public sealed class CountingInterceptor : IInterceptor { /// /// The 1.1.0 fix itself: a sibling implementation carrying no [Intercept] is not wrapped. /// - [Theory] - [InlineData(false)] - [InlineData(true)] + [VerifyTest] + [Row(false)] + [Row(true)] public void AnUnmarkedSibling_IsNotWrapped(bool generateFactories) { var resolved = Resolve( @@ -51,16 +50,16 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } generateFactories ); - Assert.Equal(["Loud_Intercepted", "Quiet"], resolved); + Verify(resolved.SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } /// /// And the same registration is not wrapped twice. Two marked implementations each get their /// own wrapper rather than both getting both. /// - [Theory] - [InlineData(false)] - [InlineData(true)] + [VerifyTest] + [Row(false)] + [Row(true)] public void TwoMarkedImplementations_EachGetTheirOwnWrapper(bool generateFactories) { var resolved = Resolve( @@ -74,16 +73,16 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } generateFactories ); - Assert.Equal(["Loud_Intercepted", "Quiet_Intercepted"], resolved); + Verify(resolved.SequenceEqual(new[] { "Loud_Intercepted", "Quiet_Intercepted" })); } /// /// A keyed registration is still one registration. Agent 08 measured a keyed service coming back /// as another implementation's wrapper. /// - [Theory] - [InlineData(false)] - [InlineData(true)] + [VerifyTest] + [Row(false)] + [Row(true)] public void AKeyedSibling_IsNotWrapped(bool generateFactories) { var generated = Build( @@ -103,17 +102,17 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } var loud = ((IKeyedServiceProvider)provider).GetRequiredKeyedService(serviceType, "loud"); var quiet = ((IKeyedServiceProvider)provider).GetRequiredKeyedService(serviceType, "quiet"); - Assert.Equal("Loud_Intercepted", loud.GetType().Name); - Assert.Equal("Quiet", quiet.GetType().Name); + Verify(loud.GetType().Name == "Loud_Intercepted"); + Verify(quiet.GetType().Name == "Quiet"); } /// /// The convention route to the same registrations. Convention-produced models are built by a /// different path from attribute-produced ones, so the exemption has to reach both. /// - [Theory] - [InlineData(false)] - [InlineData(true)] + [VerifyTest] + [Row(false)] + [Row(true)] public void AConventionRegisteredSibling_IsNotWrapped(bool generateFactories) { var generated = GeneratedAssembly.Create( @@ -159,7 +158,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { .OrderBy(name => name, System.StringComparer.Ordinal) .ToArray(); - Assert.Equal(["Loud_Intercepted", "Quiet"], resolved); + Verify(resolved.SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } private static string[] Resolve(string body, bool generateFactories) diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs index bb164a5..863d489 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratedBehaviourTests.cs @@ -1,8 +1,7 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Compiles source with the generator, loads the emitted assembly, and asserts on what the @@ -12,9 +11,9 @@ namespace DependencyModules.Tests.GeneratorTests; /// These are the tests that would fail if the generator emitted well-formed code that registered /// the wrong thing. Asserting on the shape of generated text cannot catch that. /// -public class GeneratedBehaviourTests +public partial class GeneratedBehaviourTests { - [Fact] + [VerifyTest] public void SingletonService_ResolvesTheImplementation() { var generated = GeneratedAssembly.Create( @@ -23,10 +22,10 @@ public void SingletonService_ResolvesTheImplementation() var resolved = generated.ResolveRequired("IThing"); - Assert.Equal(generated.Type("Thing"), resolved.GetType()); + Verify(resolved.GetType() == generated.Type("Thing")); } - [Fact] + [VerifyTest] public void SingletonService_ReturnsTheSameInstanceEveryTime() { var generated = GeneratedAssembly.Create( @@ -35,10 +34,10 @@ public void SingletonService_ReturnsTheSameInstanceEveryTime() var provider = generated.BuildProvider(); var serviceType = generated.Type("IThing"); - Assert.Same(provider.GetService(serviceType), provider.GetService(serviceType)); + Verify(ReferenceEquals(provider.GetService(serviceType), provider.GetService(serviceType))); } - [Fact] + [VerifyTest] public void TransientService_ReturnsANewInstanceEveryTime() { var generated = GeneratedAssembly.Create( @@ -47,10 +46,12 @@ public void TransientService_ReturnsANewInstanceEveryTime() var provider = generated.BuildProvider(); var serviceType = generated.Type("IThing"); - Assert.NotSame(provider.GetService(serviceType), provider.GetService(serviceType)); + Verify( + !ReferenceEquals(provider.GetService(serviceType), provider.GetService(serviceType)) + ); } - [Fact] + [VerifyTest] public void ScopedService_IsSharedWithinAScopeAndDiffersAcrossScopes() { var generated = GeneratedAssembly.Create( @@ -66,14 +67,14 @@ public void ScopedService_IsSharedWithinAScopeAndDiffersAcrossScopes() var firstB = first.ServiceProvider.GetService(serviceType); var secondA = second.ServiceProvider.GetService(serviceType); - Assert.Same(firstA, firstB); - Assert.NotSame(firstA, secondA); + Verify(ReferenceEquals(firstA, firstB)); + Verify(!ReferenceEquals(firstA, secondA)); } - [Theory] - [InlineData("SingletonService", ServiceLifetime.Singleton)] - [InlineData("ScopedService", ServiceLifetime.Scoped)] - [InlineData("TransientService", ServiceLifetime.Transient)] + [VerifyTest] + [Row("SingletonService", ServiceLifetime.Singleton)] + [Row("ScopedService", ServiceLifetime.Scoped)] + [Row("TransientService", ServiceLifetime.Transient)] public void ServiceAttribute_RegistersTheMatchingLifetime( string attribute, ServiceLifetime expected @@ -83,10 +84,10 @@ ServiceLifetime expected Module($"[{attribute}] public class Thing : IThing;") ); - Assert.Equal(expected, generated.Descriptor("IThing").Lifetime); + Verify(generated.Descriptor("IThing").Lifetime == expected); } - [Fact] + [VerifyTest] public void AsProperty_ResolvesUnderTheRequestedServiceTypeOnly() { var generated = GeneratedAssembly.Create( @@ -100,11 +101,11 @@ public interface IOther; var provider = generated.BuildProvider(); - Assert.NotNull(provider.GetService(generated.Type("IOther"))); - Assert.Null(provider.GetService(generated.Type("IThing"))); + Verify(provider.GetService(generated.Type("IOther")) is not null); + Verify(provider.GetService(generated.Type("IThing")) is null); } - [Fact] + [VerifyTest] public void KeyedService_ResolvesOnlyThroughItsKey() { var generated = GeneratedAssembly.Create( @@ -114,11 +115,11 @@ public void KeyedService_ResolvesOnlyThroughItsKey() var provider = generated.BuildProvider(); var serviceType = generated.Type("IThing"); - Assert.NotNull(provider.GetKeyedService(serviceType, "the-key")); - Assert.Null(provider.GetService(serviceType)); + Verify(provider.GetKeyedService(serviceType, "the-key") is not null); + Verify(provider.GetService(serviceType) is null); } - [Fact] + [VerifyTest] public void KeyedServices_WithDifferentKeysResolveDifferentImplementations() { var generated = GeneratedAssembly.Create( @@ -133,13 +134,13 @@ public void KeyedServices_WithDifferentKeysResolveDifferentImplementations() var provider = generated.BuildProvider(); var serviceType = generated.Type("IThing"); - Assert.Equal( - generated.Type("FirstThing"), + Verify( provider.GetKeyedService(serviceType, "first")!.GetType() + == generated.Type("FirstThing") ); - Assert.Equal( - generated.Type("SecondThing"), + Verify( provider.GetKeyedService(serviceType, "second")!.GetType() + == generated.Type("SecondThing") ); } @@ -147,7 +148,7 @@ public void KeyedServices_WithDifferentKeysResolveDifferentImplementations() /// The contract of [CrossWireService]: one instance, reachable through the implementation type /// and through every interface it implements. /// - [Fact] + [VerifyTest] public void CrossWireService_SharesOneInstanceAcrossAllItsInterfaces() { var generated = GeneratedAssembly.Create( @@ -167,23 +168,23 @@ public class Thing : IThing, IOther; var asOther = provider.GetService(generated.Type("IOther")); var asImplementation = provider.GetService(generated.Type("Thing")); - Assert.NotNull(asThing); - Assert.Same(asThing, asOther); - Assert.Same(asThing, asImplementation); + Verify(asThing is not null); + Verify(ReferenceEquals(asThing, asOther)); + Verify(ReferenceEquals(asThing, asImplementation)); } - [Fact] + [VerifyTest] public void TryRegistration_DoesNotReplaceAnExistingRegistration() { var generated = GeneratedAssembly.Create( Module("[SingletonService(Using = RegistrationType.Try)] public class Thing : IThing;") ); - Assert.Equal(ServiceLifetime.Singleton, generated.Descriptor("IThing").Lifetime); - Assert.Equal(generated.Type("Thing"), generated.ResolveRequired("IThing").GetType()); + Verify(generated.Descriptor("IThing").Lifetime == ServiceLifetime.Singleton); + Verify(generated.ResolveRequired("IThing").GetType() == generated.Type("Thing")); } - [Fact] + [VerifyTest] public void ReplaceRegistration_LeavesASingleRegistration() { var generated = GeneratedAssembly.Create( @@ -192,7 +193,7 @@ public void ReplaceRegistration_LeavesASingleRegistration() ) ); - Assert.Single(generated.Descriptors("IThing")); + Single(generated.Descriptors("IThing")); } /// @@ -202,7 +203,7 @@ public void ReplaceRegistration_LeavesASingleRegistration() /// nothing and added itself, then the registration it meant to displace was added after it and /// won. Renaming the class fixed it, and nothing said so. /// - [Fact] + [VerifyTest] public void ReplaceRegistration_WinsEvenWhenItsTypeNameSortsFirst() { var generated = GeneratedAssembly.Create( @@ -214,11 +215,11 @@ public void ReplaceRegistration_WinsEvenWhenItsTypeNameSortsFirst() ) ); - Assert.Single(generated.Descriptors("IThing")); - Assert.Equal(generated.Type("AaaThing"), generated.ResolveRequired("IThing").GetType()); + Single(generated.Descriptors("IThing")); + Verify(generated.ResolveRequired("IThing").GetType() == generated.Type("AaaThing")); } - [Fact] + [VerifyTest] public void TryRegistration_DeclinesEvenWhenItsTypeNameSortsFirst() { var generated = GeneratedAssembly.Create( @@ -230,11 +231,11 @@ public void TryRegistration_DeclinesEvenWhenItsTypeNameSortsFirst() ) ); - Assert.Single(generated.Descriptors("IThing")); - Assert.Equal(generated.Type("ZzzThing"), generated.ResolveRequired("IThing").GetType()); + Single(generated.Descriptors("IThing")); + Verify(generated.ResolveRequired("IThing").GetType() == generated.Type("ZzzThing")); } - [Fact] + [VerifyTest] public void ConstructorDependencies_AreInjectedFromTheContainer() { var generated = GeneratedAssembly.Create( @@ -258,11 +259,11 @@ public class Thing : IThing { var injected = thing.GetType().GetProperty("Injected")!.GetValue(thing); - Assert.NotNull(injected); - Assert.Same(provider.GetService(generated.Type("IDependency")), injected); + Verify(injected is not null); + Verify(ReferenceEquals(provider.GetService(generated.Type("IDependency")), injected)); } - [Fact] + [VerifyTest] public void StaticFactory_IsInvokedToCreateTheService() { var generated = GeneratedAssembly.Create( @@ -280,10 +281,10 @@ public class Thing : IThing { var thing = generated.ResolveRequired("IThing"); - Assert.Equal("factory", thing.GetType().GetProperty("Origin")!.GetValue(thing)); + Verify(Equals(thing.GetType().GetProperty("Origin")!.GetValue(thing), "factory")); } - [Fact] + [VerifyTest] public void StaticFactory_ReceivesItsDependenciesFromTheContainer() { var generated = GeneratedAssembly.Create( @@ -306,13 +307,15 @@ public class Thing : IThing { var provider = generated.BuildProvider(); var thing = provider.GetService(generated.Type("IThing"))!; - Assert.Same( - provider.GetService(generated.Type("IDependency")), - thing.GetType().GetProperty("Injected")!.GetValue(thing) + Verify( + ReferenceEquals( + provider.GetService(generated.Type("IDependency")), + thing.GetType().GetProperty("Injected")!.GetValue(thing) + ) ); } - [Fact] + [VerifyTest] public void OpenGenericService_ResolvesForAnyTypeArgument() { var generated = GeneratedAssembly.Create( @@ -334,10 +337,10 @@ public partial class TestModule; var provider = generated.BuildProvider(); var closed = generated.Type("IGeneric`1").MakeGenericType(typeof(string)); - Assert.NotNull(provider.GetService(closed)); + Verify(provider.GetService(closed) is not null); } - [Fact] + [VerifyTest] public void ClosedGenericService_ResolvesForItsOwnArgumentOnly() { var generated = GeneratedAssembly.Create( @@ -359,11 +362,11 @@ public partial class TestModule; var provider = generated.BuildProvider(); var generic = generated.Type("IGeneric`1"); - Assert.NotNull(provider.GetService(generic.MakeGenericType(typeof(string)))); - Assert.Null(provider.GetService(generic.MakeGenericType(typeof(int)))); + Verify(provider.GetService(generic.MakeGenericType(typeof(string))) is not null); + Verify(provider.GetService(generic.MakeGenericType(typeof(int))) is null); } - [Fact] + [VerifyTest] public void NestedService_ResolvesThroughItsContainingType() { var generated = GeneratedAssembly.Create( @@ -377,20 +380,20 @@ public class Inner : IThing; ) ); - Assert.Equal("Inner", generated.ResolveRequired("IThing").GetType().Name); + Verify(generated.ResolveRequired("IThing").GetType().Name == "Inner"); } - [Fact] + [VerifyTest] public void RecordService_Resolves() { var generated = GeneratedAssembly.Create( Module("[SingletonService] public record ThingRecord : IThing;") ); - Assert.Equal(generated.Type("ThingRecord"), generated.ResolveRequired("IThing").GetType()); + Verify(generated.ResolveRequired("IThing").GetType() == generated.Type("ThingRecord")); } - [Fact] + [VerifyTest] public void ModuleConfiguration_RunsAlongsideGeneratedRegistrations() { var generated = GeneratedAssembly.Create( @@ -419,11 +422,11 @@ public void ConfigureServices(IServiceCollection services) { var provider = generated.BuildProvider(); - Assert.NotNull(provider.GetService(generated.Type("IThing"))); - Assert.NotNull(provider.GetService(generated.Type("IManual"))); + Verify(provider.GetService(generated.Type("IThing")) is not null); + Verify(provider.GetService(generated.Type("IManual")) is not null); } - [Fact] + [VerifyTest] public void OnlyRealm_RegistersOnlyServicesInThatRealm() { var generated = GeneratedAssembly.Create( @@ -449,11 +452,11 @@ public class OutsideRealm : IOutsideRealm; var provider = generated.BuildProvider(); - Assert.NotNull(provider.GetService(generated.Type("IInRealm"))); - Assert.Null(provider.GetService(generated.Type("IOutsideRealm"))); + Verify(provider.GetService(generated.Type("IInRealm")) is not null); + Verify(provider.GetService(generated.Type("IOutsideRealm")) is null); } - [Fact] + [VerifyTest] public void ComposedModule_AppliesTheModulesItReferences() { var generated = GeneratedAssembly.Create( @@ -477,10 +480,10 @@ public partial class ComposedModule; "ComposedModule" ); - Assert.NotNull(generated.BuildProvider().GetService(generated.Type("IFromBase"))); + Verify(generated.BuildProvider().GetService(generated.Type("IFromBase")) is not null); } - [Fact] + [VerifyTest] public void ServiceWithNoInterface_ResolvesAsItself() { var generated = GeneratedAssembly.Create( @@ -497,7 +500,7 @@ public partial class TestModule; """ ); - Assert.NotNull(generated.BuildProvider().GetService(generated.Type("Standalone"))); + Verify(generated.BuildProvider().GetService(generated.Type("Standalone")) is not null); } private static string Module(string body, string extraUsings = "") => diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs index c76bd5f..9554ce5 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeAccessTests.cs @@ -1,14 +1,13 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Whether generated code can use a type, a method or a constructor comes from its symbol. The /// written keywords do not say it: a nested type or a member with no access modifier is private, /// and a public member of a private type is out of reach too. /// -public class GeneratedCodeAccessTests +public partial class GeneratedCodeAccessTests { private const string Preamble = """ using DependencyModules.Runtime.Attributes; @@ -33,7 +32,7 @@ public void Conventions(IConventionDefinitions conventions) } """; - [Fact] + [VerifyTest] public void AConvention_SkipsANestedClassThatGeneratedCodeCannotUse() { var result = Run( @@ -63,14 +62,14 @@ public class PublicInPrivateRule : IRule { } var registrations = result.SourceContaining("ConventionDependencies"); - Assert.DoesNotContain("ImplicitlyPrivateRule", registrations); - Assert.DoesNotContain("ProtectedRule)", registrations); - Assert.DoesNotContain("PublicInPrivateRule", registrations); - Assert.Contains("RuleSet.ProtectedInternalRule", registrations); - Assert.Contains("RuleSet.OpenRule", registrations); + Verify(!registrations.Contains("ImplicitlyPrivateRule")); + Verify(!registrations.Contains("ProtectedRule)")); + Verify(!registrations.Contains("PublicInPrivateRule")); + Verify(registrations.Contains("RuleSet.ProtectedInternalRule")); + Verify(registrations.Contains("RuleSet.OpenRule")); } - [Fact] + [VerifyTest] public void AConventionBySelf_SkipsANestedClassWithNoAccessModifier() { var result = Run( @@ -92,11 +91,11 @@ public class OpenWorker { } var registrations = result.SourceContaining("ConventionDependencies"); - Assert.DoesNotContain("HiddenWorker", registrations); - Assert.Contains("Workers.OpenWorker", registrations); + Verify(!registrations.Contains("HiddenWorker")); + Verify(registrations.Contains("Workers.OpenWorker")); } - [Fact] + [VerifyTest] public void AConvention_SkipsAFileLocalClass() { var result = Run( @@ -114,11 +113,11 @@ public class OpenRule : IRule { } var registrations = result.SourceContaining("ConventionDependencies"); - Assert.DoesNotContain("FileRule", registrations); - Assert.Contains("OpenRule", registrations); + Verify(!registrations.Contains("FileRule")); + Verify(registrations.Contains("OpenRule")); } - [Fact] + [VerifyTest] public void AFactoryMethodWithNoAccessModifier_IsReported_AndNotCalled() { var result = Run( @@ -140,16 +139,16 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); - Assert.Contains("'ClockFactories.CreateClock'", diagnostic.GetMessage()); - Assert.DoesNotContain(result.GeneratedSources.Values, s => s.Contains("CreateClock")); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); + Verify(diagnostic.GetMessage().Contains("'ClockFactories.CreateClock'")); + Verify(!result.GeneratedSources.Values.Any(s => s.Contains("CreateClock"))); } - [Theory] - [InlineData("private static", "private or protected")] - [InlineData("protected static", "private or protected")] - [InlineData("private protected static", "private or protected")] - [InlineData("public", "not static")] + [VerifyTest] + [Row("private static", "private or protected")] + [Row("protected static", "private or protected")] + [Row("private protected static", "private or protected")] + [Row("public", "not static")] public void AFactoryMethodTheModuleCannotCall_IsReported(string modifiers, string reason) { var result = Run( @@ -171,12 +170,12 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); - Assert.Contains(reason, diagnostic.GetMessage()); - Assert.DoesNotContain(result.GeneratedSources.Values, s => s.Contains("CreateTimer")); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); + Verify(diagnostic.GetMessage().Contains(reason)); + Verify(!result.GeneratedSources.Values.Any(s => s.Contains("CreateTimer"))); } - [Fact] + [VerifyTest] public void AFactoryMethodInAPrivateClass_IsReported() { var result = Run( @@ -201,11 +200,11 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); - Assert.Contains("'Outer.Factories.CreateTimer'", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0023"); + Verify(diagnostic.GetMessage().Contains("'Outer.Factories.CreateTimer'")); } - [Fact] + [VerifyTest] public void AnInternalFactoryMethodInAnInternalClass_IsCalled() { var assembly = GeneratedAssembly.Create( @@ -226,12 +225,12 @@ public partial class TestModule; """ ); - Assert.Equal("Timer", assembly.ResolveRequired("ITimer").GetType().Name); + Verify(assembly.ResolveRequired("ITimer").GetType().Name == "Timer"); } - [Theory] - [InlineData("internal")] - [InlineData("protected internal")] + [VerifyTest] + [Row("internal")] + [Row("protected internal")] public void AConventionClassWithOnlyAnInternalConstructor_IsReported(string access) { var result = Run( @@ -248,11 +247,12 @@ public class Handler : IHandler result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); - Assert.Contains("no public constructor", diagnostic.GetMessage()); - Assert.DoesNotContain( - result.GeneratedSources.Values, - s => s.Contains("typeof(global::TestNamespace.Handler)") + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); + Verify(diagnostic.GetMessage().Contains("no public constructor")); + Verify( + !result.GeneratedSources.Values.Any(s => + s.Contains("typeof(global::TestNamespace.Handler)") + ) ); } @@ -260,7 +260,7 @@ public class Handler : IHandler /// The first declaration has no constructor, so its syntax alone says the compiler adds a /// public one. /// - [Fact] + [VerifyTest] public void AnInternalConstructorOnAnotherPartialDeclaration_IsReported() { var result = Run( @@ -278,11 +278,11 @@ internal Worker() { } ) ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); - Assert.Contains("'Worker'", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); + Verify(diagnostic.GetMessage().Contains("'Worker'")); } - [Fact] + [VerifyTest] public void AModuleThatGeneratesFactories_RegistersAClassWithAnInternalConstructor() { var assembly = GeneratedAssembly.Create( @@ -306,10 +306,10 @@ public void Conventions(IConventionDefinitions conventions) """ ); - Assert.Equal("Handler", assembly.ResolveRequired("IHandler").GetType().Name); + Verify(assembly.ResolveRequired("IHandler").GetType().Name == "Handler"); } - [Fact] + [VerifyTest] public void AModuleThatGeneratesFactories_StillReportsAPrivateConstructor() { var result = Run( @@ -332,7 +332,7 @@ public void Conventions(IConventionDefinitions conventions) """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); - Assert.Contains("no public or internal constructor", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0006"); + Verify(diagnostic.GetMessage().Contains("no public or internal constructor")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs index 988af8c..9518a26 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratedCodeRobustnessTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Generated code lands in someone else's project, so it must not depend on how that project is /// configured. The harness compiles without implicit usings and without any project-level using /// directives, which is the strictest environment a consumer can present. /// -public class GeneratedCodeRobustnessTests +public partial class GeneratedCodeRobustnessTests { /// /// Regression test: the generated module attribute used to be emitted as a bare @@ -17,7 +16,7 @@ public class GeneratedCodeRobustnessTests /// project happened to have ImplicitUsings enabled. Projects with ImplicitUsings disabled /// failed with CS0246/CS0103 on every generated module. /// - [Fact] + [VerifyTest] public void GeneratedCode_CompilesWithoutImplicitUsings() { var result = GeneratorTestHarness.Run( @@ -37,7 +36,7 @@ public partial class TestModule; result.AssertNoErrors(); } - [Fact] + [VerifyTest] public void GeneratedModuleAttribute_UsesFullyQualifiedAttributeUsage() { var result = GeneratorTestHarness.Run( @@ -54,14 +53,14 @@ public partial class TestModule; result.AssertNoErrors(); var generated = result.SourceContaining(".Module.g.cs"); - Assert.Contains("global::System.AttributeUsage", generated); - Assert.DoesNotContain("[AttributeUsage(", generated); + Verify(generated.Contains("global::System.AttributeUsage")); + Verify(!generated.Contains("[AttributeUsage(")); } /// /// A consumer that treats warnings as errors should not be broken by generated code. /// - [Fact] + [VerifyTest] public void GeneratedCode_ProducesNoWarnings() { var result = GeneratorTestHarness.Run( @@ -98,7 +97,7 @@ public partial class TestModule; ) .ToArray(); - Assert.True( + Verify( warnings.Length == 0, "Generated code produced warnings:" + Environment.NewLine @@ -120,9 +119,9 @@ public partial class TestModule; /// GeneratedCode_ProducesNoWarnings above covers the same ground but registers a service whose /// type arguments carry no annotation, which is why it stayed green throughout. /// - [Theory] - [InlineData("attribute", "[SingletonService]")] - [InlineData("convention", "")] + [VerifyTest] + [Row("attribute", "[SingletonService]")] + [Row("convention", "")] public void GeneratedCode_ProducesNoWarnings_ForANullableTypeArgument( string _, string attribute @@ -180,7 +179,7 @@ private static void AssertNoWarningsFromGeneratedCode(GeneratorResult result) ) .ToArray(); - Assert.True( + Verify( warnings.Length == 0, "Generated code produced warnings:" + Environment.NewLine @@ -191,7 +190,7 @@ private static void AssertNoWarningsFromGeneratedCode(GeneratorResult result) ); } - [Fact] + [VerifyTest] public void GeneratedCode_QualifiesReferencesToTheRuntime() { var result = GeneratorTestHarness.Run( @@ -212,13 +211,14 @@ public partial class TestModule; result.AssertNoErrors(); - Assert.Contains( - "global::DependencyModules.Runtime.Helpers.DependencyRegistry", - result.SourceContaining(".Module.g.cs") + Verify( + result + .SourceContaining(".Module.g.cs") + .Contains("global::DependencyModules.Runtime.Helpers.DependencyRegistry") ); } - [Fact] + [VerifyTest] public void GeneratorRun_ReportsNoDiagnosticsForValidInput() { var result = GeneratorTestHarness.Run( @@ -237,6 +237,6 @@ public partial class TestModule; """ ); - Assert.Empty(result.GeneratorDiagnostics); + Verify(result.GeneratorDiagnostics.Length == 0); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs index ef77ab1..ce0986d 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratedMemberAttributeTests.cs @@ -3,15 +3,14 @@ using System.Reflection; using DependencyModules.Runtime.Interfaces; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The attributes that the generator puts on the code it writes. A module is a partial class, so /// an attribute on a generated part of the class applies to the members the developer writes too. /// -public class GeneratedMemberAttributeTests +public partial class GeneratedMemberAttributeTests { private const BindingFlags Declared = BindingFlags.DeclaredOnly @@ -61,16 +60,16 @@ public void ConfigureServices(IServiceCollection services) { } /// Coverage tools skip a whole type that has [ExcludeFromCodeCoverage], so the attribute /// on the module class hid ConfigureServices. /// - [Fact] + [VerifyTest] public void TheMembersTheDeveloperWrites_AreMeasured() { var module = GeneratedAssembly.Create(Source).Type("TestModule"); - Assert.False(Excluded(module)); - Assert.False(Excluded(module.GetMethod("ConfigureServices")!)); + Verify(!Excluded(module)); + Verify(!Excluded(module.GetMethod("ConfigureServices")!)); } - [Fact] + [VerifyTest] public void TheGeneratedMembersOfTheModule_AreExcluded() { var assembly = GeneratedAssembly.Create(Source); @@ -84,20 +83,21 @@ public void TheGeneratedMembersOfTheModule_AreExcluded() .Append(assembly.Type("TestModuleAttribute").GetMethod("GetModule")!) .ToArray(); - Assert.Contains(generated, member => member.Name.EndsWith("InternalGetModules")); - Assert.All( - generated, - member => Assert.True(Excluded(member), $"{member.Name} is measured") - ); + Verify(generated.Any(member => member.Name.EndsWith("InternalGetModules"))); + + foreach (var member in generated) + { + Verify(Excluded(member), $"{member.Name} is measured"); + } } - [Fact] + [VerifyTest] public void TheInterceptorWrapper_IsExcluded() { - Assert.True(Excluded(GeneratedAssembly.Create(Source).Type("Greeter_Intercepted"))); + Verify(Excluded(GeneratedAssembly.Create(Source).Type("Greeter_Intercepted"))); } - [Fact] + [VerifyTest] public void WithExcludeGeneratedCodeFromCoverageFalse_NothingIsExcluded() { var assembly = GeneratedAssembly.Create( @@ -112,11 +112,12 @@ public void WithExcludeGeneratedCodeFromCoverageFalse_NothingIsExcluded() { var type = assembly.Type(name); - Assert.False(Excluded(type), $"{name} is excluded"); - Assert.All( - type.GetMembers(Declared), - member => Assert.False(Excluded(member), $"{name}.{member.Name} is excluded") - ); + Verify(!Excluded(type), $"{name} is excluded"); + + foreach (var member in type.GetMembers(Declared)) + { + Verify(!Excluded(member), $"{name}.{member.Name} is excluded"); + } } } @@ -125,7 +126,7 @@ public void WithExcludeGeneratedCodeFromCoverageFalse_NothingIsExcluded() /// [EditorBrowsable(EditorBrowsableState.Never)]. [Browsable(false)] is for the /// Properties window of a designer. /// - [Fact] + [VerifyTest] public void TheInternalMembersOfIDependencyModule_AreHiddenFromIntelliSense() { var members = typeof(IDependencyModule) @@ -133,11 +134,15 @@ public void TheInternalMembersOfIDependencyModule_AreHiddenFromIntelliSense() .Where(method => method.Name.StartsWith("Internal")) .ToArray(); - Assert.Equal(6, members.Length); - Assert.All(members, member => Assert.True(Hidden(member), $"{member.Name} is shown")); + Verify(members.Length == 6); + + foreach (var member in members) + { + Verify(Hidden(member), $"{member.Name} is shown"); + } } - [Fact] + [VerifyTest] public void TheGeneratedInternalMembers_AreHiddenFromIntelliSense() { var members = GeneratedAssembly @@ -147,8 +152,12 @@ public void TheGeneratedInternalMembers_AreHiddenFromIntelliSense() .Where(method => method.Name.Contains(".Internal")) .ToArray(); - Assert.NotEmpty(members); - Assert.All(members, member => Assert.True(Hidden(member), $"{member.Name} is shown")); + Verify(members.Length != 0); + + foreach (var member in members) + { + Verify(Hidden(member), $"{member.Name} is shown"); + } } private static bool Excluded(MemberInfo member) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs index 73c3c61..70ab17b 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFailureTests.cs @@ -4,16 +4,15 @@ using DependencyModules.SourceGenerator.Impl.Utilities; using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// An exception inside the generator is reported as DM0001. An exception that escapes an output /// gives CS8785, which is only a warning, and Roslyn then drops every file the generator wrote in /// that run. /// -public class GeneratorFailureTests : IDisposable +public partial class GeneratorFailureTests : IDisposable { private readonly string _logFolder = Path.Combine( Path.GetTempPath(), @@ -21,7 +20,7 @@ public class GeneratorFailureTests : IDisposable Guid.NewGuid().ToString("n") ); - [Fact] + [VerifyTest] public void AModuleThatCannotBeWritten_IsReported_AndTheOtherModulesAreWritten() { var result = GeneratorTestHarness.Run( @@ -29,18 +28,18 @@ public void AModuleThatCannotBeWritten_IsReported_AndTheOtherModulesAreWritten() generators: new[] { new ModuleWriterGenerator(_logFolder).AsSourceGenerator() } ); - Assert.Empty(result.GeneratorExceptions); + Verify(result.GeneratorExceptions.Count == 0); - var failure = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0001"); - Assert.Contains("hintName", failure.GetMessage()); + var failure = Single(result.GeneratorDiagnostics, d => d.Id == "DM0001"); + Verify(failure.GetMessage().Contains("hintName")); - Assert.Contains("GoodModule.Module.g.cs", result.GeneratedSources.Keys); + Verify(result.GeneratedSources.ContainsKey("GoodModule.Module.g.cs")); var log = Directory.GetFiles(_logFolder, "DependencyModuleWriter.*.txt"); - Assert.Contains(log, file => File.ReadAllText(file).Contains("Bad\"Module")); + Verify(log.Any(file => File.ReadAllText(file).Contains("Bad\"Module"))); } - [Fact] + [VerifyTest] public void AnOutputThatOnlyReports_IsReported_AndTheGeneratedFilesAreKept() { var result = GeneratorTestHarness.Run( @@ -48,12 +47,13 @@ public void AnOutputThatOnlyReports_IsReported_AndTheGeneratedFilesAreKept() generators: new[] { new ThrowingReportGenerator().AsSourceGenerator() } ); - Assert.Empty(result.GeneratorExceptions); - Assert.Contains( - result.GeneratorDiagnostics, - d => d.Id == "DM0001" && d.GetMessage().Contains("the report failed") + Verify(result.GeneratorExceptions.Count == 0); + Verify( + result.GeneratorDiagnostics.Any(d => + d.Id == "DM0001" && d.GetMessage().Contains("the report failed") + ) ); - Assert.Contains("Kept.g.cs", result.GeneratedSources.Keys); + Verify(result.GeneratedSources.ContainsKey("Kept.g.cs")); } /// @@ -61,7 +61,7 @@ public void AnOutputThatOnlyReports_IsReported_AndTheGeneratedFilesAreKept() /// configuration and the services are in the log of the code output, and no other log replaces /// it. /// - [Fact] + [VerifyTest] public void TheServiceLogKeepsTheConfigurationAndTheServices() { GeneratorTestHarness.Run( @@ -86,7 +86,7 @@ public partial class ShopModule; var log = File.ReadAllText( Path.Combine( _logFolder, - Assert.Single( + Single( names, name => name!.StartsWith("ServiceSourceGenerator.") @@ -95,9 +95,9 @@ public partial class ShopModule; ) ); - Assert.Contains("Configuration:", log); - Assert.Contains("Clock -> IClock", log); - Assert.Single(names, name => name!.StartsWith("ServiceSourceGenerator.Diagnostics.")); + Verify(log.Contains("Configuration:")); + Verify(log.Contains("Clock -> IClock")); + Single(names, name => name!.StartsWith("ServiceSourceGenerator.Diagnostics.")); } /// diff --git a/tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs index 3d3eab9..79b1065 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GeneratorFeatureTests.cs @@ -1,16 +1,15 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Covers the documented module features end to end: realms, use methods, decorators, feature /// handlers, factories, and module composition. Each asserts that the generator produces output /// that compiles, which is the property most easily broken by a change to the writers. /// -public class GeneratorFeatureTests +public partial class GeneratorFeatureTests { - [Fact] + [VerifyTest] public void OnlyRealm_RegistersOnlyServicesMarkedForThatRealm() { var result = GeneratorTestHarness.Run( @@ -36,11 +35,11 @@ public class OutsideRealm : IOutsideRealm; result.AssertNoErrors(); var generated = result.SourceContaining("Dependencies"); - Assert.Contains("InRealm", generated); - Assert.DoesNotContain("OutsideRealm", generated); + Verify(generated.Contains("InRealm")); + Verify(!generated.Contains("OutsideRealm")); } - [Fact] + [VerifyTest] public void ModuleWithoutOnlyRealm_RegistersUnmarkedServices() { var result = GeneratorTestHarness.Run( @@ -60,10 +59,10 @@ public partial class OpenModule; ); result.AssertNoErrors(); - Assert.Contains("Thing", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("Thing")); } - [Fact] + [VerifyTest] public void GenerateUseMethod_EmitsTheNamedMethod() { var result = GeneratorTestHarness.Run( @@ -83,10 +82,10 @@ public class RealmService; ); result.AssertNoErrors(); - Assert.Contains("UseTestModule", result.SourceContaining(".Module.g.cs")); + Verify(result.SourceContaining(".Module.g.cs").Contains("UseTestModule")); } - [Fact] + [VerifyTest] public void GenerateAttributeFalse_SuppressesTheModuleAttribute() { var result = GeneratorTestHarness.Run( @@ -106,13 +105,12 @@ public partial class NoAttributeModule; ); result.AssertNoErrors(); - Assert.DoesNotContain( - "class NoAttributeModuleAttribute", - result.SourceContaining(".Module.g.cs") + Verify( + !result.SourceContaining(".Module.g.cs").Contains("class NoAttributeModuleAttribute") ); } - [Fact] + [VerifyTest] public void ModuleImplementingAFeature_EmitsAFeatureApplicator() { var result = GeneratorTestHarness.Run( @@ -139,11 +137,11 @@ public void HandleFeature(IServiceCollection collection, IEnumerable /// Auto-registration picks the first implemented interface. Registering every interface is /// what [CrossWireService] is for, and [SingletonService(As = ...)] selects a specific one. /// - [Fact] + [VerifyTest] public void ServiceImplementingSeveralInterfaces_RegistersTheFirstOne() { var result = GeneratorTestHarness.Run( @@ -336,11 +334,11 @@ public partial class TestModule; result.AssertNoErrors(); var generated = result.SourceContaining("Dependencies"); - Assert.Contains("IFirst", generated); - Assert.DoesNotContain("ISecond", generated); + Verify(generated.Contains("IFirst")); + Verify(!generated.Contains("ISecond")); } - [Fact] + [VerifyTest] public void CrossWireService_RegistersTheImplementationAndItsInterfaces() { var result = GeneratorTestHarness.Run( @@ -363,12 +361,12 @@ public partial class TestModule; result.AssertNoErrors(); var generated = result.SourceContaining("Dependencies"); - Assert.Contains("Both", generated); - Assert.Contains("IFirst", generated); - Assert.Contains("ISecond", generated); + Verify(generated.Contains("Both")); + Verify(generated.Contains("IFirst")); + Verify(generated.Contains("ISecond")); } - [Fact] + [VerifyTest] public void ModuleLevelRegistrationType_AppliesToItsServices() { var result = GeneratorTestHarness.Run( @@ -388,10 +386,10 @@ public partial class TryModule; ); result.AssertNoErrors(); - Assert.Contains("TryAdd", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("TryAdd")); } - [Fact] + [VerifyTest] public void SeveralModulesInOneCompilation_EachGetTheirOwnFiles() { var result = GeneratorTestHarness.Run( @@ -415,11 +413,11 @@ public partial class SecondModule; result.AssertNoErrors(); - Assert.Contains(result.GeneratedSources.Keys, key => key.StartsWith("FirstModule.")); - Assert.Contains(result.GeneratedSources.Keys, key => key.StartsWith("SecondModule.")); + Verify(result.GeneratedSources.Keys.Any(key => key.StartsWith("FirstModule."))); + Verify(result.GeneratedSources.Keys.Any(key => key.StartsWith("SecondModule."))); } - [Fact] + [VerifyTest] public void ModuleInANestedNamespace_GeneratesIntoThatNamespace() { var result = GeneratorTestHarness.Run( @@ -439,10 +437,10 @@ public partial class NestedModule; ); result.AssertNoErrors(); - Assert.Contains("namespace Outer.Inner", result.SourceContaining(".Module.g.cs")); + Verify(result.SourceContaining(".Module.g.cs").Contains("namespace Outer.Inner")); } - [Fact] + [VerifyTest] public void ServiceWithNoInterfaces_RegistersItselfAsTheServiceType() { var result = GeneratorTestHarness.Run( @@ -460,10 +458,10 @@ public partial class TestModule; ); result.AssertNoErrors(); - Assert.Contains("Standalone", result.SourceContaining("Dependencies")); + Verify(result.SourceContaining("Dependencies").Contains("Standalone")); } - [Fact] + [VerifyTest] public void ModuleThatOverridesEquals_KeepsTheDeveloperImplementation() { var result = GeneratorTestHarness.Run( @@ -489,13 +487,10 @@ public partial class CustomEqualsModule(string key) { ); result.AssertNoErrors(); - Assert.DoesNotContain( - "public override bool Equals", - result.SourceContaining(".Module.g.cs") - ); + Verify(!result.SourceContaining(".Module.g.cs").Contains("public override bool Equals")); } - [Fact] + [VerifyTest] public void ScopedAndTransientFactories_AreSupported() { var result = GeneratorTestHarness.Run( @@ -523,7 +518,7 @@ public partial class TestModule; result.AssertNoErrors(); var generated = result.SourceContaining("Dependencies"); - Assert.Contains("AddScoped", generated); - Assert.Contains("AddTransient", generated); + Verify(generated.Contains("AddScoped")); + Verify(generated.Contains("AddTransient")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs index c5b22ec..4123ace 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GlueCollectionTests.cs @@ -3,16 +3,15 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The Into* attributes. These tests build the generated code and read the collections /// from a service provider, because the order, the keys and the time an item is built are all /// decided when the modules load or later. /// -public class GlueCollectionTests +public partial class GlueCollectionTests { private const string Preamble = """ using System; @@ -94,7 +93,7 @@ private static dynamic Probe( string name ) => ActivatorUtilities.CreateInstance(provider, assembly.Type(name)); - [Fact] + [VerifyTest] public void AMap_GivesTheItemOfAKey_AndBuildsOnlyThatItem() { var assembly = Compile( @@ -116,22 +115,27 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); var probe = Probe(assembly, provider, "MapProbe"); - Assert.Equal(0, Built(assembly)); - Assert.Equal("tools/call,tools/list", (string)probe.Keys); - Assert.Equal(2, (int)probe.Count); - Assert.Equal(0, Built(assembly)); + Verify(Built(assembly) == 0); + Verify((string)probe.Keys == "tools/call,tools/list"); + Verify((int)probe.Count == 2); + Verify(Built(assembly) == 0); dynamic handler = probe.Get("tools/call"); - Assert.Equal("CallHandler", (string)handler.Name); - Assert.Equal(1, Built(assembly)); + Verify((string)handler.Name == "CallHandler"); + Verify(Built(assembly) == 1); // The item is kept, and its constructor parameter came from the service provider. - Assert.Same((object)handler, (object)probe.Get("tools/call")); - Assert.Equal(1, Built(assembly)); - Assert.Same(provider.GetRequiredService(assembly.Type("IClock")), (object)handler.Clock); + Verify(ReferenceEquals((object)handler, (object)probe.Get("tools/call"))); + Verify(Built(assembly) == 1); + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("IClock")), + (object)handler.Clock + ) + ); } - [Fact] + [VerifyTest] public void TheItemsOfACollection_AreNotServices() { var assembly = Compile( @@ -148,14 +152,14 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); - Assert.Empty(provider.GetServices(assembly.Type("Handler"))); - Assert.Null(provider.GetService(assembly.Type("OnlyHandler"))); - Assert.Equal("OnlyHandler", (string)Probe(assembly, provider, "ListProbe").Names); - Assert.Equal("OnlyHandler", (string)Probe(assembly, provider, "SetProbe").Names); - Assert.Equal("a", (string)Probe(assembly, provider, "MapProbe").Keys); + Verify(!provider.GetServices(assembly.Type("Handler")).Any()); + Verify(provider.GetService(assembly.Type("OnlyHandler")) is null); + Verify((string)Probe(assembly, provider, "ListProbe").Names == "OnlyHandler"); + Verify((string)Probe(assembly, provider, "SetProbe").Names == "OnlyHandler"); + Verify((string)Probe(assembly, provider, "MapProbe").Keys == "a"); } - [Fact] + [VerifyTest] public void AMap_HasEnumAndNumberKeys() { var assembly = Compile( @@ -189,13 +193,13 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); var probe = Probe(assembly, provider, "StageProbe"); - Assert.Equal("Auth,Routing", (string)probe.Stages); - Assert.Equal("RoutingHandler", (string)probe.Routing); - Assert.Equal("RoutingHandler", (string)probe.Seven); - Assert.False((bool)probe.HasEight); + Verify((string)probe.Stages == "Auth,Routing"); + Verify((string)probe.Routing == "RoutingHandler"); + Verify((string)probe.Seven == "RoutingHandler"); + Verify(!(bool)probe.HasEight); } - [Fact] + [VerifyTest] public void ASet_HasOneInstanceOfEachItem() { var assembly = Compile( @@ -214,13 +218,13 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); var probe = Probe(assembly, provider, "SetProbe"); - Assert.Equal(0, Built(assembly)); - Assert.Equal("FirstHandler,SecondHandler", (string)probe.Names); - Assert.Equal(2, (int)probe.Count); - Assert.Equal(2, Built(assembly)); + Verify(Built(assembly) == 0); + Verify((string)probe.Names == "FirstHandler,SecondHandler"); + Verify((int)probe.Count == 2); + Verify(Built(assembly) == 2); } - [Fact] + [VerifyTest] public void AListWithTypeOrder_PutsAnItemAfterTheTypesItDependsOn() { var assembly = Compile( @@ -245,16 +249,16 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); var probe = Probe(assembly, provider, "ListProbe"); - Assert.Equal(0, Built(assembly)); - Assert.Equal(4, (int)probe.Count); - Assert.Equal(0, Built(assembly)); + Verify(Built(assembly) == 0); + Verify((int)probe.Count == 4); + Verify(Built(assembly) == 0); // AuthHandler and ZHandler have no order between them, so their names give it. AHandler // is last because it is after RoutingHandler. - Assert.Equal("AuthHandler,RoutingHandler,AHandler,ZHandler", (string)probe.Names); + Verify((string)probe.Names == "AuthHandler,RoutingHandler,AHandler,ZHandler"); } - [Fact] + [VerifyTest] public void AListWithTypeOrder_PutsAnItemAfterEachItemOfABaseType() { var assembly = Compile( @@ -277,13 +281,13 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); - Assert.Equal( - "CorsHandler,TokenHandler,AHandler", + Verify( (string)Probe(assembly, provider, "ListProbe").Names + == "CorsHandler,TokenHandler,AHandler" ); } - [Fact] + [VerifyTest] public void AListWithOrderValues_SortsByValue_AndEqualValuesAreOneLevel() { var assembly = Compile( @@ -307,13 +311,13 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); - Assert.Equal( - "MHandler,BHandler,ZHandler,AHandler", + Verify( (string)Probe(assembly, provider, "ListProbe").Names + == "MHandler,BHandler,ZHandler,AHandler" ); } - [Fact] + [VerifyTest] public void AListWithOrderValues_PutsAnItemAfterTheValuesItDependsOn() { var assembly = Compile( @@ -339,13 +343,13 @@ public partial class TestModule; // "auth" sorts first by value, but it is after the two "routing" items. A value with no // item has no effect. - Assert.Equal( - "CorsHandler,OtherRoutingHandler,RoutingHandler,AuthHandler", + Verify( (string)Probe(assembly, provider, "ListProbe").Names + == "CorsHandler,OtherRoutingHandler,RoutingHandler,AuthHandler" ); } - [Fact] + [VerifyTest] public void AListWithEnumOrderValues_SortsByTheEnumValue() { var assembly = Compile( @@ -366,16 +370,15 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); - Assert.Equal( - "CHandler,BHandler,AHandler", - (string)Probe(assembly, provider, "ListProbe").Names + Verify( + (string)Probe(assembly, provider, "ListProbe").Names == "CHandler,BHandler,AHandler" ); } - [Fact] + [VerifyTest] public void AListWithAnOrderCycle_FailsTheLoad_AndNamesTheItems() { - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => Compile( """ [IntoList(typeof(SecondHandler))] @@ -393,15 +396,14 @@ public partial class TestModule; ) ); - Assert.Contains("order cycle", exception.Message); - Assert.Contains( - "TestNamespace.FirstHandler, TestNamespace.SecondHandler", - exception.Message + Verify(exception.Message.Contains("order cycle")); + Verify( + exception.Message.Contains("TestNamespace.FirstHandler, TestNamespace.SecondHandler") ); - Assert.DoesNotContain("ThirdHandler", exception.Message); + Verify(!exception.Message.Contains("ThirdHandler")); } - [Fact] + [VerifyTest] public void AnItem_IsBuiltOneTimeForEachCollectionInstance_AndDisposedWithItsScope() { var assembly = Compile( @@ -441,13 +443,13 @@ public partial class TestModule; { var list = Probe(assembly, scope.ServiceProvider, "ListProbe"); - Assert.Same((object)list.Get(0), (object)list.Get(0)); - Assert.Equal("DisposableHandler", (string)list.Get(1).Name); - Assert.Equal(2, Built(assembly)); - Assert.Empty(disposed); + Verify(ReferenceEquals((object)list.Get(0), (object)list.Get(0))); + Verify((string)list.Get(1).Name == "DisposableHandler"); + Verify(Built(assembly) == 2); + Verify(disposed.Count == 0); } - Assert.Equal(new[] { "DisposableHandler", "AsyncHandler" }, disposed); + Verify(disposed.SequenceEqual(new[] { "DisposableHandler", "AsyncHandler" })); // A second scope gets a new collection with new items. using (var scope = provider.CreateScope()) @@ -455,10 +457,10 @@ public partial class TestModule; _ = Probe(assembly, scope.ServiceProvider, "ListProbe").Get(0); } - Assert.Equal(3, Built(assembly)); + Verify(Built(assembly) == 3); } - [Fact] + [VerifyTest] public void AnItemWithARealm_IsOnlyInTheCollectionOfThatModule() { var assembly = Compile( @@ -479,7 +481,7 @@ public partial class OtherModule; using (var provider = assembly.BuildProvider()) { - Assert.Equal("SharedHandler", (string)Probe(assembly, provider, "ListProbe").Names); + Verify((string)Probe(assembly, provider, "ListProbe").Names == "SharedHandler"); } // A second load on the same service collection adds to the same list. @@ -489,14 +491,13 @@ public partial class OtherModule; using (var provider = assembly.BuildProvider()) { - Assert.Equal( - "OtherHandler,SharedHandler", - (string)Probe(assembly, provider, "ListProbe").Names + Verify( + (string)Probe(assembly, provider, "ListProbe").Names == "OtherHandler,SharedHandler" ); } } - [Fact] + [VerifyTest] public void TwoModulesOfOneProject_AddAnItemOneTime() { var assembly = Compile( @@ -517,12 +518,12 @@ public partial class SecondModule; using var provider = assembly.BuildProvider(); - Assert.Equal("OnlyHandler", (string)Probe(assembly, provider, "ListProbe").Names); - Assert.Equal("OnlyHandler", (string)Probe(assembly, provider, "SetProbe").Names); - Assert.Equal("only", (string)Probe(assembly, provider, "MapProbe").Keys); + Verify((string)Probe(assembly, provider, "ListProbe").Names == "OnlyHandler"); + Verify((string)Probe(assembly, provider, "SetProbe").Names == "OnlyHandler"); + Verify((string)Probe(assembly, provider, "MapProbe").Keys == "only"); } - [Fact] + [VerifyTest] public void AnItemWithAnEnvironmentCondition_IsInTheCollectionOnlyInThatEnvironment() { const string source = """ @@ -543,17 +544,14 @@ public partial class TestModule; using var productionProvider = production.BuildProvider(); using var developmentProvider = development.BuildProvider(); - Assert.Equal( - "AlwaysHandler", - (string)Probe(production, productionProvider, "ListProbe").Names - ); - Assert.Equal( - "AlwaysHandler,DevelopmentHandler", + Verify((string)Probe(production, productionProvider, "ListProbe").Names == "AlwaysHandler"); + Verify( (string)Probe(development, developmentProvider, "ListProbe").Names + == "AlwaysHandler,DevelopmentHandler" ); } - [Fact] + [VerifyTest] public void ACollectionThatAModuleRegisters_IsKept() { var assembly = Compile( @@ -576,8 +574,8 @@ public void ConfigureServices(IServiceCollection services) using var provider = assembly.BuildProvider(); - Assert.Equal("ManualHandler", (string)Probe(assembly, provider, "ListProbe").Names); - Assert.Single( + Verify((string)Probe(assembly, provider, "ListProbe").Names == "ManualHandler"); + Single( assembly.Services, descriptor => descriptor.ServiceType @@ -585,7 +583,7 @@ public void ConfigureServices(IServiceCollection services) ); } - [Fact] + [VerifyTest] public void TwoModulesWithOneKey_FailTheLoad_AndNameTheClasses() { var assembly = Compile( @@ -604,18 +602,18 @@ public partial class OtherModule; """ ); - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => assembly.Services.AddModule( (IDependencyModule)Activator.CreateInstance(assembly.Type("OtherModule"))! ) ); - Assert.Contains("'same'", exception.Message); - Assert.Contains("TestNamespace.FirstHandler", exception.Message); - Assert.Contains("TestNamespace.SecondHandler", exception.Message); + Verify(exception.Message.Contains("'same'")); + Verify(exception.Message.Contains("TestNamespace.FirstHandler")); + Verify(exception.Message.Contains("TestNamespace.SecondHandler")); } - [Fact] + [VerifyTest] public void TwoClassesOfOneModuleWithOneKey_AreDM0028() { var result = Run( @@ -634,14 +632,14 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0028"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0028"); - Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); - Assert.Contains("'FirstHandler' and 'SecondHandler'", diagnostic.GetMessage()); - Assert.Contains("\"same\"", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Error); + Verify(diagnostic.GetMessage().Contains("'FirstHandler' and 'SecondHandler'")); + Verify(diagnostic.GetMessage().Contains("\"same\"")); } - [Fact] + [VerifyTest] public void AListWithTwoOrderSchemes_IsDM0029() { var result = Run( @@ -657,25 +655,25 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0029"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0029"); - Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); - Assert.Contains("IntoList", diagnostic.GetMessage()); - Assert.Contains("IntoList", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Error); + Verify(diagnostic.GetMessage().Contains("IntoList")); + Verify(diagnostic.GetMessage().Contains("IntoList")); } - [Theory] - [InlineData("public abstract class BadHandler : Handler { }", "it is abstract")] - [InlineData("public class BadHandler { }", "it is not assignable to 'TestNamespace.Handler'")] - [InlineData( + [VerifyTest] + [Row("public abstract class BadHandler : Handler { }", "it is abstract")] + [Row("public class BadHandler { }", "it is not assignable to 'TestNamespace.Handler'")] + [Row( "public class BadHandler : Handler { private BadHandler() { } }", "it has no constructor that the generated module can call" )] - [InlineData( + [Row( "public class BadHandler(int retries) : Handler { }", "its constructor parameter 'retries' has the type 'int'" )] - [InlineData("public class BadHandler : Handler { }", "it is an open generic class")] + [Row("public class BadHandler : Handler { }", "it is an open generic class")] public void AClassThatCannotBeAnItem_IsDM0027_AndTheOtherItemsStay( string declaration, string reason @@ -697,19 +695,19 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0027"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0027"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("the list of TestNamespace.Handler", diagnostic.GetMessage()); - Assert.Contains(reason, diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("the list of TestNamespace.Handler")); + Verify(diagnostic.GetMessage().Contains(reason)); var assembly = Compile(source); using var provider = assembly.BuildProvider(); - Assert.Equal("GoodHandler", (string)Probe(assembly, provider, "ListProbe").Names); + Verify((string)Probe(assembly, provider, "ListProbe").Names == "GoodHandler"); } - [Fact] + [VerifyTest] public void AMap_GivesItsValuesAndPairs_AndHasNoItemForAMissingKey() { var assembly = Compile( @@ -740,17 +738,20 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); var probe = Probe(assembly, provider, "FullMapProbe"); - Assert.Equal("AHandler,BHandler", (string)probe.Values); - Assert.Equal("a=AHandler,b=BHandler", (string)probe.Pairs); - Assert.False((bool)probe.HasMissing); - Assert.Equal(2, Built(assembly)); + Verify((string)probe.Values == "AHandler,BHandler"); + Verify((string)probe.Pairs == "a=AHandler,b=BHandler"); + Verify(!(bool)probe.HasMissing); + Verify(Built(assembly) == 2); - var exception = Assert.Throws(() => (object)probe.Missing); + var exception = ThrowsExactly(() => + { + _ = (object)probe.Missing; + }); - Assert.Contains("'missing'", exception.Message); + Verify(exception.Message.Contains("'missing'")); } - [Fact] + [VerifyTest] public void ASet_AnswersTheSetQuestions() { var assembly = Compile( @@ -788,10 +789,10 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); - Assert.True((bool)Probe(assembly, provider, "FullSetProbe").Answers()); + Verify((bool)Probe(assembly, provider, "FullSetProbe").Answers()); } - [Fact] + [VerifyTest] public async Task AnAsyncScope_DisposesTheItemsOfItsCollections() { var assembly = Compile( @@ -832,14 +833,16 @@ public partial class TestModule; await using (var scope = provider.CreateAsyncScope()) { - Assert.Equal(2, (int)Probe(assembly, scope.ServiceProvider, "BothProbe").Read()); - Assert.Empty(disposed); + Verify((int)Probe(assembly, scope.ServiceProvider, "BothProbe").Read() == 2); + Verify(disposed.Count == 0); } - Assert.Equal(new[] { "AsyncHandler", "SyncHandler" }, disposed.OrderBy(name => name)); + Verify( + disposed.OrderBy(name => name).SequenceEqual(new[] { "AsyncHandler", "SyncHandler" }) + ); } - [Fact] + [VerifyTest] public void TwoModulesWithTwoOrderSchemes_FailTheLoad_AndNameTheClass() { var assembly = Compile( @@ -858,24 +861,25 @@ public partial class OtherModule; """ ); - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => assembly.Services.AddModule( (IDependencyModule)Activator.CreateInstance(assembly.Type("OtherModule"))! ) ); - Assert.Contains( - "System.Collections.Generic.IReadOnlyList", - exception.Message + Verify( + exception.Message.Contains( + "System.Collections.Generic.IReadOnlyList" + ) ); - Assert.Contains("TestNamespace.SecondHandler uses IntoList", exception.Message); - Assert.Contains("IntoList", exception.Message); + Verify(exception.Message.Contains("TestNamespace.SecondHandler uses IntoList")); + Verify(exception.Message.Contains("IntoList")); } - [Fact] + [VerifyTest] public void AListWithOrderValuesAndACycle_FailsTheLoad() { - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => Compile( """ [IntoList("a", "b")] @@ -890,10 +894,10 @@ public partial class TestModule; ) ); - Assert.Contains("order cycle", exception.Message); + Verify(exception.Message.Contains("order cycle")); } - [Fact] + [VerifyTest] public void AModuleWithNoItems_GetsNoGlueFile() { var result = Run( @@ -903,10 +907,10 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratedSources.Keys, name => name.Contains("Glue")); + Verify(!result.GeneratedSources.Keys.Any(name => name.Contains("Glue"))); } - [Fact] + [VerifyTest] public void ARecordModule_CompilesWithItems() { var assembly = Compile( @@ -921,6 +925,6 @@ public partial record TestModule; using var provider = assembly.BuildProvider(); - Assert.Equal("OnlyHandler", (string)Probe(assembly, provider, "SetProbe").Names); + Verify((string)Probe(assembly, provider, "SetProbe").Names == "OnlyHandler"); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs b/tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs index 575715d..dea2cb3 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/GlueFuncTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The registrations that the generator writes for Func constructor parameters, and the /// rules that give a constructor parameter of an object that the generated code builds. /// -public class GlueFuncTests +public partial class GlueFuncTests { private const string Preamble = """ using System; @@ -39,7 +38,7 @@ private static GeneratorResult Run(string source) => private static string Glue(GeneratorResult result) => result.SourceContaining("Glue"); - [Fact] + [VerifyTest] public void AFuncWithACallerArgument_BuildsTheClass_FromTheArgumentAndTheProvider() { var assembly = Compile( @@ -68,16 +67,21 @@ public partial class TestModule; dynamic first = checkout.Create(7); dynamic second = checkout.Create(8); - Assert.Equal(7, (int)first.Id.Value); - Assert.Equal(8, (int)second.Id.Value); - Assert.NotSame((object)first, (object)second); - Assert.Same(provider.GetRequiredService(assembly.Type("IClock")), (object)first.Clock); + Verify((int)first.Id.Value == 7); + Verify((int)second.Id.Value == 8); + Verify(!ReferenceEquals((object)first, (object)second)); + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("IClock")), + (object)first.Clock + ) + ); // The class that the delegate builds has no registration. - Assert.Null(provider.GetService(assembly.Type("OrderProcessor"))); + Verify(provider.GetService(assembly.Type("OrderProcessor")) is null); } - [Fact] + [VerifyTest] public void AFuncWithTwoCallerArguments_MatchesThemByType_InAnyOrder() { var assembly = Compile( @@ -101,10 +105,10 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); dynamic printer = provider.GetRequiredService(assembly.Type("Printer")); - Assert.Equal("sales:3:True", (string)printer.Print()); + Verify((string)printer.Print() == "sales:3:True"); } - [Fact] + [VerifyTest] public void AFuncWithCallerArguments_UsesTheConstructorThatTakesThem() { var assembly = Compile( @@ -138,10 +142,10 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); dynamic printer = provider.GetRequiredService(assembly.Type("Printer")); - Assert.Equal("sales", (string)printer.Print()); + Verify((string)printer.Print() == "sales"); } - [Fact] + [VerifyTest] public void AFuncWithNoArguments_OverAnInterface_GetsTheServiceFromTheProvider() { var assembly = Compile( @@ -160,10 +164,15 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Same(provider.GetRequiredService(assembly.Type("IClock")), (object)consumer.Clock); + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("IClock")), + (object)consumer.Clock + ) + ); } - [Fact] + [VerifyTest] public void AFuncWithNoArguments_OverAConcreteClass_BuildsANewInstanceForEachCall() { var assembly = Compile( @@ -189,11 +198,16 @@ public partial class TestModule; dynamic first = consumer.Create(); - Assert.NotSame((object)first, (object)consumer.Create()); - Assert.Same(provider.GetRequiredService(assembly.Type("IClock")), (object)first.Clock); + Verify(!ReferenceEquals((object)first, (object)consumer.Create())); + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("IClock")), + (object)first.Clock + ) + ); } - [Fact] + [VerifyTest] public void AConcreteClassThatTheApplicationRegisters_ComesFromTheProvider() { var assembly = Compile( @@ -225,8 +239,8 @@ public partial class TestModule; { dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Equal("new", (string)consumer.WorkerName); - Assert.Equal("new", (string)consumer.SettingsName); + Verify((string)consumer.WorkerName == "new"); + Verify((string)consumer.SettingsName == "new"); } // Added after the modules loaded, as code after AddModule in Program.cs does. @@ -238,12 +252,12 @@ public partial class TestModule; { dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Equal("registered", (string)consumer.WorkerName); - Assert.Equal("registered", (string)consumer.SettingsName); + Verify((string)consumer.WorkerName == "registered"); + Verify((string)consumer.SettingsName == "registered"); } } - [Fact] + [VerifyTest] public void AClassWithAServiceAttribute_IsNotBuiltWithNew() { var result = Run( @@ -267,12 +281,12 @@ public partial class TestModule; var glue = Glue(result); - Assert.DoesNotContain("new global::TestNamespace.Store", glue); - Assert.Contains("provider.GetRequiredService()", glue); - Assert.Contains("provider.GetRequiredService()", glue); + Verify(!glue.Contains("new global::TestNamespace.Store")); + Verify(glue.Contains("provider.GetRequiredService()")); + Verify(glue.Contains("provider.GetRequiredService()")); } - [Fact] + [VerifyTest] public void AFrameworkClassAndAClassWithAValueParameter_ComeFromTheProvider() { var result = Run( @@ -293,14 +307,14 @@ public partial class TestModule; var glue = Glue(result); - Assert.Contains("provider.GetRequiredService()", glue); - Assert.Contains("provider.GetRequiredService()", glue); - Assert.Contains("provider.GetService()", glue); - Assert.DoesNotContain("new global::System.Text.StringBuilder", glue); - Assert.DoesNotContain("new global::TestNamespace.Rates", glue); + Verify(glue.Contains("provider.GetRequiredService()")); + Verify(glue.Contains("provider.GetRequiredService()")); + Verify(glue.Contains("provider.GetService()")); + Verify(!glue.Contains("new global::System.Text.StringBuilder")); + Verify(!glue.Contains("new global::TestNamespace.Rates")); } - [Fact] + [VerifyTest] public void AKeyedParameterAndTheProvider_AreGivenToAnObjectThatTheGlueBuilds() { var assembly = Compile( @@ -330,14 +344,16 @@ public partial class TestModule; dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); dynamic worker = consumer.Create(); - Assert.Same( - provider.GetRequiredKeyedService(assembly.Type("IClock"), "utc"), - (object)worker.Clock + Verify( + ReferenceEquals( + provider.GetRequiredKeyedService(assembly.Type("IClock"), "utc"), + (object)worker.Clock + ) ); - Assert.NotNull((object)worker.Provider); + Verify((object)worker.Provider is not null); } - [Fact] + [VerifyTest] public void FromConstructor_BuildsTheParameter_AlsoWhenTheProviderHasARegistration() { var assembly = Compile( @@ -370,12 +386,12 @@ public partial class TestModule; dynamic worker = consumer.Create(); var registered = provider.GetRequiredService(assembly.Type("Store")); - Assert.Same(registered, (object)worker.Resolved); - Assert.NotSame(registered, (object)worker.Built); - Assert.NotNull((object)worker.Built); + Verify(ReferenceEquals(registered, (object)worker.Resolved)); + Verify(!ReferenceEquals(registered, (object)worker.Built)); + Verify((object)worker.Built is not null); } - [Fact] + [VerifyTest] public void FromServiceProvider_GetsTheParameterFromTheProvider_AndNotFromNewOrACaller() { var result = Run( @@ -398,19 +414,21 @@ public partial class TestModule; ); result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id is "DM0030" or "DM0031"); - - Assert.Contains( - "(arg0) => new global::TestNamespace.Worker(" - + "provider.GetRequiredService(), " - + "(provider.GetService() ?? new global::TestNamespace.Helper()), " - + "provider.GetRequiredService(), " - + "arg0)", + Verify(!result.GeneratorDiagnostics.Any(d => d.Id is "DM0030" or "DM0031")); + + Verify( Glue(result) + .Contains( + "(arg0) => new global::TestNamespace.Worker(" + + "provider.GetRequiredService(), " + + "(provider.GetService() ?? new global::TestNamespace.Helper()), " + + "provider.GetRequiredService(), " + + "arg0)" + ) ); } - [Fact] + [VerifyTest] public void FromServiceProvider_OnAStringParameter_LetsTheGlueBuildTheClass() { var assembly = Compile( @@ -440,14 +458,14 @@ public void ConfigureServices(IServiceCollection services) using var provider = assembly.BuildProvider(); dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Equal("registered", (string)consumer.Name); + Verify((string)consumer.Name == "registered"); } - [Theory] - [InlineData("IClock", "it is not a class")] - [InlineData("string", "it is not a class")] - [InlineData("AbstractHelper", "it is abstract")] - [InlineData("PrivateHelper", "it has no constructor that the generated module can call")] + [VerifyTest] + [Row("IClock", "it is not a class")] + [Row("string", "it is not a class")] + [Row("AbstractHelper", "it is abstract")] + [Row("PrivateHelper", "it has no constructor that the generated module can call")] public void FromConstructor_OnAParameterThatCannotBeBuilt_IsDM0031( string parameterType, string reason @@ -476,18 +494,19 @@ public partial class TestModule; result.AssertNoErrors(); // The set item and the Func build the same class. The parameter is reported one time. - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0031"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0031"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains( - "The parameter 'helper' of 'Worker' has [FromConstructor]", - diagnostic.GetMessage() + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify( + diagnostic + .GetMessage() + .Contains("The parameter 'helper' of 'Worker' has [FromConstructor]") ); - Assert.Contains(reason, diagnostic.GetMessage()); - Assert.Contains("provider.GetRequiredService<", Glue(result)); + Verify(diagnostic.GetMessage().Contains(reason)); + Verify(Glue(result).Contains("provider.GetRequiredService<")); } - [Fact] + [VerifyTest] public void AFuncThatTheApplicationRegisters_IsKept() { var assembly = Compile( @@ -517,8 +536,8 @@ public void ConfigureServices(IServiceCollection services) using var provider = assembly.BuildProvider(); dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Equal("manual x", (string)consumer.Name); - Assert.Single( + Verify((string)consumer.Name == "manual x"); + Single( assembly.Services, descriptor => descriptor.ServiceType @@ -526,7 +545,7 @@ public void ConfigureServices(IServiceCollection services) ); } - [Fact] + [VerifyTest] public void AFuncParameterOfACollectionItem_AndOfAnObjectThatTheGlueBuilds_IsRegistered() { var assembly = Compile( @@ -562,14 +581,16 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); dynamic forest = ActivatorUtilities.CreateInstance(provider, assembly.Type("Forest")); - Assert.Equal(4, (int)forest.Tree.Depth); - Assert.Same( - provider.GetRequiredService(assembly.Type("IClock")), - (object)forest.Tree.Clock + Verify((int)forest.Tree.Depth == 4); + Verify( + ReferenceEquals( + provider.GetRequiredService(assembly.Type("IClock")), + (object)forest.Tree.Clock + ) ); } - [Fact] + [VerifyTest] public void AFuncParameterOfAFactoryMethod_IsRegistered() { var assembly = Compile( @@ -599,17 +620,17 @@ public partial class TestModule; using var provider = assembly.BuildProvider(); dynamic consumer = provider.GetRequiredService(assembly.Type("Consumer")); - Assert.Equal("made", (string)consumer.Name); + Verify((string)consumer.Name == "made"); } - [Theory] - [InlineData("Func")] - [InlineData("Func")] - [InlineData("Func")] - [InlineData("Func")] - [InlineData("Func")] - [InlineData("Func")] - [InlineData("Action")] + [VerifyTest] + [Row("Func")] + [Row("Func")] + [Row("Func")] + [Row("Func")] + [Row("Func")] + [Row("Func")] + [Row("Action")] public void ADelegateThatIsNotARequestForAService_GetsNoRegistration(string parameterType) { var result = Run( @@ -624,17 +645,17 @@ public partial class TestModule; result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratedSources.Keys, name => name.Contains("Glue")); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0030"); + Verify(!result.GeneratedSources.Keys.Any(name => name.Contains("Glue"))); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0030")); } - [Theory] - [InlineData( + [VerifyTest] + [Row( "Func", "its constructor has no parameter of the type 'int' for the caller argument" )] - [InlineData("Func", "two caller arguments have the type 'string'")] - [InlineData("Func", "its constructor parameter 'name' has the type 'string'")] + [Row("Func", "two caller arguments have the type 'string'")] + [Row("Func", "its constructor parameter 'name' has the type 'string'")] public void AFuncWhoseArgumentsDoNotMatchTheConstructor_IsDM0030( string parameterType, string reason @@ -654,15 +675,15 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0030"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0030"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("'Consumer' takes a", diagnostic.GetMessage()); - Assert.Contains(reason, diagnostic.GetMessage()); - Assert.DoesNotContain(result.GeneratedSources.Keys, name => name.Contains("Glue")); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("'Consumer' takes a")); + Verify(diagnostic.GetMessage().Contains(reason)); + Verify(!result.GeneratedSources.Keys.Any(name => name.Contains("Glue"))); } - [Fact] + [VerifyTest] public void AFuncOfAServiceWithARealm_IsRegisteredByTheModuleOfThatRealm() { var result = Run( @@ -682,12 +703,12 @@ public partial class OtherModule; result.AssertNoErrors(); - var glueFile = Assert.Single(result.GeneratedSources.Keys, name => name.Contains("Glue")); + var glueFile = Single(result.GeneratedSources.Keys, name => name.Contains("Glue")); - Assert.Contains("OtherModule", glueFile); + Verify(glueFile.Contains("OtherModule")); } - [Fact] + [VerifyTest] public void ObjectsThatNeedEachOther_DoNotStopTheGenerator() { var result = Run( @@ -707,10 +728,10 @@ public partial class TestModule; result.AssertNoErrors(); // The second use of First comes from the provider, which gives the error for the cycle. - Assert.Contains("provider.GetRequiredService()", Glue(result)); + Verify(Glue(result).Contains("provider.GetRequiredService()")); } - [Fact] + [VerifyTest] public void TheGlueFile_IsTheSameForTheSameSource() { const string source = """ @@ -736,7 +757,7 @@ public partial class TestModule; var result = Run(source); result.AssertNoErrors(); - Assert.Equal(Glue(result), Glue(Run(source))); + Verify(Glue(result) == Glue(Run(source))); Snapshot.Match(Glue(result)); } diff --git a/tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs b/tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs index 53dc1ee..9a9ccc8 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/IgnoredDecoratorTests.cs @@ -1,13 +1,12 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// A [Decorator] that the generator cannot apply is reported as DM0025, and one that gets its /// service type through a base class or a derived interface is applied. /// -public class IgnoredDecoratorTests +public partial class IgnoredDecoratorTests { private const string Preamble = """ using DependencyModules.Runtime.Attributes; @@ -40,11 +39,11 @@ private static string Now(GeneratedAssembly assembly) return (string)clock.GetType().GetMethod("Now")!.Invoke(clock, null)!; } - [Theory] - [InlineData("protected")] - [InlineData("private")] - [InlineData("private protected")] - [InlineData("")] + [VerifyTest] + [Row("protected")] + [Row("private")] + [Row("private protected")] + [Row("")] public void ADecoratorThatGeneratedCodeCannotConstruct_IsReported(string access) { var result = Run( @@ -63,18 +62,19 @@ public class LoggingClock : IClock result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); - Assert.Contains("'LoggingClock'", diagnostic.GetMessage()); - Assert.Contains("no constructor that generated code can call", diagnostic.GetMessage()); - Assert.DoesNotContain( - result.GeneratedSources.Values, - s => s.Contains("new global::TestNamespace.LoggingClock") + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); + Verify(diagnostic.GetMessage().Contains("'LoggingClock'")); + Verify(diagnostic.GetMessage().Contains("no constructor that generated code can call")); + Verify( + !result.GeneratedSources.Values.Any(s => + s.Contains("new global::TestNamespace.LoggingClock") + ) ); } - [Theory] - [InlineData("internal")] - [InlineData("protected internal")] + [VerifyTest] + [Row("internal")] + [Row("protected internal")] public void ADecoratorWithAnInternalConstructor_IsApplied(string access) { var assembly = GeneratedAssembly.Create( @@ -92,10 +92,10 @@ public class LoggingClock : IClock """ ); - Assert.Equal("logged(now)", Now(assembly)); + Verify(Now(assembly) == "logged(now)"); } - [Fact] + [VerifyTest] public void ADecoratorThatGetsItsServiceFromABaseClass_IsApplied() { var assembly = GeneratedAssembly.Create( @@ -114,10 +114,10 @@ public class LoudClock(IClock inner) : ClockBase """ ); - Assert.Equal("NOW", Now(assembly)); + Verify(Now(assembly) == "NOW"); } - [Fact] + [VerifyTest] public void ADecoratorThatGetsItsServiceFromADerivedInterface_IsApplied() { var assembly = GeneratedAssembly.Create( @@ -133,10 +133,10 @@ public class LoggingClock(IClock inner) : ITimedClock """ ); - Assert.Equal("logged(now)", Now(assembly)); + Verify(Now(assembly) == "logged(now)"); } - [Fact] + [VerifyTest] public void ADecoratorWithNoService_IsReported() { var result = Run( @@ -151,12 +151,12 @@ public class Stopwatch(IClock clock) result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); - Assert.Contains("'Stopwatch'", diagnostic.GetMessage()); - Assert.Contains("no service to decorate", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); + Verify(diagnostic.GetMessage().Contains("'Stopwatch'")); + Verify(diagnostic.GetMessage().Contains("no service to decorate")); } - [Fact] + [VerifyTest] public void ADecoratorWhoseConstructorDoesNotTakeItsService_IsReported() { var result = Run( @@ -176,12 +176,12 @@ public class TimerClock(ITimer timer) : IClock result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); - Assert.Contains("'TimerClock'", diagnostic.GetMessage()); - Assert.Contains("'IClock'", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); + Verify(diagnostic.GetMessage().Contains("'TimerClock'")); + Verify(diagnostic.GetMessage().Contains("'IClock'")); } - [Fact] + [VerifyTest] public void AGenericDecoratorWithReorderedTypeParameters_IsReported() { var result = GeneratorTestHarness.Run( @@ -214,12 +214,12 @@ public partial class TestModule; result.AssertNoErrors(); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); - Assert.Contains("'Swapped'", diagnostic.GetMessage()); - Assert.Contains("type parameters", diagnostic.GetMessage()); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0025"); + Verify(diagnostic.GetMessage().Contains("'Swapped'")); + Verify(diagnostic.GetMessage().Contains("type parameters")); } - [Fact] + [VerifyTest] public void ADecoratorThatCanBeApplied_IsNotReported() { var result = Run( @@ -233,6 +233,6 @@ public class LoggingClock(IClock inner) : IClock ); result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0025"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0025")); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs index 3f14578..6ee3991 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/IncrementalGenerationTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The generator is an IIncrementalGenerator, so its model comparers decide how much work the @@ -9,21 +8,21 @@ namespace DependencyModules.Tests.GeneratorTests; /// and a real change serves stale output. These tests pin that behaviour from the outside, which /// is more durable than asserting on the comparers directly. /// -public class IncrementalGenerationTests +public partial class IncrementalGenerationTests { - [Fact] + [VerifyTest] public void RerunningOnUnchangedSource_ReusesCachedOutput() { var result = GeneratorTestHarness.RunIncremental(Sources(Service), Sources(Service)); - Assert.True( + Verify( result.AllOutputsCached, "Re-running on identical source recomputed output: " + string.Join(", ", result.OutputReasons) ); } - [Fact] + [VerifyTest] public void EditingAnUnrelatedMethodBody_ReusesCachedOutput() { var before = Sources( @@ -48,15 +47,19 @@ public class Unrelated { var result = GeneratorTestHarness.RunIncremental(before, after); - Assert.Equal(result.FirstRun.Keys.OrderBy(k => k), result.SecondRun.Keys.OrderBy(k => k)); - Assert.True( + Verify( + result + .SecondRun.Keys.OrderBy(k => k) + .SequenceEqual(result.FirstRun.Keys.OrderBy(k => k)) + ); + Verify( result.AllOutputsCached, "Editing an unrelated method body regenerated output: " + string.Join(", ", result.OutputReasons) ); } - [Fact] + [VerifyTest] public void AddingAComment_ReusesCachedOutput() { var result = GeneratorTestHarness.RunIncremental( @@ -64,13 +67,13 @@ public void AddingAComment_ReusesCachedOutput() Sources("// a new comment\n" + Service) ); - Assert.True( + Verify( result.AllOutputsCached, "Adding a comment regenerated output: " + string.Join(", ", result.OutputReasons) ); } - [Fact] + [VerifyTest] public void AddingAService_RegeneratesAndIncludesIt() { var after = Sources( @@ -88,14 +91,15 @@ public class SecondThing : ISecond; var dependencies = result.SecondRun.Single(pair => pair.Key.Contains("Dependencies")).Value; - Assert.Contains("SecondThing", dependencies); - Assert.DoesNotContain( - "SecondThing", - result.FirstRun.Single(pair => pair.Key.Contains("Dependencies")).Value + Verify(dependencies.Contains("SecondThing")); + Verify( + !result + .FirstRun.Single(pair => pair.Key.Contains("Dependencies")) + .Value.Contains("SecondThing") ); } - [Fact] + [VerifyTest] public void ChangingAServiceLifetime_RegeneratesWithTheNewLifetime() { var before = Sources("[SingletonService]\npublic class Thing : IThing;"); @@ -106,12 +110,12 @@ public void ChangingAServiceLifetime_RegeneratesWithTheNewLifetime() var first = result.FirstRun.Single(pair => pair.Key.Contains("Dependencies")).Value; var second = result.SecondRun.Single(pair => pair.Key.Contains("Dependencies")).Value; - Assert.Contains("AddSingleton", first); - Assert.Contains("AddScoped", second); - Assert.DoesNotContain("AddSingleton", second); + Verify(first.Contains("AddSingleton")); + Verify(second.Contains("AddScoped")); + Verify(!second.Contains("AddSingleton")); } - [Fact] + [VerifyTest] public void RemovingAService_RegeneratesWithoutIt() { var before = Sources( @@ -129,7 +133,7 @@ public class SecondThing : ISecond; var second = result.SecondRun.Single(pair => pair.Key.Contains("Dependencies")).Value; - Assert.DoesNotContain("SecondThing", second); + Verify(!second.Contains("SecondThing")); } private const string Service = """ diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs index 8511511..355996a 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptAttributeSpellingTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Every legal way of writing [Intercept] has to mean [Intercept]. @@ -17,41 +16,37 @@ namespace DependencyModules.Tests.GeneratorTests; /// Interceptors are audit, authorisation, retry and metrics, which is the worst set of things to /// silently not run. /// -public class InterceptAttributeSpellingTests +public partial class InterceptAttributeSpellingTests { - [Theory] - [InlineData("[Intercept(typeof(LoggingInterceptor))]")] - [InlineData("[InterceptAttribute(typeof(LoggingInterceptor))]")] - [InlineData("[DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]")] - [InlineData( - "[DependencyModules.Runtime.Attributes.InterceptAttribute(typeof(LoggingInterceptor))]" - )] - [InlineData( - "[global::DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]" - )] - [InlineData( + [VerifyTest] + [Row("[Intercept(typeof(LoggingInterceptor))]")] + [Row("[InterceptAttribute(typeof(LoggingInterceptor))]")] + [Row("[DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]")] + [Row("[DependencyModules.Runtime.Attributes.InterceptAttribute(typeof(LoggingInterceptor))]")] + [Row("[global::DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]")] + [Row( "[global::DependencyModules.Runtime.Attributes.InterceptAttribute(typeof(LoggingInterceptor))]" )] - [InlineData("[Wrap(typeof(LoggingInterceptor))]")] + [Row("[Wrap(typeof(LoggingInterceptor))]")] public void EverySpelling_GeneratesTheWrapper(string attribute) { var result = Run(attribute).AssertNoErrors(); - Assert.Contains("Thing_Intercepted", string.Join(", ", result.GeneratedSources.Keys)); + Verify(string.Join(", ", result.GeneratedSources.Keys).Contains("Thing_Intercepted")); } - [Theory] - [InlineData("[Intercept(typeof(LoggingInterceptor))]")] - [InlineData("[DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]")] - [InlineData( + [VerifyTest] + [Row("[Intercept(typeof(LoggingInterceptor))]")] + [Row("[DependencyModules.Runtime.Attributes.Intercept(typeof(LoggingInterceptor))]")] + [Row( "[global::DependencyModules.Runtime.Attributes.InterceptAttribute(typeof(LoggingInterceptor))]" )] - [InlineData("[Wrap(typeof(LoggingInterceptor))]")] + [Row("[Wrap(typeof(LoggingInterceptor))]")] public void EverySpelling_AppliesTheInterception(string attribute) { var interceptors = Run(attribute).SourceContaining("Interceptors"); - Assert.Contains("Thing_Intercepted", interceptors); + Verify(interceptors.Contains("Thing_Intercepted")); } private static GeneratorResult Run(string attribute) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs index 8bb8209..7511646 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptedMembersTests.cs @@ -1,8 +1,7 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// [Intercept].Members — which kinds of member the interceptors are placed around. @@ -17,37 +16,37 @@ namespace DependencyModules.Tests.GeneratorTests; /// just does not run through the chain, which is the same path a member no interceptor can serve /// already took. /// -public class InterceptedMembersTests +public partial class InterceptedMembersTests { - [Fact] + [VerifyTest] public void WithNoKindsNamed_EveryMemberIsIntercepted() { var calls = Run("[Intercept(typeof(CountingInterceptor))]"); - Assert.Equal(["Handle", "get_Name"], calls); + Verify(calls.SequenceEqual(["Handle", "get_Name"])); } - [Fact] + [VerifyTest] public void NamingMethods_LeavesPropertiesAlone() { var calls = Run( "[Intercept(typeof(CountingInterceptor), Members = InterceptedMembers.Methods)]" ); - Assert.Equal(["Handle"], calls); + Verify(calls.SequenceEqual(["Handle"])); } - [Fact] + [VerifyTest] public void NamingProperties_LeavesMethodsAlone() { var calls = Run( "[Intercept(typeof(CountingInterceptor), Members = InterceptedMembers.Properties)]" ); - Assert.Equal(["get_Name"], calls); + Verify(calls.SequenceEqual(["get_Name"])); } - [Fact] + [VerifyTest] public void KindsCombine() { var calls = Run( @@ -55,14 +54,14 @@ public void KindsCombine() + "Members = InterceptedMembers.Methods | InterceptedMembers.Properties)]" ); - Assert.Equal(["Handle", "get_Name"], calls); + Verify(calls.SequenceEqual(["Handle", "get_Name"])); } /// /// The excluded member still works — it is forwarded rather than dropped, and the wrapper still /// implements the interface. /// - [Fact] + [VerifyTest] public void AnExcludedMember_IsStillForwarded() { var generated = Build( @@ -71,15 +70,15 @@ public void AnExcludedMember_IsStillForwarded() var service = generated.BuildProvider().GetService(generated.Type("IHandler"))!; - Assert.Equal("Handler_Intercepted", service.GetType().Name); - Assert.Equal("named", service.GetType().GetProperty("Name")!.GetValue(service)); + Verify(service.GetType().Name == "Handler_Intercepted"); + Verify(Equals(service.GetType().GetProperty("Name")!.GetValue(service), "named")); } /// /// An interceptor that cannot serve a member's shape is DM0015. An interceptor that was never /// asked to cover it is not — reporting that would report the feature. /// - [Fact] + [VerifyTest] public void AnExcludedMember_IsNotReportedAsUnserved() { var result = GeneratorTestHarness.Run( @@ -89,7 +88,7 @@ public void AnExcludedMember_IsNotReportedAsUnserved() ) ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0015"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0015")); } private static string[] Run(string attribute) diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs index 9877bd3..2a55c09 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptionRealmTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Where an interception's applicator is emitted, when realms are in play. @@ -18,7 +17,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// with a realm-scoped service; agent 08 reached it by accident through a convention, because /// convention registrations are always stamped with their declaring module's realm. /// -public class InterceptionRealmTests +public partial class InterceptionRealmTests { private const string Preamble = """ using DependencyModules.Runtime.Attributes; @@ -39,7 +38,7 @@ public sealed class CountingInterceptor : IInterceptor { /// The service names a realm; the interception does not. The applicator has to follow the /// registration, because a per-implementation interception is about that one registration. /// - [Fact] + [VerifyTest] public void ARealmScopedService_WithAnUnrealmedInterception_IsInterceptedInThatRealm() { var result = Run( @@ -57,14 +56,14 @@ public partial class TestModule; ) .AssertNoErrors(); - Assert.Contains("Greeter_Intercepted", result.SourceContaining("RealmModule.Interceptors")); + Verify(result.SourceContaining("RealmModule.Interceptors").Contains("Greeter_Intercepted")); } /// /// And nowhere else. A module that does not register the implementation has nothing to apply the /// wrapper to, so an applicator there is dead weight at best. /// - [Fact] + [VerifyTest] public void ARealmScopedService_IsNotInterceptedOutsideItsRealm() { var result = Run( @@ -82,17 +81,14 @@ public partial class TestModule; ) .AssertNoErrors(); - Assert.DoesNotContain( - "Greeter_Intercepted", - result.SourceContaining("TestModule.Interceptors") - ); + Verify(!result.SourceContaining("TestModule.Interceptors").Contains("Greeter_Intercepted")); } /// /// An explicit [Intercept(Realm = ...)] still wins outright. It is the escape hatch the /// changelog documents, and following the registration must not take it away. /// - [Fact] + [VerifyTest] public void AnExplicitInterceptRealm_StillDecides() { var result = Run( @@ -110,18 +106,15 @@ public partial class TestModule; ) .AssertNoErrors(); - Assert.Contains("Greeter_Intercepted", result.SourceContaining("RealmModule.Interceptors")); - Assert.DoesNotContain( - "Greeter_Intercepted", - result.SourceContaining("TestModule.Interceptors") - ); + Verify(result.SourceContaining("RealmModule.Interceptors").Contains("Greeter_Intercepted")); + Verify(!result.SourceContaining("TestModule.Interceptors").Contains("Greeter_Intercepted")); } /// /// The ordinary case, unchanged: nothing names a realm, so the interception belongs to every /// module that is not realm-only. /// - [Fact] + [VerifyTest] public void AnUnrealmedService_WithAnUnrealmedInterception_IsInterceptedNormally() { var result = Run( @@ -136,7 +129,7 @@ public partial class TestModule; ) .AssertNoErrors(); - Assert.Contains("Greeter_Intercepted", result.SourceContaining("TestModule.Interceptors")); + Verify(result.SourceContaining("TestModule.Interceptors").Contains("Greeter_Intercepted")); } /// @@ -155,7 +148,7 @@ public partial class TestModule; /// interceptor needing a dependency the isolated container lacks threw while building the /// provider. /// - [Fact] + [VerifyTest] public void AConventionRegisteredClass_InAnOnlyRealmModule_ReportsDM0020() { var result = Run( @@ -172,17 +165,17 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0020"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0020"); - Assert.Contains("Greeter", diagnostic.GetMessage()); - Assert.Contains("Realm", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("Greeter")); + Verify(diagnostic.GetMessage().Contains("Realm")); } /// /// An interception a module does apply is not reported. The diagnostic is about a wrapper that /// can never run, not about every realm arrangement that looks unusual. /// - [Fact] + [VerifyTest] public void AnInterceptionSomeModuleApplies_IsNotReported() { var result = Run( @@ -196,14 +189,14 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0020"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0020")); } /// /// Nor is the realm-scoped case that now works: the interception follows the registration, so a /// module applies it and there is nothing to report. /// - [Fact] + [VerifyTest] public void ARealmScopedServiceFollowingItsRegistration_IsNotReported() { var result = Run( @@ -220,14 +213,14 @@ public partial class TestModule; """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0020"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0020")); } /// /// The shape that happened to work, kept as a control: one convention module, not realm-only, /// so the unrealmed interception landed on it by luck rather than by rule. /// - [Fact] + [VerifyTest] public void AConventionRegisteredClass_InAPlainModule_IsStillIntercepted() { var result = Run( @@ -245,9 +238,8 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ) .AssertNoErrors(); - Assert.Contains( - "Greeter_Intercepted", - result.SourceContaining("ConventionModule.Interceptors") + Verify( + result.SourceContaining("ConventionModule.Interceptors").Contains("Greeter_Intercepted") ); } @@ -257,7 +249,7 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { /// telling the two apart matters: this one is about which service type was registered, not /// about which module the applicator landed on. /// - [Fact] + [VerifyTest] public void AConventionRegisteringAsSelf_StillInterceptsTheInterface() { var result = Run( @@ -275,9 +267,8 @@ void IConventionModule.Conventions(IConventionDefinitions conventions) { ) .AssertNoErrors(); - Assert.Contains( - "Greeter_Intercepted", - result.SourceContaining("ConventionModule.Interceptors") + Verify( + result.SourceContaining("ConventionModule.Interceptors").Contains("Greeter_Intercepted") ); } diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs index a716328..fab6d2d 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptionScopeTests.cs @@ -2,9 +2,8 @@ using DependencyModules.Runtime; using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// An interceptor's wrapper is generated from one class and forwards that class's members, so it @@ -16,7 +15,7 @@ namespace DependencyModules.Tests.GeneratorTests; /// [Intercept] coming back wrapped in another class's wrapper, and, with two implementations /// marked, every interceptor running twice per call. Neither threw. /// -public class InterceptionScopeTests +public partial class InterceptionScopeTests { private const string Interceptor = """ public sealed class CountingInterceptor : IInterceptor { @@ -28,7 +27,7 @@ public TResult Intercept(InvocationContext context) { } """; - [Fact] + [VerifyTest] public void AnUnmarkedSiblingImplementation_IsNotWrapped() { var generated = GeneratedAssembly.Create( @@ -58,10 +57,10 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } .OrderBy(n => n) .ToArray(); - Assert.Equal(new[] { "Loud_Intercepted", "Quiet" }, resolved); + Verify(resolved.SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } - [Fact] + [VerifyTest] public void TwoMarkedImplementations_EachGetTheirOwnWrapper() { var generated = GeneratedAssembly.Create( @@ -92,7 +91,7 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } .ToArray(); // Each behind its own wrapper, rather than both behind whichever was emitted last. - Assert.Equal(new[] { "Loud_Intercepted", "Quiet_Intercepted" }, resolved); + Verify(resolved.SequenceEqual(new[] { "Loud_Intercepted", "Quiet_Intercepted" })); } /// @@ -101,7 +100,7 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } /// its own registration anyway, or narrowing the rewrite would silently stop intercepting a /// service that had asked for it. /// - [Fact] + [VerifyTest] public void AnInterceptorOrderedOutsideADecorator_StillApplies() { var generated = GeneratedAssembly.Create( @@ -120,19 +119,19 @@ public sealed class Bracketed(IGreeter inner) : IGreeter { var resolved = generated.ResolveRequired("IGreeter"); - Assert.Equal("Core_Intercepted", resolved.GetType().Name); + Verify(resolved.GetType().Name == "Core_Intercepted"); // The decorator is still inside the interception wrapper, so both ran. var greet = (string)resolved.GetType().GetMethod("Greet")!.Invoke(resolved, null)!; - Assert.Equal("[core]", greet); + Verify(greet == "[core]"); } /// /// The repro from issue #80. A registration made from a factory or an instance of another class /// is not the one the wrapper was generated from. /// - [Fact] + [VerifyTest] public void AFactoryOrAnInstanceOfAnotherClass_IsNotWrapped() { var generated = GeneratedAssembly.Create( @@ -152,7 +151,7 @@ public sealed class Plain : IGreeter { public string Greet() => "plain"; } ) ); - Assert.Equal(new[] { "Loud_Intercepted", "Plain", "Quiet" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud_Intercepted", "Plain", "Quiet" })); } /// @@ -160,14 +159,14 @@ public sealed class Plain : IGreeter { public string Greet() => "plain"; } /// as its implementation. A cross-wired interface is a factory that resolves the class, so /// that factory is typed to return the class. /// - [Theory] - [InlineData("[SingletonService]")] - [InlineData("[SingletonService(Using = RegistrationType.Try)]")] - [InlineData("[SingletonService(Using = RegistrationType.Replace)]")] - [InlineData("[SingletonService(Using = RegistrationType.TryEnumerable)]")] - [InlineData("[SingletonService] [IfEnvironment(\"Development\")]")] - [InlineData("[CrossWireService]")] - [InlineData("[CrossWireService(Using = RegistrationType.TryEnumerable)]")] + [VerifyTest] + [Row("[SingletonService]")] + [Row("[SingletonService(Using = RegistrationType.Try)]")] + [Row("[SingletonService(Using = RegistrationType.Replace)]")] + [Row("[SingletonService(Using = RegistrationType.TryEnumerable)]")] + [Row("[SingletonService] [IfEnvironment(\"Development\")]")] + [Row("[CrossWireService]")] + [Row("[CrossWireService(Using = RegistrationType.TryEnumerable)]")] public void OnlyTheRegistrationOfTheInterceptedClass_IsWrapped(string registration) { var generated = GeneratedAssembly.Create( @@ -183,10 +182,10 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } environment: new ModuleEnvironment("Development") ); - Assert.Equal(new[] { "Loud_Intercepted", "Quiet" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } - [Fact] + [VerifyTest] public void OnlyTheKeyedRegistrationOfTheInterceptedClass_IsWrapped() { var generated = GeneratedAssembly.Create( @@ -201,10 +200,10 @@ public sealed class Quiet : IGreeter { public string Greet() => "quiet"; } ) ); - Assert.Equal(new[] { "Loud_Intercepted", "Quiet" }, Greeters(generated, "k")); + Verify(Greeters(generated, "k").SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } - [Fact] + [VerifyTest] public void AConventionThatCrossWiresTheInterceptedClass_StillWrapsIt() { var generated = GeneratedAssembly.Create( @@ -239,13 +238,13 @@ public void ConfigureServices(IServiceCollection services) { """ ); - Assert.Equal(new[] { "Loud_Intercepted", "Quiet" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } /// /// The registration of a factory method is typed to the class the method returns. /// - [Fact] + [VerifyTest] public void AFactoryMethodThatReturnsTheInterceptedClass_IsWrapped() { var generated = GeneratedAssembly.Create( @@ -268,13 +267,13 @@ public static class Factories { ) ); - Assert.Equal(new[] { "Loud_Intercepted", "Quiet" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud_Intercepted", "Quiet" })); } /// /// The container reads an instance's own type as its implementation, and so does interception. /// - [Fact] + [VerifyTest] public void AnInstanceOfTheInterceptedClass_IsWrapped() { var generated = GeneratedAssembly.Create( @@ -287,14 +286,14 @@ public sealed class Loud : IGreeter { public string Greet() => "loud"; } ) ); - Assert.Equal(new[] { "Loud_Intercepted", "Loud_Intercepted" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud_Intercepted", "Loud_Intercepted" })); } /// /// A factory typed to return the service names no implementation, so it is not wrapped even when /// it builds the intercepted class. The container cannot tell what it builds either. /// - [Fact] + [VerifyTest] public void AFactoryThatReturnsTheService_IsNotWrapped() { var generated = GeneratedAssembly.Create( @@ -307,7 +306,7 @@ public sealed class Loud : IGreeter { public string Greet() => "loud"; } ) ); - Assert.Equal(new[] { "Loud", "Loud_Intercepted" }, Greeters(generated)); + Verify(Greeters(generated).SequenceEqual(new[] { "Loud", "Loud_Intercepted" })); } /// diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs index ee3a595..cb93a2d 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptorGenerationTests.cs @@ -1,16 +1,15 @@ using DependencyModules.Tests.Infrastructure; using Microsoft.CodeAnalysis; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Interception verified by compiling, loading and calling the generated wrapper, since the point is /// what an interceptor observes and can change rather than what the emitted text looks like. /// -public class InterceptorGenerationTests +public partial class InterceptorGenerationTests { - [Fact] + [VerifyTest] public void InterceptedService_ResolvesAsTheGeneratedWrapper() { var generated = GeneratedAssembly.Create( @@ -19,10 +18,10 @@ public void InterceptedService_ResolvesAsTheGeneratedWrapper() var resolved = generated.ResolveRequired("IWork"); - Assert.EndsWith("_Intercepted", resolved.GetType().Name); + Verify(resolved.GetType().Name.EndsWith("_Intercepted")); } - [Fact] + [VerifyTest] public void SyncMethod_ReturnsTheInnerValueThroughThePipeline() { var generated = GeneratedAssembly.Create( @@ -31,18 +30,18 @@ public void SyncMethod_ReturnsTheInnerValueThroughThePipeline() var work = generated.ResolveRequired("IWork"); - Assert.Equal(10, Invoke(work, "Sync", 5)); - Assert.Equal(["enter Sync", "exit Sync"], Log(generated)); + Verify(Equals(Invoke(work, "Sync", 5), 10)); + Verify(Log(generated).SequenceEqual(["enter Sync", "exit Sync"])); } - [Fact] + [VerifyTest] public void VoidMethod_RunsThroughThePipeline() { var generated = GeneratedAssembly.Create(Source("void Run();", "public void Run() { }")); Invoke(generated.ResolveRequired("IWork"), "Run"); - Assert.Equal(["enter Run", "exit Run"], Log(generated)); + Verify(Log(generated).SequenceEqual(["enter Run", "exit Run"])); } /// @@ -51,7 +50,7 @@ public void VoidMethod_RunsThroughThePipeline() /// An interceptor awaits inside its own method body, so what follows the await runs when the /// call has actually finished. /// - [Fact] + [VerifyTest] public async Task AsyncMethod_ExitsAfterTheWorkCompletes() { var generated = GeneratedAssembly.Create( @@ -64,17 +63,17 @@ public async Task AsyncMethod_ExitsAfterTheWorkCompletes() var task = (Task)Invoke(generated.ResolveRequired("IWork"), "Compute", 21)!; // The work is suspended at a gate nothing has released, so this cannot have happened yet. - Assert.DoesNotContain("exit Compute", Log(generated)); + Verify(!Log(generated).Contains("exit Compute")); Gate(generated).SetResult(); var result = await task; - Assert.Equal(42, result); - Assert.Equal(["enter Compute", "exit Compute"], Log(generated)); + Verify(result == 42); + Verify(Log(generated).SequenceEqual(["enter Compute", "exit Compute"])); } - [Fact] + [VerifyTest] public async Task AsyncVoidMethod_RunsThroughThePipeline() { var generated = GeneratedAssembly.Create( @@ -86,10 +85,10 @@ public async Task AsyncVoidMethod_RunsThroughThePipeline() await (Task)Invoke(generated.ResolveRequired("IWork"), "Run")!; - Assert.Equal(["enter Run", "exit Run"], Log(generated)); + Verify(Log(generated).SequenceEqual(["enter Run", "exit Run"])); } - [Fact] + [VerifyTest] public async Task ValueTaskMethod_ReturnsTheInnerValue() { var generated = GeneratedAssembly.Create( @@ -101,11 +100,11 @@ public async Task ValueTaskMethod_ReturnsTheInnerValue() var result = await (ValueTask)Invoke(generated.ResolveRequired("IWork"), "Fetch")!; - Assert.Equal("done", result); - Assert.Equal(["enter Fetch", "exit Fetch"], Log(generated)); + Verify(result == "done"); + Verify(Log(generated).SequenceEqual(["enter Fetch", "exit Fetch"])); } - [Fact] + [VerifyTest] public async Task ValueTaskWithNoResult_RunsThroughThePipeline() { var generated = GeneratedAssembly.Create( @@ -117,7 +116,7 @@ public async Task ValueTaskWithNoResult_RunsThroughThePipeline() await (ValueTask)Invoke(generated.ResolveRequired("IWork"), "Save")!; - Assert.Equal(["enter Save", "exit Save"], Log(generated)); + Verify(Log(generated).SequenceEqual(["enter Save", "exit Save"])); } /// @@ -125,7 +124,7 @@ public async Task ValueTaskWithNoResult_RunsThroughThePipeline() /// time the construction of the iterator. The interceptor enumerates it instead, and sees each /// item as it is produced. /// - [Fact] + [VerifyTest] public async Task AsyncEnumerableMethod_ObservesEachItem() { var generated = GeneratedAssembly.Create( @@ -149,11 +148,14 @@ var item in (IAsyncEnumerable) items.Add(item); } - Assert.Equal([0, 1, 2], items); - Assert.Equal(["enter Stream", "item 0", "item 1", "item 2", "exit Stream"], Log(generated)); + Verify(items.SequenceEqual([0, 1, 2])); + Verify( + Log(generated) + .SequenceEqual(["enter Stream", "item 0", "item 1", "item 2", "exit Stream"]) + ); } - [Fact] + [VerifyTest] public void GenericMethod_ForwardsWithItsConstraints() { var generated = GeneratedAssembly.Create( @@ -166,15 +168,15 @@ public void GenericMethod_ForwardsWithItsConstraints() var work = generated.ResolveRequired("IWork"); var method = work.GetType().GetMethod("Pick")!.MakeGenericMethod(typeof(string)); - Assert.Equal("value", method.Invoke(work, ["value"])); - Assert.Equal(["enter Pick", "exit Pick"], Log(generated)); + Verify(Equals(method.Invoke(work, ["value"]), "value")); + Verify(Log(generated).SequenceEqual(["enter Pick", "exit Pick"])); } /// /// Accessors are reported the way the CLR names them, so a getter and a setter are told apart /// and the name matches what appears in a stack trace. /// - [Fact] + [VerifyTest] public void Property_RoutesBothAccessorsAndReportsThemByTheirClrNames() { var generated = GeneratedAssembly.Create( @@ -186,14 +188,19 @@ public void Property_RoutesBothAccessorsAndReportsThemByTheirClrNames() property.SetValue(work, "assigned"); - Assert.Equal("assigned", property.GetValue(work)); - Assert.Equal( - ["enter set_Name", "exit set_Name", "enter get_Name", "exit get_Name"], + Verify(Equals(property.GetValue(work), "assigned")); + Verify( Log(generated) + .SequenceEqual([ + "enter set_Name", + "exit set_Name", + "enter get_Name", + "exit get_Name", + ]) ); } - [Fact] + [VerifyTest] public void ReadOnlyProperty_DeclaresNoSetter() { var generated = GeneratedAssembly.Create( @@ -203,16 +210,16 @@ public void ReadOnlyProperty_DeclaresNoSetter() var work = generated.ResolveRequired("IWork"); var property = work.GetType().GetProperty("Count")!; - Assert.Equal(7, property.GetValue(work)); - Assert.Null(property.SetMethod); - Assert.Equal(["enter get_Count", "exit get_Count"], Log(generated)); + Verify(Equals(property.GetValue(work), 7)); + Verify(property.SetMethod is null); + Verify(Log(generated).SequenceEqual(["enter get_Count", "exit get_Count"])); } /// /// An accessor cannot be async whatever its type, so a property of task type takes the sync path /// and hands the task itself to the interceptor. /// - [Fact] + [VerifyTest] public async Task PropertyReturningATask_TakesTheSyncPath() { var generated = GeneratedAssembly.Create( @@ -225,11 +232,11 @@ public async Task PropertyReturningATask_TakesTheSyncPath() var work = generated.ResolveRequired("IWork"); var pending = (Task)work.GetType().GetProperty("Pending")!.GetValue(work)!; - Assert.Equal(3, await pending); - Assert.Equal(["enter get_Pending", "exit get_Pending"], Log(generated)); + Verify(await pending == 3); + Verify(Log(generated).SequenceEqual(["enter get_Pending", "exit get_Pending"])); } - [Fact] + [VerifyTest] public void Indexer_ForwardsItsIndicesAndAssignedValue() { var generated = GeneratedAssembly.Create( @@ -250,22 +257,22 @@ public void Indexer_ForwardsItsIndicesAndAssignedValue() indexer.SetValue(work, 42, [2, 3]); - Assert.Equal(42, indexer.GetValue(work, [2, 3])); - Assert.Equal(-1, indexer.GetValue(work, [9, 9])); - Assert.Equal( - [ - "enter set_Item", - "exit set_Item", - "enter get_Item", - "exit get_Item", - "enter get_Item", - "exit get_Item", - ], + Verify(Equals(indexer.GetValue(work, [2, 3]), 42)); + Verify(Equals(indexer.GetValue(work, [9, 9]), -1)); + Verify( Log(generated) + .SequenceEqual([ + "enter set_Item", + "exit set_Item", + "enter get_Item", + "exit get_Item", + "enter get_Item", + "exit get_Item", + ]) ); } - [Fact] + [VerifyTest] public void IndexerSetter_ExposesItsIndicesAndValueAsArguments() { var generated = GeneratedAssembly.Create( @@ -292,10 +299,10 @@ public TResult Intercept(InvocationContext context) { work.GetType().GetProperty("Item")!.SetValue(work, 8, [1]); - Assert.Equal(["row=1", "value=8"], Log(generated)); + Verify(Log(generated).SequenceEqual(["row=1", "value=8"])); } - [Fact] + [VerifyTest] public void Event_RoutesAddAndRemove() { var generated = GeneratedAssembly.Create( @@ -312,18 +319,18 @@ public void Event_RoutesAddAndRemove() changed.AddEventHandler(work, handler); changed.RemoveEventHandler(work, handler); - Assert.Equal( - [ - "enter add_Changed", - "exit add_Changed", - "enter remove_Changed", - "exit remove_Changed", - ], + Verify( Log(generated) + .SequenceEqual([ + "enter add_Changed", + "exit add_Changed", + "enter remove_Changed", + "exit remove_Changed", + ]) ); } - [Fact] + [VerifyTest] public void ThrowingMethod_PropagatesThroughThePipeline() { var generated = GeneratedAssembly.Create( @@ -333,15 +340,15 @@ public void ThrowingMethod_PropagatesThroughThePipeline() ) ); - var exception = Assert.Throws(() => + var exception = ThrowsExactly(() => Invoke(generated.ResolveRequired("IWork"), "Run") ); - Assert.IsType(exception.InnerException); - Assert.Equal(["enter Run", "exit Run"], Log(generated)); + Verify(exception.InnerException?.GetType() == typeof(InvalidOperationException)); + Verify(Log(generated).SequenceEqual(["enter Run", "exit Run"])); } - [Fact] + [VerifyTest] public void SeveralInterceptors_NestInDeclarationOrder() { var generated = GeneratedAssembly.Create( @@ -365,13 +372,18 @@ public partial class TestModule; Invoke(generated.ResolveRequired("IWork"), "Run"); - Assert.Equal( - ["enter first Run", "enter second Run", "exit second Run", "exit first Run"], + Verify( Log(generated) + .SequenceEqual([ + "enter first Run", + "enter second Run", + "exit second Run", + "exit first Run", + ]) ); } - [Fact] + [VerifyTest] public void Caller_CarriesTheServiceTypeAndMember() { var generated = GeneratedAssembly.Create( @@ -392,14 +404,14 @@ public TResult Intercept(InvocationContext context) { Invoke(generated.ResolveRequired("IWork"), "Run"); - Assert.Equal(["IWork.Run", "IWork"], Log(generated)); + Verify(Log(generated).SequenceEqual(["IWork.Run", "IWork"])); } /// /// Arguments live as typed fields on the state, which is where the inner call reads them from, /// so writing one replaces the value the implementation receives. /// - [Fact] + [VerifyTest] public void Arguments_AreReadableByNameAndReplaceable() { var generated = GeneratedAssembly.Create( @@ -425,15 +437,15 @@ public TResult Intercept(InvocationContext context) { var result = Invoke(generated.ResolveRequired("IWork"), "Sync", 5, "text"); - Assert.Equal(99, result); - Assert.Equal(["a=5", "b=text", "inner 99 text"], Log(generated)); + Verify(Equals(result, 99)); + Verify(Log(generated).SequenceEqual(["a=5", "b=text", "inner 99 text"])); } /// /// The stage index is carried on the context rather than mutated on the state, so proceeding a /// second time re-enters the same next stage rather than walking past it. /// - [Fact] + [VerifyTest] public void ProceedingTwice_CallsTheImplementationTwice() { var generated = GeneratedAssembly.Create( @@ -453,11 +465,11 @@ public TResult Intercept(InvocationContext context) { var result = Invoke(generated.ResolveRequired("IWork"), "Sync", 5); - Assert.Equal(5, result); - Assert.Equal(["inner", "inner"], Log(generated)); + Verify(Equals(result, 5)); + Verify(Log(generated).SequenceEqual(["inner", "inner"])); } - [Fact] + [VerifyTest] public void NotProceeding_SkipsTheImplementation() { var generated = GeneratedAssembly.Create( @@ -472,8 +484,8 @@ public class TracingInterceptor : IInterceptor { ) ); - Assert.Equal(0, Invoke(generated.ResolveRequired("IWork"), "Sync", 5)); - Assert.Empty(Log(generated)); + Verify(Equals(Invoke(generated.ResolveRequired("IWork"), "Sync", 5), 0)); + Verify(Log(generated).Count == 0); } /// @@ -481,7 +493,7 @@ public class TracingInterceptor : IInterceptor { /// visible to every wrapper: two services with different interceptors each ran both. The /// wrapper holds its interceptors as typed fields now, so a wrapper can only reach its own. /// - [Fact] + [VerifyTest] public void TwoServices_DoNotCrossApplyEachOthersInterceptors() { var generated = GeneratedAssembly.Create( @@ -512,7 +524,7 @@ public partial class TestModule; Invoke(provider.GetService(generated.Type("IAlpha"))!, "Run"); - Assert.Equal(["enter alpha Run", "exit alpha Run"], Log(generated)); + Verify(Log(generated).SequenceEqual(["enter alpha Run", "exit alpha Run"])); } /// @@ -520,7 +532,7 @@ public partial class TestModule; /// is ordinary. A sync-only interceptor serves the sync members and has nothing to say about the /// rest, which are forwarded untouched rather than costing the sync members their interception. /// - [Fact] + [VerifyTest] public async Task SyncOnlyInterceptor_ServesSyncMembersAndPassesAsyncOnesThrough() { var generated = GeneratedAssembly.Create( @@ -558,17 +570,17 @@ public partial class TestModule; var work = generated.ResolveRequired("IWork"); - Assert.Equal(10, Invoke(work, "Sync", 5)); - Assert.Equal(["enter Sync", "exit Sync"], Log(generated)); + Verify(Equals(Invoke(work, "Sync", 5), 10)); + Verify(Log(generated).SequenceEqual(["enter Sync", "exit Sync"])); - Assert.Equal(15, await (Task)Invoke(work, "Async", 5)!); - Assert.Equal(["enter Sync", "exit Sync"], Log(generated)); + Verify(await (Task)Invoke(work, "Async", 5)! == 15); + Verify(Log(generated).SequenceEqual(["enter Sync", "exit Sync"])); } /// /// The mirror of the above, so neither direction is the special case. /// - [Fact] + [VerifyTest] public async Task AsyncOnlyInterceptor_ServesAsyncMembersAndPassesSyncOnesThrough() { var generated = GeneratedAssembly.Create( @@ -606,18 +618,18 @@ public partial class TestModule; var work = generated.ResolveRequired("IWork"); - Assert.Equal(10, Invoke(work, "Sync", 5)); - Assert.Empty(Log(generated)); + Verify(Equals(Invoke(work, "Sync", 5), 10)); + Verify(Log(generated).Count == 0); - Assert.Equal(15, await (Task)Invoke(work, "Async", 5)!); - Assert.Equal(["enter Async", "exit Async"], Log(generated)); + Verify(await (Task)Invoke(work, "Async", 5)! == 15); + Verify(Log(generated).SequenceEqual(["enter Async", "exit Async"])); } /// /// Each member's pipeline is only the interceptors that can serve it, so the stage a proceed /// walks to is its position in that pipeline rather than in the attribute. /// - [Fact] + [VerifyTest] public void MixedInterceptors_NestOnlyThoseThatServeTheMember() { var generated = GeneratedAssembly.Create( @@ -651,9 +663,14 @@ public partial class TestModule; Invoke(generated.ResolveRequired("IWork"), "Sync", 1); - Assert.Equal( - ["enter sync-only", "enter both Sync", "exit both Sync", "exit sync-only"], + Verify( Log(generated) + .SequenceEqual([ + "enter sync-only", + "enter both Sync", + "exit both Sync", + "exit sync-only", + ]) ); } @@ -661,7 +678,7 @@ public partial class TestModule; /// An interceptor that can serve nothing on the service produces no wrapper at all, so the /// service resolves as the implementation registered it. /// - [Fact] + [VerifyTest] public void InterceptorThatServesNothing_GeneratesNoWrapper() { var generated = GeneratedAssembly.Create( @@ -685,7 +702,7 @@ public partial class TestModule; var resolved = generated.ResolveRequired("IWork"); - Assert.Equal("Work", resolved.GetType().Name); + Verify(resolved.GetType().Name == "Work"); } /// @@ -694,37 +711,38 @@ public partial class TestModule; /// generic service type — but interception does not need one: the wrapper is a generated type, /// and an open generic implementation type is what the container does accept. /// - [Fact] + [VerifyTest] public void GenericImplementation_IsIntercepted() { var result = GeneratorTestHarness.Run( GenericRepo("public class Repo : IRepo { public void Run() { } }") ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Contains(result.GeneratedSources.Keys, key => key.Contains("Repo_Intercepted")); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0008")); + Verify(result.GeneratedSources.Keys.Any(key => key.Contains("Repo_Intercepted"))); } /// /// The wrapper is generic over the same parameters, so the container can register it as an open /// generic implementation type and close it per construction. /// - [Fact] + [VerifyTest] public void GenericImplementation_EmitsAGenericWrapper() { var result = GeneratorTestHarness.Run( GenericRepo("public class Repo : IRepo { public void Run() { } }") ); - var wrapper = Assert - .Single(result.GeneratedSources, pair => pair.Key.Contains("Repo_Intercepted")) - .Value; + var wrapper = Single( + result.GeneratedSources, + pair => pair.Key.Contains("Repo_Intercepted") + ).Value; - Assert.Contains("class Repo_Intercepted", wrapper); + Verify(wrapper.Contains("class Repo_Intercepted")); // It takes the implementation by its own type. Asking for the service would resolve the // wrapper itself, which is registered as that service, and recurse. - Assert.Contains("Repo inner", wrapper); + Verify(wrapper.Contains("Repo inner")); } /// @@ -732,27 +750,28 @@ public void GenericImplementation_EmitsAGenericWrapper() /// factory, which an open generic service type cannot carry. Every type is written unbound: no /// `T` is in scope at the registration. /// - [Fact] + [VerifyTest] public void GenericImplementation_RegistersAsAnOpenGenericImplementation() { var result = GeneratorTestHarness.Run( GenericRepo("public class Repo : IRepo { public void Run() { } }") ); - var registration = Assert - .Single(result.GeneratedSources, pair => pair.Key.Contains("Interceptors")) - .Value; + var registration = Single( + result.GeneratedSources, + pair => pair.Key.Contains("Interceptors") + ).Value; - Assert.Contains("InterceptOpenGeneric", registration); - Assert.Contains("typeof(global::TestNamespace.IRepo<>)", registration); - Assert.Contains("typeof(global::TestNamespace.Repo_Intercepted<>)", registration); + Verify(registration.Contains("InterceptOpenGeneric")); + Verify(registration.Contains("typeof(global::TestNamespace.IRepo<>)")); + Verify(registration.Contains("typeof(global::TestNamespace.Repo_Intercepted<>)")); } /// /// The wrapper repeats the implementation's constraints, without which it could not reference /// what it wraps. /// - [Fact] + [VerifyTest] public void ConstrainedGenericImplementation_RepeatsTheConstraints() { var result = GeneratorTestHarness.Run( @@ -762,13 +781,14 @@ public void ConstrainedGenericImplementation_RepeatsTheConstraints() ) ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0008")); - var wrapper = Assert - .Single(result.GeneratedSources, pair => pair.Key.Contains("Repo_Intercepted")) - .Value; + var wrapper = Single( + result.GeneratedSources, + pair => pair.Key.Contains("Repo_Intercepted") + ).Value; - Assert.Contains("where T : class, global::TestNamespace.IMarker, new()", wrapper); + Verify(wrapper.Contains("where T : class, global::TestNamespace.IMarker, new()")); } /// @@ -776,7 +796,7 @@ public void ConstrainedGenericImplementation_RepeatsTheConstraints() /// Roslyn reports the constructor constraint for a struct-constrained parameter anyway, so the /// reader has to drop it rather than pass it through. /// - [Fact] + [VerifyTest] public void StructConstrainedGeneric_DoesNotRepeatTheDefaultConstructor() { var result = GeneratorTestHarness.Run( @@ -785,18 +805,19 @@ public void StructConstrainedGeneric_DoesNotRepeatTheDefaultConstructor() ) ); - var wrapper = Assert - .Single(result.GeneratedSources, pair => pair.Key.Contains("Repo_Intercepted")) - .Value; + var wrapper = Single( + result.GeneratedSources, + pair => pair.Key.Contains("Repo_Intercepted") + ).Value; - Assert.Contains("where T : struct", wrapper); - Assert.DoesNotContain("new()", wrapper); + Verify(wrapper.Contains("where T : struct")); + Verify(!wrapper.Contains("new()")); } /// /// And the constrained wrapper is not merely well-formed text: it compiles, loads and runs. /// - [Fact] + [VerifyTest] public void ConstrainedGenericImplementation_ResolvesAndIntercepts() { var generated = GeneratedAssembly.Create( @@ -813,8 +834,8 @@ public class Marked : IMarker; var closed = generated.Type("IRepo`1").MakeGenericType(generated.Type("Marked")); var resolved = generated.BuildProvider().GetService(closed); - Assert.NotNull(resolved); - Assert.StartsWith("Repo_Intercepted", resolved!.GetType().Name); + Verify(resolved is not null); + Verify(resolved!.GetType().Name.StartsWith("Repo_Intercepted")); } /// @@ -844,7 +865,7 @@ public partial class TestModule; /// interface is reached through the base rather than declared, and a service registration finds /// it that way too — interception used to disagree and report that the class implemented none. /// - [Fact] + [VerifyTest] public void ClosedConstructionOfAGenericService_IsIntercepted() { var generated = GeneratedAssembly.Create( @@ -871,12 +892,12 @@ public partial class TestModule; generated.Type("IRepo`1").MakeGenericType(typeof(string)) )!; - Assert.EndsWith("_Intercepted", resolved.GetType().Name); - Assert.Equal("repo", resolved.GetType().GetMethod("Name")!.Invoke(resolved, null)); - Assert.Equal(["enter tracing Name", "exit tracing Name"], Log(generated)); + Verify(resolved.GetType().Name.EndsWith("_Intercepted")); + Verify(Equals(resolved.GetType().GetMethod("Name")!.Invoke(resolved, null), "repo")); + Verify(Log(generated).SequenceEqual(["enter tracing Name", "exit tracing Name"])); } - [Fact] + [VerifyTest] public void RefParameter_ReportsDM0008() { var result = GeneratorTestHarness.Run( @@ -896,27 +917,27 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Contains("by ref", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("by ref")); } /// /// The invocation state keeps the arguments and the result in fields, and a class cannot hold a /// ref struct in a field. /// - [Theory] - [InlineData( + [VerifyTest] + [Row( "System.ReadOnlySpan Name();", "public System.ReadOnlySpan Name() => System.MemoryExtensions.AsSpan(\"name\");", "returns a ref struct" )] - [InlineData( + [Row( "int Count(System.ReadOnlySpan text);", "public int Count(System.ReadOnlySpan text) => text.Length;", "which is a ref struct" )] - [InlineData( + [Row( "System.ReadOnlySpan Name { get; }", "public System.ReadOnlySpan Name => default;", "is a ref struct" @@ -929,14 +950,14 @@ string reason { var result = GeneratorTestHarness.Run(Source(interfaceMember, implementation)); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Contains(reason, diagnostic.GetMessage()); - Assert.DoesNotContain(result.GeneratedSources.Keys, name => name.Contains("_Intercepted")); + Verify(diagnostic.GetMessage().Contains(reason)); + Verify(!result.GeneratedSources.Keys.Any(name => name.Contains("_Intercepted"))); result.AssertNoErrors(); } - [Fact] + [VerifyTest] public void ServiceWithNoInterface_ReportsDM0008() { var result = GeneratorTestHarness.Run( @@ -954,13 +975,13 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); - Assert.Contains("interface", diagnostic.GetMessage()); + Verify(diagnostic.Severity == DiagnosticSeverity.Warning); + Verify(diagnostic.GetMessage().Contains("interface")); } - [Fact] + [VerifyTest] public void ServiceWithSeveralInterfaces_ReportsDM0008() { var result = GeneratorTestHarness.Run( @@ -981,9 +1002,9 @@ public partial class TestModule; """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0008"); - Assert.Contains("Service", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("Service")); } private static IReadOnlyList Log(GeneratedAssembly generated) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs b/tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs index f634233..bf4fb17 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/InterceptorLifetimeTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The lifetime an interceptor is registered with. @@ -17,47 +16,47 @@ namespace DependencyModules.Tests.GeneratorTests; /// decorators, but only somebody reading the generated code would ever find it. Naming the lifetime /// where the interception is declared says it out loud. /// -public class InterceptorLifetimeTests +public partial class InterceptorLifetimeTests { - [Fact] + [VerifyTest] public void WithNoLifetimeNamed_TheInterceptorIsASingleton() { var interceptors = Run("[Intercept(typeof(CountingInterceptor))]"); - Assert.Contains("TryAddSingleton", interceptors); + Verify(interceptors.Contains("TryAddSingleton")); } - [Theory] - [InlineData("Scoped", "TryAddScoped")] - [InlineData("Transient", "TryAddTransient")] - [InlineData("Singleton", "TryAddSingleton")] + [VerifyTest] + [Row("Scoped", "TryAddScoped")] + [Row("Transient", "TryAddTransient")] + [Row("Singleton", "TryAddSingleton")] public void ANamedLifetime_IsTheOneRegistered(string lifetime, string expected) { var interceptors = Run( $"[Intercept(typeof(CountingInterceptor), Lifetime = ServiceLifetime.{lifetime})]" ); - Assert.Contains(expected, interceptors); + Verify(interceptors.Contains(expected)); } /// /// A scoped interceptor must not also be registered as a singleton. The point is to choose, /// not to add a second registration the container resolves ahead of the first. /// - [Fact] + [VerifyTest] public void AScopedInterceptor_IsNotAlsoRegisteredAsASingleton() { var interceptors = Run( "[Intercept(typeof(CountingInterceptor), Lifetime = ServiceLifetime.Scoped)]" ); - Assert.DoesNotContain("TryAddSingleton", interceptors); + Verify(!interceptors.Contains("TryAddSingleton")); } /// /// The registration still has to work end to end, not merely be emitted with the right name. /// - [Fact] + [VerifyTest] public void AScopedInterceptor_Runs() { var generated = GeneratedAssembly.Create( @@ -67,8 +66,8 @@ public void AScopedInterceptor_Runs() var provider = generated.BuildProvider(); var greeter = provider.GetService(generated.Type("IGreeter"))!; - Assert.Equal("Greeter_Intercepted", greeter.GetType().Name); - Assert.Equal("hi", greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null)); + Verify(greeter.GetType().Name == "Greeter_Intercepted"); + Verify(Equals(greeter.GetType().GetMethod("Greet")!.Invoke(greeter, null), "hi")); } private static string Run(string attribute) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs b/tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs index 9fdfc74..a368ec6 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/MockTestExportDiagnosticTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// DM0021: a [Mock] parameter and a [TestExport] on the same method, both naming one @@ -16,9 +15,9 @@ namespace DependencyModules.Tests.GeneratorTests; /// everything under it, and one test overriding it for one argument is exactly what having both /// scopes is for. Reporting that would be reporting the feature. /// -public class MockTestExportDiagnosticTests +public partial class MockTestExportDiagnosticTests { - [Fact] + [VerifyTest] public void BothOnOneMethod_ReportsDM0021() { var result = Run( @@ -28,17 +27,17 @@ public void Conflicting([Mock] IThing thing) { } """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); - Assert.Contains("Conflicting", diagnostic.GetMessage()); - Assert.Contains("IThing", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("Conflicting")); + Verify(diagnostic.GetMessage().Contains("IThing")); } /// /// Reported at the parameter, which is the half that wins and the half a reader has to look at /// to see what actually happens. /// - [Fact] + [VerifyTest] public void ItIsReportedAtTheParameter() { var result = Run( @@ -48,16 +47,16 @@ public void Conflicting([Mock] IThing thing) { } """ ); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); - Assert.NotNull(diagnostic.Location.SourceTree); - Assert.Equal("Test.cs", System.IO.Path.GetFileName(diagnostic.Location.GetLineSpan().Path)); + Verify(diagnostic.Location.SourceTree is not null); + Verify(System.IO.Path.GetFileName(diagnostic.Location.GetLineSpan().Path) == "Test.cs"); } /// /// The class-level default a test opts out of. This is the shape the override exists for. /// - [Fact] + [VerifyTest] public void TestExportOnTheClass_IsNotReported() { var result = GeneratorTestHarness.Run( @@ -71,10 +70,10 @@ public void Overriding([Mock] IThing thing) { } """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } - [Fact] + [VerifyTest] public void TestExportOnTheAssembly_IsNotReported() { var result = GeneratorTestHarness.Run( @@ -89,13 +88,13 @@ public void Overriding([Mock] IThing thing) { } """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } /// /// Naming different services is two unrelated declarations, not a disagreement. /// - [Fact] + [VerifyTest] public void BothOnOneMethodNamingDifferentServices_IsNotReported() { var result = Run( @@ -105,18 +104,18 @@ public void Unrelated([Mock] IThing thing) { } """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } - [Fact] + [VerifyTest] public void AMockWithNoTestExport_IsNotReported() { var result = Run("public void JustAMock([Mock] IThing thing) { }"); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } - [Fact] + [VerifyTest] public void ATestExportWithNoMock_IsNotReported() { var result = Run( @@ -126,13 +125,13 @@ public void JustAnExport(IThing thing) { } """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } /// /// A keyed [Mock] is registered under its key. The unkeyed export stays in use. /// - [Fact] + [VerifyTest] public void AKeyedMock_IsNotReported() { var result = Run( @@ -142,7 +141,7 @@ public void Keyed([Mock] [Microsoft.Extensions.DependencyInjection.FromKeyedServ """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } /// @@ -150,7 +149,7 @@ public void Keyed([Mock] [Microsoft.Extensions.DependencyInjection.FromKeyedServ /// [Mock] T then registers nothing. The export replaces mock.Object, so the /// parameter gets the export. /// - [Fact] + [VerifyTest] public void AMockPairedWithAMoqMock_IsNotReported() { var result = Run( @@ -160,10 +159,10 @@ public void Paired([Mock] IThing thing, Moq.Mock mock) { } """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0021")); } - [Fact] + [VerifyTest] public void AMoqMockOfAnotherService_IsStillReported() { var result = Run( @@ -173,13 +172,13 @@ public void Unpaired([Mock] IThing thing, Moq.Mock other) { } """ ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); } /// /// Resolved rather than string-matched, the way every other attribute this generator reads is. /// - [Fact] + [VerifyTest] public void QualifiedSpellings_AreStillReported() { var result = Run( @@ -189,7 +188,7 @@ public void Conflicting([global::DependencyModules.Testing.Attributes.Mock] IThi """ ); - Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); + Single(result.GeneratorDiagnostics, d => d.Id == "DM0021"); } private const string Preamble = """ diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs index 9ac5d55..52251e3 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModelComparerTests.cs @@ -1,153 +1,150 @@ using CSharpAuthor; using DependencyModules.SourceGenerator.Impl.Models; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// These comparers are what Roslyn consults to decide whether a pipeline step's output changed. /// Every field that affects generated code must make two models compare unequal, or an edit to /// that field will serve stale output. /// -public class ModelComparerTests +public partial class ModelComparerTests { private readonly ModuleEntryPointModelComparer _entryPointComparer = new(); private readonly DependencyModuleConfigurationModelComparer _configurationComparer = new(); - [Fact] + [VerifyTest] public void EntryPoints_BuiltFromTheSameValues_AreEqual() { - Assert.True( - _entryPointComparer.Equals(ModelFactory.EntryPoint(), ModelFactory.EntryPoint()) - ); + Verify(_entryPointComparer.Equals(ModelFactory.EntryPoint(), ModelFactory.EntryPoint())); } - [Fact] + [VerifyTest] public void EqualEntryPoints_ShareAHashCode() { - Assert.Equal( - _entryPointComparer.GetHashCode(ModelFactory.EntryPoint()), + Verify( _entryPointComparer.GetHashCode(ModelFactory.EntryPoint()) + == _entryPointComparer.GetHashCode(ModelFactory.EntryPoint()) ); } - [Fact] + [VerifyTest] public void EntryPoints_BothNull_AreEqual() { - Assert.True(_entryPointComparer.Equals(null, null)); + Verify(_entryPointComparer.Equals(null, null)); } - [Fact] + [VerifyTest] public void EntryPoints_OneNull_AreNotEqual() { - Assert.False(_entryPointComparer.Equals(ModelFactory.EntryPoint(), null)); - Assert.False(_entryPointComparer.Equals(null, ModelFactory.EntryPoint())); + Verify(!_entryPointComparer.Equals(ModelFactory.EntryPoint(), null)); + Verify(!_entryPointComparer.Equals(null, ModelFactory.EntryPoint())); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByFileLocation_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(fileLocation: "/project/A.cs"), ModelFactory.EntryPoint(fileLocation: "/project/B.cs") ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByType_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("Ns", "One")), ModelFactory.EntryPoint(entryPointType: TypeDefinition.Get("Ns", "Two")) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByFeatures_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(features: ModuleEntryPointFeatures.None), ModelFactory.EntryPoint(features: ModuleEntryPointFeatures.OnlyRealm) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByUseMethod_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(useMethod: "UseOne"), ModelFactory.EntryPoint(useMethod: "UseTwo") ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByRegistrationType_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(registrationType: RegistrationType.Add), ModelFactory.EntryPoint(registrationType: RegistrationType.Try) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByGenerateAttribute_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(generateAttribute: true), ModelFactory.EntryPoint(generateAttribute: false) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByJsonSerializerRegistration_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(registerJsonSerializers: true), ModelFactory.EntryPoint(registerJsonSerializers: false) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByFactoryGeneration_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(generateFactories: true), ModelFactory.EntryPoint(generateFactories: false) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByParameters_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(parameters: [Parameter("one")]), ModelFactory.EntryPoint(parameters: [Parameter("two")]) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_WithSeparateButEqualParameters_AreEqual() { - Assert.True( + Verify( _entryPointComparer.Equals( ModelFactory.EntryPoint(parameters: [Parameter("same")]), ModelFactory.EntryPoint(parameters: [Parameter("same")]) @@ -155,32 +152,32 @@ public void EntryPoints_WithSeparateButEqualParameters_AreEqual() ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByProperties_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(properties: [Property("One")]), ModelFactory.EntryPoint(properties: [Property("Two")]) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByAttributes_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(attributes: [Attribute("One")]), ModelFactory.EntryPoint(attributes: [Attribute("Two")]) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_WithSeparateButEqualAttributes_AreEqual() { - Assert.True( + Verify( _entryPointComparer.Equals( ModelFactory.EntryPoint(attributes: [Attribute("Same")]), ModelFactory.EntryPoint(attributes: [Attribute("Same")]) @@ -188,32 +185,32 @@ public void EntryPoints_WithSeparateButEqualAttributes_AreEqual() ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByFeatureTypes_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(featureTypes: [TypeDefinition.Get("Ns", "IOne")]), ModelFactory.EntryPoint(featureTypes: [TypeDefinition.Get("Ns", "ITwo")]) ) ); } - [Fact] + [VerifyTest] public void EntryPoints_DifferingByAdditionalModules_AreNotEqual() { - Assert.False( - _entryPointComparer.Equals( + Verify( + !_entryPointComparer.Equals( ModelFactory.EntryPoint(additionalModules: [TypeDefinition.Get("Ns", "One")]), ModelFactory.EntryPoint(additionalModules: [TypeDefinition.Get("Ns", "Two")]) ) ); } - [Fact] + [VerifyTest] public void Configurations_BuiltFromTheSameValues_AreEqual() { - Assert.True( + Verify( _configurationComparer.Equals( ModelFactory.Configuration(), ModelFactory.Configuration() @@ -221,90 +218,89 @@ public void Configurations_BuiltFromTheSameValues_AreEqual() ); } - [Fact] + [VerifyTest] public void SameConfigurationInstance_IsEqualToItself() { var configuration = ModelFactory.Configuration(); - Assert.True(_configurationComparer.Equals(configuration, configuration)); + Verify(_configurationComparer.Equals(configuration, configuration)); } - [Fact] + [VerifyTest] public void Configurations_OneNull_AreNotEqual() { - Assert.False(_configurationComparer.Equals(ModelFactory.Configuration(), null)); - Assert.False(_configurationComparer.Equals(null, ModelFactory.Configuration())); + Verify(!_configurationComparer.Equals(ModelFactory.Configuration(), null)); + Verify(!_configurationComparer.Equals(null, ModelFactory.Configuration())); } - [Fact] + [VerifyTest] public void EqualConfigurations_ShareAHashCode() { - Assert.Equal( - _configurationComparer.GetHashCode(ModelFactory.Configuration()), + Verify( _configurationComparer.GetHashCode(ModelFactory.Configuration()) + == _configurationComparer.GetHashCode(ModelFactory.Configuration()) ); } - [Theory] - [MemberData(nameof(DifferingConfigurations))] + [VerifyTest] + [RowSource(nameof(DifferingConfigurations), DeterministicReplay = true)] public void Configurations_DifferingByAnyField_AreNotEqual( string field, DependencyModuleConfigurationModel other ) { - Assert.False( - _configurationComparer.Equals(ModelFactory.Configuration(), other), + Verify( + !_configurationComparer.Equals(ModelFactory.Configuration(), other), $"Configurations differing by {field} compared equal, so a change to it would serve stale output." ); } - public static TheoryData< - string, - DependencyModuleConfigurationModel - > DifferingConfigurations() => - new() - { - { + public static IEnumerable<( + string Field, + DependencyModuleConfigurationModel Other + )> DifferingConfigurations() => + [ + ( nameof(DependencyModuleConfigurationModel.RegistrationType), ModelFactory.Configuration(registrationType: RegistrationType.Try) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.RegisterSourceGenerator), ModelFactory.Configuration(registerSourceGenerator: true) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.RootNamespace), ModelFactory.Configuration(rootNamespace: "Other") - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.ProjectDir), ModelFactory.Configuration(projectDir: "/other/") - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.AutoGenerateEntry), ModelFactory.Configuration(autoGenerateEntry: false) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.LogOutputFolder), ModelFactory.Configuration(logOutputFolder: "/logs") - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.LogOutputLevel), ModelFactory.Configuration(logOutputLevel: LogOutputLevel.Error) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.GenerateFactories), ModelFactory.Configuration(generateFactories: true) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.ExcludeGeneratedCodeFromCoverage), ModelFactory.Configuration(excludeGeneratedCodeFromCoverage: false) - }, - { + ), + ( nameof(DependencyModuleConfigurationModel.GeneratedCodeStyle), ModelFactory.Configuration(generatedCodeStyle: BraceStyle.KAndR) - }, - }; + ), + ]; private readonly InterceptorModelComparer _interceptorComparer = new(); @@ -314,58 +310,58 @@ public static TheoryData< /// the interception stayed on whichever module had it before. Both sibling comparers already /// compared theirs. /// - [Fact] + [VerifyTest] public void Interceptors_DifferingByRealm_AreNotEqual() { - Assert.False( - _interceptorComparer.Equals( + Verify( + !_interceptorComparer.Equals( Interceptor(realm: TypeDefinition.Get("Ns", "OneRealm")), Interceptor(realm: TypeDefinition.Get("Ns", "OtherRealm")) ) ); } - [Fact] + [VerifyTest] public void Interceptors_GainingARealm_AreNotEqual() { - Assert.False( - _interceptorComparer.Equals( + Verify( + !_interceptorComparer.Equals( Interceptor(), Interceptor(realm: TypeDefinition.Get("Ns", "OneRealm")) ) ); } - [Fact] + [VerifyTest] public void Interceptors_BuiltFromTheSameValues_AreEqual() { - Assert.True(_interceptorComparer.Equals(Interceptor(), Interceptor())); + Verify(_interceptorComparer.Equals(Interceptor(), Interceptor())); } - [Fact] + [VerifyTest] public void EqualInterceptors_ShareAHashCode() { - Assert.Equal( - _interceptorComparer.GetHashCode(Interceptor()), + Verify( _interceptorComparer.GetHashCode(Interceptor()) + == _interceptorComparer.GetHashCode(Interceptor()) ); } - [Fact] + [VerifyTest] public void Interceptors_DifferingByRealm_DoNotShareAHashCode() { - Assert.NotEqual( - _interceptorComparer.GetHashCode(Interceptor()), - _interceptorComparer.GetHashCode( - Interceptor(realm: TypeDefinition.Get("Ns", "OneRealm")) - ) + Verify( + _interceptorComparer.GetHashCode(Interceptor()) + != _interceptorComparer.GetHashCode( + Interceptor(realm: TypeDefinition.Get("Ns", "OneRealm")) + ) ); } - [Fact] + [VerifyTest] public void Interceptors_DifferingByOrder_AreNotEqual() { - Assert.False(_interceptorComparer.Equals(Interceptor(order: 1), Interceptor(order: 2))); + Verify(!_interceptorComparer.Equals(Interceptor(order: 1), Interceptor(order: 2))); } private static InterceptorModel Interceptor(ITypeDefinition? realm = null, int order = 0) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs index 8bfabee..0538b07 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModelEqualityTests.cs @@ -1,8 +1,7 @@ using CSharpAuthor; using DependencyModules.SourceGenerator.Impl.Models; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// The generator's model records feed Roslyn's incremental cache, so two structurally identical @@ -10,124 +9,125 @@ namespace DependencyModules.Tests.GeneratorTests; /// IReadOnlyList members by reference, which silently disables caching — these tests pin the /// structural semantics that replaced it. /// -public class ModelEqualityTests +public partial class ModelEqualityTests { private static readonly ITypeDefinition SomeType = TypeDefinition.Get("Ns", "SomeType"); private static readonly ITypeDefinition OtherType = TypeDefinition.Get("Ns", "OtherType"); - [Fact] + [VerifyTest] public void AttributeModel_WithSeparateButEqualLists_IsEqual() { var first = Attribute(arguments: [new AttributeArgumentValue("key", "value")]); var second = Attribute(arguments: [new AttributeArgumentValue("key", "value")]); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Verify(first.Equals(second)); + Verify(first.GetHashCode() == second.GetHashCode()); } - [Fact] + [VerifyTest] public void AttributeModel_WithEmptyLists_IsEqual() { - Assert.Equal(Attribute(), Attribute()); + Verify(Attribute().Equals(Attribute())); } - [Fact] + [VerifyTest] public void AttributeModel_WithDifferentArguments_IsNotEqual() { var first = Attribute(arguments: [new AttributeArgumentValue("key", "one")]); var second = Attribute(arguments: [new AttributeArgumentValue("key", "two")]); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeModel_WithDifferentArgumentCounts_IsNotEqual() { var first = Attribute(arguments: [new AttributeArgumentValue("key", "one")]); var second = Attribute(); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeModel_WithDifferentProperties_IsNotEqual() { var first = Attribute(properties: [new AttributeArgumentValue("P", 1)]); var second = Attribute(properties: [new AttributeArgumentValue("P", 2)]); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeModel_WithDifferentImplementedInterfaces_IsNotEqual() { var first = Attribute(interfaces: [SomeType]); var second = Attribute(interfaces: [OtherType]); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeModel_WithDifferentType_IsNotEqual() { var first = new AttributeModel(SomeType, [], [], []); var second = new AttributeModel(OtherType, [], [], []); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_WithEqualArrayValues_IsEqual() { var first = new AttributeArgumentValue("names", new[] { "a", "b" }); var second = new AttributeArgumentValue("names", new[] { "a", "b" }); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Verify(first.Equals(second)); + Verify(first.GetHashCode() == second.GetHashCode()); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_WithDifferentArrayValues_IsNotEqual() { var first = new AttributeArgumentValue("names", new[] { "a", "b" }); var second = new AttributeArgumentValue("names", new[] { "a", "c" }); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_WithDifferentArrayLengths_IsNotEqual() { var first = new AttributeArgumentValue("names", new[] { "a" }); var second = new AttributeArgumentValue("names", new[] { "a", "b" }); - Assert.NotEqual(first, second); + Verify(!first.Equals(second)); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_WithDifferentNames_IsNotEqual() { - Assert.NotEqual( - new AttributeArgumentValue("one", "value"), - new AttributeArgumentValue("two", "value") + Verify( + !new AttributeArgumentValue("one", "value").Equals( + new AttributeArgumentValue("two", "value") + ) ); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_WithNullValues_IsEqual() { - Assert.Equal( - new AttributeArgumentValue("key", null), - new AttributeArgumentValue("key", null) + Verify( + new AttributeArgumentValue("key", null).Equals(new AttributeArgumentValue("key", null)) ); } - [Fact] + [VerifyTest] public void AttributeArgumentValue_NullVersusValue_IsNotEqual() { - Assert.NotEqual( - new AttributeArgumentValue("key", null), - new AttributeArgumentValue("key", "value") + Verify( + !new AttributeArgumentValue("key", null).Equals( + new AttributeArgumentValue("key", "value") + ) ); } @@ -135,72 +135,77 @@ public void AttributeArgumentValue_NullVersusValue_IsNotEqual() /// A string is IEnumerable; it must not be compared character by character against a /// char collection. /// - [Fact] + [VerifyTest] public void AttributeArgumentValue_StringVersusCharArray_IsNotEqual() { - Assert.NotEqual( - new AttributeArgumentValue("key", "ab"), - new AttributeArgumentValue("key", new[] { 'a', 'b' }) + Verify( + !new AttributeArgumentValue("key", "ab").Equals( + new AttributeArgumentValue("key", new[] { 'a', 'b' }) + ) ); } - [Fact] + [VerifyTest] public void ParameterInfoModel_WithSeparateButEqualAttributes_IsEqual() { var first = new ParameterInfoModel("name", SomeType, null, [Attribute()]); var second = new ParameterInfoModel("name", SomeType, null, [Attribute()]); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Verify(first.Equals(second)); + Verify(first.GetHashCode() == second.GetHashCode()); } - [Fact] + [VerifyTest] public void ParameterInfoModel_WithDifferentNames_IsNotEqual() { - Assert.NotEqual( - new ParameterInfoModel("one", SomeType, null, []), - new ParameterInfoModel("two", SomeType, null, []) + Verify( + !new ParameterInfoModel("one", SomeType, null, []).Equals( + new ParameterInfoModel("two", SomeType, null, []) + ) ); } - [Fact] + [VerifyTest] public void ParameterInfoModel_WithDifferentTypes_IsNotEqual() { - Assert.NotEqual( - new ParameterInfoModel("name", SomeType, null, []), - new ParameterInfoModel("name", OtherType, null, []) + Verify( + !new ParameterInfoModel("name", SomeType, null, []).Equals( + new ParameterInfoModel("name", OtherType, null, []) + ) ); } - [Fact] + [VerifyTest] public void ParameterInfoModel_WithDifferentDefaultValues_IsNotEqual() { - Assert.NotEqual( - new ParameterInfoModel("name", SomeType, 1, []), - new ParameterInfoModel("name", SomeType, 2, []) + Verify( + !new ParameterInfoModel("name", SomeType, 1, []).Equals( + new ParameterInfoModel("name", SomeType, 2, []) + ) ); } - [Fact] + [VerifyTest] public void ConstructorInfoModel_WithSeparateButEqualParameters_IsEqual() { var first = new ConstructorInfoModel([new ParameterInfoModel("a", SomeType, null, [])]); var second = new ConstructorInfoModel([new ParameterInfoModel("a", SomeType, null, [])]); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Verify(first.Equals(second)); + Verify(first.GetHashCode() == second.GetHashCode()); } - [Fact] + [VerifyTest] public void ConstructorInfoModel_WithDifferentParameters_IsNotEqual() { - Assert.NotEqual( - new ConstructorInfoModel([new ParameterInfoModel("a", SomeType, null, [])]), - new ConstructorInfoModel([new ParameterInfoModel("b", SomeType, null, [])]) + Verify( + !new ConstructorInfoModel([new ParameterInfoModel("a", SomeType, null, [])]).Equals( + new ConstructorInfoModel([new ParameterInfoModel("b", SomeType, null, [])]) + ) ); } - [Fact] + [VerifyTest] public void ServiceFactoryModel_WithSeparateButEqualParameters_IsEqual() { var first = new ServiceFactoryModel( @@ -214,25 +219,27 @@ [new ParameterInfoModel("a", SomeType, null, [])] [new ParameterInfoModel("a", SomeType, null, [])] ); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); + Verify(first.Equals(second)); + Verify(first.GetHashCode() == second.GetHashCode()); } - [Fact] + [VerifyTest] public void ServiceFactoryModel_WithDifferentMethodNames_IsNotEqual() { - Assert.NotEqual( - new ServiceFactoryModel(SomeType, "Create", []), - new ServiceFactoryModel(SomeType, "Build", []) + Verify( + !new ServiceFactoryModel(SomeType, "Create", []).Equals( + new ServiceFactoryModel(SomeType, "Build", []) + ) ); } - [Fact] + [VerifyTest] public void ServiceFactoryModel_WithDifferentDeclaringTypes_IsNotEqual() { - Assert.NotEqual( - new ServiceFactoryModel(SomeType, "Create", []), - new ServiceFactoryModel(OtherType, "Create", []) + Verify( + !new ServiceFactoryModel(SomeType, "Create", []).Equals( + new ServiceFactoryModel(OtherType, "Create", []) + ) ); } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs index 897a913..9fa44d7 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModuleDeclarationTests.cs @@ -2,15 +2,14 @@ using DependencyModules.Runtime.Interfaces; using DependencyModules.Tests.Infrastructure; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// What the generator reads from a module declaration: its parameters, its equality members, /// and whether it can complete the module at all. /// -public class ModuleDeclarationTests +public partial class ModuleDeclarationTests { private const string Preamble = """ using DependencyModules.Runtime.Attributes; @@ -24,7 +23,7 @@ namespace TestNamespace; private static GeneratorResult Run(string source) => GeneratorTestHarness.Run(Preamble + source); - [Fact] + [VerifyTest] public void APropertyWithAPrivateSetter_IsNotAModuleParameter() { var result = Run( @@ -43,11 +42,11 @@ public partial class TestModule var module = result.SourceContaining("Module.g.cs"); - Assert.DoesNotContain("newModule.Label", module); - Assert.Contains("newModule.Host", module); + Verify(!module.Contains("newModule.Label")); + Verify(module.Contains("newModule.Host")); } - [Fact] + [VerifyTest] public void APropertyOfANestedClass_IsNotAModuleParameter() { var result = Run( @@ -65,11 +64,11 @@ public class Options result.AssertNoErrors(); - Assert.DoesNotContain("newModule.Size", result.SourceContaining("Module.g.cs")); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.SourceContaining("Module.g.cs").Contains("newModule.Size")); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } - [Fact] + [VerifyTest] public void EqualsInAnotherPartialDeclaration_IsNotGeneratedAgain() { var result = GeneratorTestHarness.Run( @@ -100,10 +99,10 @@ public override bool Equals(object? obj) => result.AssertNoErrors(); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } - [Fact] + [VerifyTest] public void AGetHashCodeOfItsOwn_IsNotGeneratedAgain() { var result = Run( @@ -120,15 +119,15 @@ public partial class TestModule var module = result.SourceContaining("Module.g.cs"); - Assert.Contains("override bool Equals", module); - Assert.DoesNotContain("override int GetHashCode", module); + Verify(module.Contains("override bool Equals")); + Verify(!module.Contains("override int GetHashCode")); } - [Theory] - [InlineData("other is not null", "a", "a", 1)] - [InlineData("other is not null", "a", "b", 1)] - [InlineData("other is not null && other.Host == Host", "a", "a", 1)] - [InlineData("other is not null && other.Host == Host", "a", "b", 2)] + [VerifyTest] + [Row("other is not null", "a", "a", 1)] + [Row("other is not null", "a", "b", 1)] + [Row("other is not null && other.Host == Host", "a", "a", 1)] + [Row("other is not null && other.Host == Host", "a", "b", 2)] public void AModuleWithOnlyTypedEquals_IsLoadedByThatEquals( string equality, string firstHost, @@ -153,10 +152,7 @@ public void ConfigureServices(IServiceCollection services) => } """; - Assert.DoesNotContain( - GeneratorTestHarness.Run(source).GeneratorDiagnostics, - d => d.Id == "DM0018" - ); + Verify(!GeneratorTestHarness.Run(source).GeneratorDiagnostics.Any(d => d.Id == "DM0018")); var assembly = GeneratedAssembly.Create(source); @@ -171,13 +167,10 @@ IDependencyModule Module(string host) var services = new ServiceCollection().AddModules(Module(firstHost), Module(secondHost)); - Assert.Equal( - expectedLoads, - services.Count(d => d.ServiceType == assembly.Type("AuditMarker")) - ); + Verify(services.Count(d => d.ServiceType == assembly.Type("AuditMarker")) == expectedLoads); } - [Fact] + [VerifyTest] public void AModuleThatIsNotPartial_GetsOnlyDM0003() { var result = Run( @@ -192,11 +185,11 @@ public class ShopModule { } """ ); - Assert.Equal("DM0003", Assert.Single(result.Errors).Id); - Assert.DoesNotContain(result.GeneratedSources.Keys, key => key.Contains("ShopModule")); + Verify(Single(result.Errors).Id == "DM0003"); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("ShopModule"))); } - [Fact] + [VerifyTest] public void ANestedModule_GetsOnlyDM0017() { var result = Run( @@ -235,7 +228,7 @@ public partial class ShopModule; """ ); - Assert.Equal("DM0017", Assert.Single(result.Errors).Id); - Assert.DoesNotContain(result.GeneratedSources.Keys, key => key.Contains("ShopModule")); + Verify(Single(result.Errors).Id == "DM0017"); + Verify(!result.GeneratedSources.Keys.Any(key => key.Contains("ShopModule"))); } } diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs index 662136e..ed787ac 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModuleEqualityDiagnosticTests.cs @@ -1,8 +1,7 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// DM0018. Modules de-duplicate by type, which is right for a module with no parameters and wrong @@ -12,16 +11,16 @@ namespace DependencyModules.Tests.GeneratorTests; /// The generator has to pick an identity either way. This reports that it picked, so the choice is /// the developer's. /// -public class ModuleEqualityDiagnosticTests +public partial class ModuleEqualityDiagnosticTests { - [Fact] + [VerifyTest] public void ASettableProperty_IsReported() { var result = Run("public int SizeLimit { get; set; }"); - var diagnostic = Assert.Single(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + var diagnostic = Single(result.GeneratorDiagnostics, d => d.Id == "DM0018"); - Assert.Contains("TestModule", diagnostic.GetMessage()); + Verify(diagnostic.GetMessage().Contains("TestModule")); } /// @@ -29,43 +28,43 @@ public void ASettableProperty_IsReported() /// public string Value => "A"; has nothing anyone can configure, and the generated /// attribute never assigns it — so there is no identity question to answer and nothing to report. /// - [Fact] + [VerifyTest] public void AnExpressionBodiedProperty_IsNotReported() { var result = Run("""public string Value => "A";"""); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } - [Fact] + [VerifyTest] public void AGetOnlyProperty_IsNotReported() { var result = Run("public string Value { get; } = \"A\";"); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } - [Fact] + [VerifyTest] public void AStaticProperty_IsNotReported() { var result = Run("public static int Shared { get; set; }"); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } - [Fact] + [VerifyTest] public void NoPropertiesAtAll_IsNotReported() { var result = Run(""); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } /// /// Declaring equality is the whole point of the diagnostic, so having done it must silence it. /// The generator already stands aside when a module declares its own Equals. /// - [Fact] + [VerifyTest] public void DeclaringEquals_SilencesIt() { var result = Run( @@ -79,11 +78,11 @@ public override bool Equals(object? obj) => """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } /// A record gets its equality from the language, so it never faces the question. - [Fact] + [VerifyTest] public void ARecordModule_IsNotReported() { var result = GeneratorTestHarness.Run( @@ -99,7 +98,7 @@ public partial record TestModule { """ ); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } private static GeneratorResult Run(string body) => diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs index 23722e6..10671ea 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModuleGenerationSnapshotTests.cs @@ -1,7 +1,6 @@ using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Snapshots of the generator's full output. These exist to make any change to generated code @@ -9,12 +8,12 @@ namespace DependencyModules.Tests.GeneratorTests; /// lands in every consumer's build. /// /// To accept intentional changes: -/// UPDATE_SNAPSHOTS=1 dotnet test tests/DependencyModules.Tests -/// then review the diff under tests/DependencyModules.Tests/Snapshots. +/// UPDATE_SNAPSHOTS=1 scripts/test-verificationglue.sh +/// then review the diff under tests/DependencyModules.Specs/Snapshots. /// -public class ModuleGenerationSnapshotTests +public partial class ModuleGenerationSnapshotTests { - [Fact] + [VerifyTest] public void SimpleModule() { var result = GeneratorTestHarness.Run( @@ -46,7 +45,7 @@ public partial class TestModule; /// emitted after it, because the container resolves a single service from the last matching /// descriptor and the conditional registration is the override. /// - [Fact] + [VerifyTest] public void ModuleWithEnvironmentConditions() { var result = GeneratorTestHarness.Run( @@ -83,7 +82,7 @@ public partial class TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void ModuleWithAllServiceLifetimes() { var result = GeneratorTestHarness.Run( @@ -114,7 +113,7 @@ public partial class TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void ModuleWithConstructorParametersAndProperties() { var result = GeneratorTestHarness.Run( @@ -144,7 +143,7 @@ public void ConfigureServices(IServiceCollection services) { Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void KeyedAndAsRegistrations() { var result = GeneratorTestHarness.Run( @@ -171,7 +170,7 @@ public partial class TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void RegistrationTypeVariants() { var result = GeneratorTestHarness.Run( @@ -202,7 +201,7 @@ public partial class TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void RecordModule() { var result = GeneratorTestHarness.Run( @@ -225,7 +224,7 @@ public partial record TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void GenericServiceRegistrations() { var result = GeneratorTestHarness.Run( @@ -251,7 +250,7 @@ public partial class TestModule; Snapshot.Match(result.ToSnapshot()); } - [Fact] + [VerifyTest] public void ModuleWithCoverageExclusionDisabled() { var result = GeneratorTestHarness.Run( diff --git a/tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs b/tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs index 939cffe..be4a670 100644 --- a/tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs +++ b/tests/DependencyModules.Specs/GeneratorTests/ModuleParameterAccessibilityTests.cs @@ -1,8 +1,7 @@ using System.Linq; using DependencyModules.Tests.Infrastructure; -using Xunit; -namespace DependencyModules.Tests.GeneratorTests; +namespace DependencyModules.Specs.GeneratorTests; /// /// Which of a module's properties become parameters on its generated attribute. @@ -17,60 +16,60 @@ namespace DependencyModules.Tests.GeneratorTests; /// Accessibility is judged from where the generated attribute sits: same assembly, different type. /// So internal reaches it and private does not, and an unmodified property is private by default. /// -public class ModuleParameterAccessibilityTests +public partial class ModuleParameterAccessibilityTests { - [Theory] - [InlineData("private int SizeLimit { get; set; }")] - [InlineData("protected int SizeLimit { get; set; }")] - [InlineData("private protected int SizeLimit { get; set; }")] - [InlineData("int SizeLimit { get; set; }")] + [VerifyTest] + [Row("private int SizeLimit { get; set; }")] + [Row("protected int SizeLimit { get; set; }")] + [Row("private protected int SizeLimit { get; set; }")] + [Row("int SizeLimit { get; set; }")] public void APropertyTheAttributeCannotReach_CompilesCleanly(string property) { Run(property).AssertNoErrors(); } - [Theory] - [InlineData("private int SizeLimit { get; set; }")] - [InlineData("protected int SizeLimit { get; set; }")] - [InlineData("private protected int SizeLimit { get; set; }")] - [InlineData("int SizeLimit { get; set; }")] + [VerifyTest] + [Row("private int SizeLimit { get; set; }")] + [Row("protected int SizeLimit { get; set; }")] + [Row("private protected int SizeLimit { get; set; }")] + [Row("int SizeLimit { get; set; }")] public void APropertyTheAttributeCannotReach_IsNotCopiedOntoIt(string property) { var attribute = Run(property).SourceContaining("TestModule.Module"); - Assert.DoesNotContain("SizeLimit", attribute); + Verify(!attribute.Contains("SizeLimit")); } /// /// It is not a parameter, so there is no identity question and DM0018 has nothing to report. /// Reporting it would have sent the reader to a page describing a property they cannot set. /// - [Theory] - [InlineData("private int SizeLimit { get; set; }")] - [InlineData("protected int SizeLimit { get; set; }")] - [InlineData("private protected int SizeLimit { get; set; }")] - [InlineData("int SizeLimit { get; set; }")] + [VerifyTest] + [Row("private int SizeLimit { get; set; }")] + [Row("protected int SizeLimit { get; set; }")] + [Row("private protected int SizeLimit { get; set; }")] + [Row("int SizeLimit { get; set; }")] public void APropertyTheAttributeCannotReach_IsNotReportedAsDM0018(string property) { var result = Run(property); - Assert.DoesNotContain(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(!result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } /// /// The controls. internal and protected internal are both reachable from a type in the same /// assembly, which is what the generated attribute is, so they stay parameters. /// - [Theory] - [InlineData("public int SizeLimit { get; set; }")] - [InlineData("internal int SizeLimit { get; set; }")] - [InlineData("protected internal int SizeLimit { get; set; }")] + [VerifyTest] + [Row("public int SizeLimit { get; set; }")] + [Row("internal int SizeLimit { get; set; }")] + [Row("protected internal int SizeLimit { get; set; }")] public void AReachableProperty_IsStillAParameter(string property) { var result = Run(property).AssertNoErrors(); - Assert.Contains("SizeLimit", result.SourceContaining("TestModule.Module")); - Assert.Contains(result.GeneratorDiagnostics, d => d.Id == "DM0018"); + Verify(result.SourceContaining("TestModule.Module").Contains("SizeLimit")); + Verify(result.GeneratorDiagnostics.Any(d => d.Id == "DM0018")); } private static GeneratorResult Run(string body) => diff --git a/tests/DependencyModules.Specs/Infrastructure/GeneratorTestHarness.cs b/tests/DependencyModules.Specs/Infrastructure/GeneratorTestHarness.cs index 399d2d8..285b08b 100644 --- a/tests/DependencyModules.Specs/Infrastructure/GeneratorTestHarness.cs +++ b/tests/DependencyModules.Specs/Infrastructure/GeneratorTestHarness.cs @@ -251,6 +251,17 @@ public static (MetadataReference Reference, System.Reflection.Assembly Assembly) bool runGenerator = false ) { + // The rows of one test run at the same time and compile the same library. A second copy + // would replace the first in the resolver, and a row that holds the first copy's types + // would then not find the services that the generated code registers against the second. + lock (LoadedLibraries) + { + if (TryGetLoadedLibrary(source, assemblyName, out var cached)) + { + return cached; + } + } + Compilation compilation = CSharpCompilation.Create( assemblyName, new[] @@ -286,26 +297,32 @@ public static (MetadataReference Reference, System.Reflection.Assembly Assembly) ); var bytes = stream.ToArray(); - var assembly = System.Reflection.Assembly.Load(bytes); // Assembly.Load(byte[]) puts it in the default context but does not make it discoverable by // name, so generated code referencing it fails to bind at run time. The resolver closes that. lock (LoadedLibraries) { + if (TryGetLoadedLibrary(source, assemblyName, out var loaded)) + { + return loaded; + } + // Two test classes compiling different libraries under one name is a trap worth being // loud about. The resolver below is keyed by name, so the second registration decides // what every earlier reference binds to at run time - and the tests that break are // whichever ones happened to run second, which is a failure that appears and disappears // with the filter you ran. Require.That( - !LibrarySources.TryGetValue(assemblyName, out var previousSource) - || previousSource == source, + !LibrarySources.ContainsKey(assemblyName), $"'{assemblyName}' was compiled more than once from different source. The runtime " + "resolver is keyed by assembly name, so one of them would silently stand in for the " + "other. Give each test class its own assembly name." ); + var assembly = System.Reflection.Assembly.Load(bytes); + LibrarySources[assemblyName] = source; + LibraryImages[assemblyName] = bytes; LoadedLibraries[assemblyName] = assembly; if (!_resolverHooked) @@ -324,13 +341,38 @@ public static (MetadataReference Reference, System.Reflection.Assembly Assembly) _resolverHooked = true; } + + return (MetadataReference.CreateFromImage(bytes), assembly); } + } - return (MetadataReference.CreateFromImage(bytes), assembly); + /// Call with the lock on held. + private static bool TryGetLoadedLibrary( + string source, + string assemblyName, + out (MetadataReference Reference, System.Reflection.Assembly Assembly) loaded + ) + { + if ( + LibrarySources.TryGetValue(assemblyName, out var loadedSource) + && loadedSource == source + ) + { + loaded = ( + MetadataReference.CreateFromImage(LibraryImages[assemblyName]), + LoadedLibraries[assemblyName] + ); + return true; + } + + loaded = default; + return false; } private static readonly Dictionary LoadedLibraries = new(); + private static readonly Dictionary LibraryImages = new(); + /// What each library name was compiled from, so a reused name is caught. private static readonly Dictionary LibrarySources = new();