From 52124ffc8d75e810dbae90d227eff19e764840b0 Mon Sep 17 00:00:00 2001 From: Brent Miller Date: Mon, 16 Nov 2026 14:33:27 -0600 Subject: [PATCH] test(analyzers): add branch coverage tests for the analyzer package Add 177 BranchCoverageTests files to E128.Analyzers.Tests. Branch coverage of the E128.Analyzers package surface rises from 72.0 to 87.2 percent. Document the nested worktree .globalconfig collision in the Lode and add a Branch Coverage Tests section to the analyzer testing note. Co-Authored-By: Claude --- lode/dotnet/analyzers/testing.md | 18 +- lode/infrastructure/agent-worktree-builds.md | 40 +- ...gressiveOptimizationBranchCoverageTests.cs | 124 +++ .../AlternateLookupBranchCoverageTests.cs | 205 ++++ ...AppSettingsKeyReaderBranchCoverageTests.cs | 79 ++ ...lSqliteParameterSizeBranchCoverageTests.cs | 159 +++ ...ParameterSizeCodeFixBranchCoverageTests.cs | 93 ++ .../AsyncDbIoBranchCoverageTests.cs | 183 ++++ ...merableConsumedTwiceBranchCoverageTests.cs | 162 ++++ .../AsyncFileIoBranchCoverageTests.cs | 183 ++++ .../AsyncSiblingCodeFixBranchCoverageTests.cs | 177 ++++ .../AwaitInFinallyBranchCoverageTests.cs | 59 ++ .../BareParseBranchCoverageTests.cs | 148 +++ ...aSizeCodeFixProviderBranchCoverageTests.cs | 142 +++ ...nwrapViaCastAnalyzerBranchCoverageTests.cs | 86 ++ .../CaptiveDependencyBranchCoverageTests.cs | 170 ++++ .../CatchFilterOceBranchCoverageTests.cs | 77 ++ ...ChainedStringReplaceBranchCoverageTests.cs | 236 +++++ .../ClosedHierarchyBranchCoverageTests.cs | 169 ++++ ...utationInEnumerationBranchCoverageTests.cs | 161 ++++ .../CollectionPathBranchCoverageTests.cs | 95 ++ ...parerSetConstructionBranchCoverageTests.cs | 128 +++ .../ComplexityCeilingBranchCoverageTests.cs | 603 ++++++++++++ ...lexityCeilingCodeFixBranchCoverageTests.cs | 431 +++++++++ ...DetectionSpecificityBranchCoverageTests.cs | 75 ++ ...ationCodeFixProviderBranchCoverageTests.cs | 128 +++ ...eDiDependencyCodeFixBranchCoverageTests.cs | 58 ++ ...pendencyCodeFixNoiseBranchCoverageTests.cs | 97 ++ .../ConcurrencyLimitBranchCoverageTests.cs | 164 ++++ ...currencyLimitCodeFixBranchCoverageTests.cs | 84 ++ ...oncurrencyLimitShapeBranchCoverageTests.cs | 117 +++ ...ctionaryDoubleLookupBranchCoverageTests.cs | 110 +++ ...uctorNewDiRegisteredBranchCoverageTests.cs | 137 +++ ...teTimeParseRoundtripBranchCoverageTests.cs | 51 + ...ationCodeFixProviderBranchCoverageTests.cs | 160 +++ .../DiskIoCatalogBranchCoverageTests.cs | 123 +++ .../DiskIoCatalogHelperBranchCoverageTests.cs | 505 ++++++++++ .../DiskRoundtripBranchCoverageTests.cs | 311 ++++++ ...DiskRoundtripCodeFixBranchCoverageTests.cs | 104 ++ ...isposableFieldInLoopBranchCoverageTests.cs | 121 +++ ...ableSingletonFactoryBranchCoverageTests.cs | 115 +++ ...cateJsonPropertyNameBranchCoverageTests.cs | 218 +++++ .../EfQueryInLoopBranchCoverageTests.cs | 153 +++ ...lementLoopToBulkSpanBranchCoverageTests.cs | 428 +++++++++ ...oopToBulkSpanCodeFixBranchCoverageTests.cs | 167 ++++ .../EnclosingBodyBranchCoverageTests.cs | 55 ++ ...ChainCodeFixProviderBranchCoverageTests.cs | 110 +++ ...ventSubscriptionLeakBranchCoverageTests.cs | 187 ++++ .../ExclusiveBranchesBranchCoverageTests.cs | 53 + ...GuardCodeFixProviderBranchCoverageTests.cs | 47 + .../FileInfoToctouBranchCoverageTests.cs | 137 +++ ...ileInfoToctouCodeFixBranchCoverageTests.cs | 102 ++ ...treamWithoutUseAsyncBranchCoverageTests.cs | 56 ++ ...leSystemPathAnalyzerBranchCoverageTests.cs | 269 ++++++ ...ileSystemPathCodeFixBranchCoverageTests.cs | 69 ++ ...yBlockCleanupCodeFixBranchCoverageTests.cs | 72 ++ .../FipsAesGcmTagSizeBranchCoverageTests.cs | 59 ++ .../FipsCipherModeBranchCoverageTests.cs | 108 +++ ...sDirectInstantiationBranchCoverageTests.cs | 173 ++++ ...rbiddenAlgorithmNameBranchCoverageTests.cs | 164 ++++ ...psHashNameResolutionBranchCoverageTests.cs | 330 +++++++ .../FipsHmacKeyLengthBranchCoverageTests.cs | 376 ++++++++ .../FipsPbkdfIterationBranchCoverageTests.cs | 258 +++++ .../FipsRsaKeySizeBranchCoverageTests.cs | 414 ++++++++ .../FipsSha3BranchCoverageTests.cs | 99 ++ .../FipsTlsVersionBranchCoverageTests.cs | 185 ++++ .../FipsUnapprovedHashBranchCoverageTests.cs | 506 ++++++++++ ...napprovedHashCodeFixBranchCoverageTests.cs | 96 ++ .../FixSyntaxBranchCoverageTests.cs | 206 ++++ ...FieldCodeFixProviderBranchCoverageTests.cs | 114 +++ ...ringMutationAnalyzerBranchCoverageTests.cs | 192 ++++ .../GcHandleFreeBranchCoverageTests.cs | 170 ++++ .../GeneratedRegexBranchCoverageTests.cs | 330 +++++++ ...eneratedRegexCodeFixBranchCoverageTests.cs | 293 ++++++ ...eneratedRegexHelpersBranchCoverageTests.cs | 255 +++++ ...AttributeElementTypeBranchCoverageTests.cs | 273 ++++++ .../GetBufferNotVisibleBranchCoverageTests.cs | 212 ++++ ...RolledProcessCaptureBranchCoverageTests.cs | 729 ++++++++++++++ ...ndlerNoDecompressionBranchCoverageTests.cs | 82 ++ .../HardcodedSecretBranchCoverageTests.cs | 196 ++++ .../HardcodedUrlBranchCoverageTests.cs | 82 ++ ...ReadWithoutSizeBoundBranchCoverageTests.cs | 261 +++++ ...entCertificateBypassBranchCoverageTests.cs | 180 ++++ ...lientInfiniteTimeoutBranchCoverageTests.cs | 83 ++ ...lientMissingOceCatchBranchCoverageTests.cs | 181 ++++ ...mmutableArrayDefaultBranchCoverageTests.cs | 92 ++ ...StateMachineAnalyzerBranchCoverageTests.cs | 469 +++++++++ .../InModifierHelperBranchCoverageTests.cs | 66 ++ ...oSearchValuesCodeFixBranchCoverageTests.cs | 113 +++ .../IndexedForLoopBranchCoverageTests.cs | 62 ++ ...itializerAssignmentsBranchCoverageTests.cs | 40 + ...andomInCryptoContextBranchCoverageTests.cs | 182 ++++ ...CryptoContextCodeFixBranchCoverageTests.cs | 58 ++ .../InterfaceMembersBranchCoverageTests.cs | 176 ++++ ...JsonDocumentLifetimeBranchCoverageTests.cs | 227 +++++ .../LargeStructByValueBranchCoverageTests.cs | 539 +++++++++++ ...azyFieldThreadSafetyBranchCoverageTests.cs | 119 +++ .../LinearLookupInLoopBranchCoverageTests.cs | 307 ++++++ ...rLookupInLoopCodeFixBranchCoverageTests.cs | 119 +++ .../LoggerArgumentGuardBranchCoverageTests.cs | 384 ++++++++ ...ArgumentGuardCodeFixBranchCoverageTests.cs | 51 + .../LoopContextBranchCoverageTests.cs | 362 +++++++ .../LoopCountBranchCoverageTests.cs | 236 +++++ ...LowValueTestAnalyzerBranchCoverageTests.cs | 128 +++ ...eTestCodeFixProviderBranchCoverageTests.cs | 102 ++ .../ManualBitCountBranchCoverageTests.cs | 190 ++++ ...raitCategoryAnalyzerBranchCoverageTests.cs | 129 +++ .../MonthTimeSpanBranchCoverageTests.cs | 188 ++++ ...tionExposureAnalyzerBranchCoverageTests.cs | 107 +++ ...ArrayCodeFixProviderBranchCoverageTests.cs | 126 +++ .../NamespacesBranchCoverageTests.cs | 44 + ...StyleCodeFixProviderBranchCoverageTests.cs | 129 +++ ...clReflectionAnalyzerBranchCoverageTests.cs | 88 ++ .../NullByRefAnalyzerBranchCoverageTests.cs | 144 +++ .../OceWhenTokenFilterBranchCoverageTests.cs | 72 ++ .../OptionsBindInitBranchCoverageTests.cs | 147 +++ ...tionsBindInitCodeFixBranchCoverageTests.cs | 104 ++ ...ationMissingAnalyzerBranchCoverageTests.cs | 349 +++++++ .../OrderByFirstBranchCoverageTests.cs | 145 +++ ...allelCollectionIndexBranchCoverageTests.cs | 216 +++++ ...allelForEachAsyncCapBranchCoverageTests.cs | 111 +++ .../PathCombineSegmentBranchCoverageTests.cs | 84 ++ ...mportEphemeralKeySetBranchCoverageTests.cs | 89 ++ .../PollingLoopNoTokenBranchCoverageTests.cs | 128 +++ ...oolRentCapacityGuardBranchCoverageTests.cs | 281 ++++++ .../PooledBufferZeroingBranchCoverageTests.cs | 127 +++ ...FieldCodeFixProviderBranchCoverageTests.cs | 82 ++ ...ocessOutputValidatorBranchCoverageTests.cs | 176 ++++ ...tputValidatorCodeFixBranchCoverageTests.cs | 104 ++ ...essStartInfoArgumentBranchCoverageTests.cs | 93 ++ ...tInfoArgumentCodeFixBranchCoverageTests.cs | 161 ++++ ...orAllMaterializationBranchCoverageTests.cs | 135 +++ ...ReadOnlyMemoryStreamBranchCoverageTests.cs | 267 +++++ ...leCollectionEqualityBranchCoverageTests.cs | 81 ++ .../RecursiveDeleteRootBranchCoverageTests.cs | 908 ++++++++++++++++++ ...timeRegexToGeneratedBranchCoverageTests.cs | 196 ++++ .../SaveChangesInLoopBranchCoverageTests.cs | 174 ++++ ...SemaphoreSlimReleaseBranchCoverageTests.cs | 576 +++++++++++ ...SensitiveLogArgumentBranchCoverageTests.cs | 167 ++++ .../SequenceEqualLoopBranchCoverageTests.cs | 412 ++++++++ ...RenameFixAllProviderBranchCoverageTests.cs | 161 ++++ .../SortInLoopBranchCoverageTests.cs | 176 ++++ .../StackAllocSafetyBranchCoverageTests.cs | 170 ++++ ...ceAssembliesAnalyzerBranchCoverageTests.cs | 70 ++ .../StatementExitsBranchCoverageTests.cs | 30 + ...ementCodeFixProviderBranchCoverageTests.cs | 160 +++ ...gConcatInLoopCodeFixBranchCoverageTests.cs | 462 +++++++++ ...ormatToInterpolationBranchCoverageTests.cs | 274 ++++++ ...tringLengthUnderflowBranchCoverageTests.cs | 103 ++ ...haustivenessAnalyzerBranchCoverageTests.cs | 156 +++ ...yncLocalFunctionCallBranchCoverageTests.cs | 69 ++ ...AsyncCodeFixProviderBranchCoverageTests.cs | 109 +++ ...pletionSourceOptionsBranchCoverageTests.cs | 257 +++++ ...TaskFromResultSyncIoBranchCoverageTests.cs | 221 +++++ ...cellationPropagationBranchCoverageTests.cs | 251 +++++ ...onPropagationCodeFixBranchCoverageTests.cs | 56 ++ ...mpDirCleanupAnalyzerBranchCoverageTests.cs | 163 ++++ ...odReflectionAnalyzerBranchCoverageTests.cs | 118 +++ .../TextContentGuardBranchCoverageTests.cs | 160 +++ ...TimingSafeComparisonBranchCoverageTests.cs | 219 +++++ ...afeComparisonCodeFixBranchCoverageTests.cs | 99 ++ .../TypeSymbolsBranchCoverageTests.cs | 98 ++ ...UnboundedTaskWhenAllBranchCoverageTests.cs | 266 +++++ .../UncontainedRootJoinBranchCoverageTests.cs | 264 +++++ ...ainedRootJoinCodeFixBranchCoverageTests.cs | 100 ++ .../UnguardedSplitIndexBranchCoverageTests.cs | 228 +++++ .../UnionTypesBranchCoverageTests.cs | 71 ++ ...ionValueReadAnalyzerBranchCoverageTests.cs | 126 +++ ...steredServiceResolveBranchCoverageTests.cs | 349 +++++++ ...sionsCodeFixProviderBranchCoverageTests.cs | 110 +++ .../UntimedProcessExitBranchCoverageTests.cs | 152 +++ ...ParamCodeFixProviderBranchCoverageTests.cs | 78 ++ ...validatedJwtIdentityBranchCoverageTests.cs | 763 +++++++++++++++ .../UseAfterDisposeBranchCoverageTests.cs | 123 +++ .../UsingDirectivesBranchCoverageTests.cs | 93 ++ .../Utf8GetBytesLiteralBranchCoverageTests.cs | 252 +++++ ...nAnyResultUnobservedBranchCoverageTests.cs | 93 ++ .../WordSplitterBranchCoverageTests.cs | 35 + .../XunitTestHelperBranchCoverageTests.cs | 163 ++++ 179 files changed, 32313 insertions(+), 15 deletions(-) create mode 100644 tests/E128.Analyzers.Tests/AggressiveOptimizationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AlternateLookupBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AsyncDbIoBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AsyncFileIoBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AsyncSiblingCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/AwaitInFinallyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/BareParseBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ByteSizeForDataSizeCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/CatchFilterOceBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ChainedStringReplaceBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/CollectionMutationInEnumerationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/CollectionPathBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ComparerSetConstructionBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ComplexityCeilingCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/CompositeDetectionSpecificityBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixNoiseBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcurrencyLimitBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcurrencyLimitCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcurrencyLimitShapeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ConstructorNewDiRegisteredBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DateTimeParseRoundtripBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DiskIoCatalogBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DiskIoCatalogHelperBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DiskRoundtripCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DisposableFieldInLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DisposableSingletonFactoryBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/EfQueryInLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ElementLoopToBulkSpanBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ElementLoopToBulkSpanCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/EnclosingBodyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/EventSubscriptionLeakBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ExclusiveBranchesBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ExecuteScalarNullGuardCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FileInfoToctouCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FileSystemPathCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FinallyBlockCleanupCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsAesGcmTagSizeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsCipherModeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsDirectInstantiationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsForbiddenAlgorithmNameBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsHashNameResolutionBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsHmacKeyLengthBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsPbkdfIterationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsRsaKeySizeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsSha3BranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsTlsVersionBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsUnapprovedHashBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FipsUnapprovedHashCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FixSyntaxBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GcHandleFreeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GeneratedRegexBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GeneratedRegexCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GetAttributeElementTypeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/GetBufferNotVisibleBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HandRolledProcessCaptureBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HandlerNoDecompressionBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HardcodedSecretBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HardcodedUrlBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HttpClientInfiniteTimeoutBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/HttpClientMissingOceCatchBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ImmutableArrayDefaultBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/InModifierHelperBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/IndexOfAnyToSearchValuesCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/IndexedForLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/InitializerAssignmentsBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/InterfaceMembersBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/JsonDocumentLifetimeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LargeStructByValueBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LazyFieldThreadSafetyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LinearLookupInLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LoggerArgumentGuardBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LoggerArgumentGuardCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LoopContextBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LoopCountBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/LowValueTestCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ManualBitCountBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/MonthTimeSpanBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/NamespacesBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/NamingStyleCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/NonPublicBclReflectionAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/OceWhenTokenFilterBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/OptionsBindInitBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/OptionsBindInitCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/OrderByFirstBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ParallelCollectionIndexBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ParallelForEachAsyncCapBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PathCombineSegmentBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PollingLoopNoTokenBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PoolRentCapacityGuardBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PooledBufferZeroingBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/PrimaryConstructorBackingFieldCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ProcessOutputValidatorBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ProcessStartInfoArgumentBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ProcessStartInfoArgumentCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/RecursiveDeleteRootBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/RuntimeRegexToGeneratedBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SaveChangesInLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SemaphoreSlimReleaseBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SensitiveLogArgumentBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SequenceEqualLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SortInLoopBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StackAllocSafetyBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StaleReferenceAssembliesAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StatementExitsBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/StringFormatToInterpolationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SubstringLengthUnderflowBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SyncLocalFunctionCallBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/SyncOverAsyncCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TaskFromResultSyncIoBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TestMethodReflectionAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TextContentGuardBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TimingSafeComparisonCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/TypeSymbolsBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnboundedTaskWhenAllBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UncontainedRootJoinBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnguardedSplitIndexBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnionTypesBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnionValueReadAnalyzerBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnregisteredServiceResolveBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UntimedProcessExitBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnusedInterfaceParamCodeFixProviderBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UseAfterDisposeBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/UsingDirectivesBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/Utf8GetBytesLiteralBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/WhenAnyResultUnobservedBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/WordSplitterBranchCoverageTests.cs create mode 100644 tests/E128.Analyzers.Tests/XunitTestHelperBranchCoverageTests.cs diff --git a/lode/dotnet/analyzers/testing.md b/lode/dotnet/analyzers/testing.md index a03d88a7..a9b581f1 100644 --- a/lode/dotnet/analyzers/testing.md +++ b/lode/dotnet/analyzers/testing.md @@ -1,6 +1,6 @@ # Analyzer Testing -*Updated: 2026-11-12T13:55:10Z* +*Updated: 2026-11-16T20:16:49Z* How a test drives an analyzer and a code fix. The harness types live in `Microsoft.CodeAnalysis.CSharp.Testing`. The repo wrapper lives in @@ -144,6 +144,22 @@ confirm the test count in the run output. - xUnit v3 runs on the Microsoft Testing Platform. Only `scripts/test.sh` works. +## Branch Coverage Tests + +A file named `BranchCoverageTests.cs` closes the branches that the rule +tests leave open. One file targets one analyzer, code fix provider, or helper +class. Each test asserts a reported diagnostic or a fix result. + +A branch that no valid input reaches gets no test. Two examples are the +`context is null` guard in `Initialize` and a null syntax root in a fix +provider. Do not pin a production defect as expected behavior. Report it +instead. + +The NuGet package `E128.Analyzers` carries two assemblies: `E128.Analyzers` and +`E128.Analyzers.CodeFixers`. Add their branch totals to get the package surface. +As of 2026-11-16, that surface covers about 87 percent of its branches. See +[Code Coverage](../code-coverage.md) for collection and the CI floors. + ## Related - [New Analyzer Checklist](new-analyzer-checklist.md): pitfalls and gates diff --git a/lode/infrastructure/agent-worktree-builds.md b/lode/infrastructure/agent-worktree-builds.md index ed9b0feb..e987c9e8 100644 --- a/lode/infrastructure/agent-worktree-builds.md +++ b/lode/infrastructure/agent-worktree-builds.md @@ -1,5 +1,5 @@ # Agent Worktree Builds -*Updated: 2026-11-05T04:06:10Z* +*Updated: 2026-11-16T20:16:49Z* A subagent spawned with worktree isolation lands under `.claude/worktrees/agent-/`. That worktree holds a full copy of the @@ -7,26 +7,38 @@ repository and a branch of its own. ## Verified Behavior -These runs build clean at the same commit: - -- `scripts/build.sh --project E128.Analyzers` in a nested worktree. -- `scripts/build.sh --project E128.Analyzers.Tests` in a nested worktree. -- The same two builds, run side by side in two worktrees at once. - `ArtifactsPath` resolves through `$(MSBuildThisFileDirectory)`, so each worktree writes its own `artifacts/` directory. Concurrent builds do not share output. -## The Unreproduced Failure +A build that finds current output in `artifacts/` skips compilation and +reports success. That result does not show that the worktree compiles. + +## The Nested Globalconfig Collision -One batch of five delegated agents each reported about 500 errors in files they -did not touch: CS1591, S3267, and S3358. A direct probe did not reproduce it, so -the cause stays unknown. Do not record a cause for it without a reproduction. +A forced rebuild in a nested worktree fails with phantom errors in files nobody +touched. A rebuild of `E128.Analyzers` with `-t:Rebuild` reports RS0016, CS1591, +RS0017, S3267, IDE0046, and S3358. + +The SDK targets (`Microsoft.Managed.Core.targets`) add the `.globalconfig` of +every ancestor directory to `GlobalAnalyzerConfigFiles`. A nested worktree +therefore loads two files: its own and the primary checkout root file. Both set +`global_level = 100`. Roslyn drops the keys that two global configs set at the +same level. The rules that the file sets to `none` then fall back to the +blanket error severity. + +Check the evaluation with +`dotnet msbuild -getItem:EditorConfigFiles` and look for both root +`.globalconfig` paths. ## Dispatch Rule -Treat a phantom error report from a delegated agent as suspect. Discard its -build log and build in the primary checkout instead. The parent holds the -merged tree, and one build there costs less than five worktree builds. +Do not build or test inside a nested worktree. Treat an error report from a +worktree agent as this collision until the evaluation shows one root file. + +Run delegated test writers in the primary checkout, one agent at a time, +because builds share `artifacts/`. A worktree outside the repository tree has +no ancestor root `.globalconfig`, so the collision cannot occur there. Do not +edit `global_level` or add a targets file to bypass the collision. Give each agent write access to its own new files only. The parent edits the shared surfaces: `src/E128.Analyzers/README.md`, diff --git a/tests/E128.Analyzers.Tests/AggressiveOptimizationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AggressiveOptimizationBranchCoverageTests.cs new file mode 100644 index 00000000..dcf6cde9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/AggressiveOptimizationBranchCoverageTests.cs @@ -0,0 +1,124 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AggressiveOptimizationBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_ForOtherAttributesAndAnAttributeWithoutArguments() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Runtime.CompilerServices; + class C + { + [Obsolete("old")] + void First() + { + } + + [MethodImpl] + void Second() + { + } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheRightOptionWhenTheLeftOneIsRemoved() + { + return VerifyFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + [{|E128116:MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)|}] + void M() + { + } + } + """, + """ + using System.Runtime.CompilerServices; + class C + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void M() + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RemovesOnlyTheAttributeWhenTheListHoldsSeveral() + { + return VerifyFixAsync( + """ + using System; + using System.Runtime.CompilerServices; + class C + { + [Obsolete, {|E128116:MethodImpl(MethodImplOptions.AggressiveOptimization)|}] + void M() + { + } + } + """, + """ + using System; + using System.Runtime.CompilerServices; + class C + { + [Obsolete] + void M() + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RemovesALaterAttributeList() + { + return VerifyFixAsync( + """ + using System; + using System.Runtime.CompilerServices; + class C + { + [Obsolete] + [{|E128116:MethodImpl(MethodImplOptions.AggressiveOptimization)|}] + void M() + { + } + } + """, + """ + using System; + using System.Runtime.CompilerServices; + class C + { + [Obsolete] + void M() + { + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AlternateLookupBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AlternateLookupBranchCoverageTests.cs new file mode 100644 index 00000000..c57aa0f5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/AlternateLookupBranchCoverageTests.cs @@ -0,0 +1,205 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AlternateLookupBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + var code = "using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\n\n" + + "class C\n{\n" + + members + + "}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("")] + [InlineData("StringComparer.Ordinal")] + [InlineData("EqualityComparer.Default")] + public Task Reports_ForALocalWithADefaultOrOrdinalComparer(string comparer) + { + return VerifyAsync($$""" + int Lookup(ReadOnlySpan key) + { + var cache = new Dictionary({{comparer}}); + return cache[{|E128133:new string(key)|}]; + } + + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("StringComparer.OrdinalIgnoreCase")] + [InlineData("StringComparer.InvariantCulture")] + [InlineData("comparer")] + [InlineData("4, StringComparer.Ordinal")] + public Task Silent_ForALocalWithAnotherComparer(string comparer) + { + return VerifyAsync($$""" + int Lookup(ReadOnlySpan key, IEqualityComparer comparer) + { + var cache = new Dictionary({{comparer}}); + return cache[new string(key)]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAFieldHoldingACollectionExpression() + { + return VerifyAsync(""" + private readonly HashSet _names = []; + + bool Has(ReadOnlySpan key) + { + return _names.Contains({|E128133:new string(key)|}); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForConcurrentDictionaryLookups() + { + return VerifyAsync(""" + private readonly ConcurrentDictionary _cache = new(); + + int Lookup(ReadOnlySpan key) + { + _ = _cache.TryGetValue({|E128133:new string(key)|}, out var value); + return _cache[{|E128133:new string(key)|}] + value; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAddAndRemoveOnAStringSet() + { + return VerifyAsync(""" + private readonly HashSet _names = new(); + + void Update(ReadOnlySpan key) + { + _ = _names.Add({|E128133:new string(key)|}); + _ = _names.Remove({|E128133:new string(key)|}); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsAParameterOrHasNoInitializer() + { + return VerifyAsync(""" + int FromParameter(Dictionary cache, ReadOnlySpan key) + { + return cache[new string(key)]; + } + + int NoInitializer(ReadOnlySpan key) + { + Dictionary cache; + cache = new(); + return cache[new string(key)]; + } + + int FromCall(ReadOnlySpan key) + { + var cache = Create(); + return cache[new string(key)]; + } + + static Dictionary Create() => new(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsNotAPlainName() + { + return VerifyAsync(""" + private readonly Dictionary _cache = new(); + + Dictionary Get() => _cache; + + int Lookup(ReadOnlySpan key) + { + return this._cache[new string(key)] + Get()[new string(key)]; + } + + bool Has(ReadOnlySpan key) + { + return this._cache.ContainsKey(new string(key)); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCollectionIsNotStringKeyed() + { + return VerifyAsync(""" + private readonly Dictionary _numbers = new(); + + private readonly HashSet _set = new(); + + private readonly List _list = new(); + + bool Has(ReadOnlySpan key) + { + return _numbers.ContainsKey(new string(key).Length) + || _set.Contains(new string(key).Length) + || _list.Contains(new string(key)); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMemberTakesAValueOrNoArguments() + { + return VerifyAsync(""" + private readonly Dictionary _cache = new(); + + bool Has(ReadOnlySpan key) + { + _cache.Clear(); + return _cache.ContainsValue(new string(key).Length); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheKeyDoesNotCopyAWholeSpanOrArray() + { + return VerifyAsync(""" + private readonly Dictionary _cache = new(); + + int Lookup(Span mutable, char letter, string text, ReadOnlySpan span) + { + return _cache[new string(mutable)] + + _cache[new string(letter, 3)] + + _cache[new string(span).Trim()] + + _cache[new(span)] + + _cache[text]; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageTests.cs new file mode 100644 index 00000000..96f1fe7c --- /dev/null +++ b/tests/E128.Analyzers.Tests/AppSettingsKeyReaderBranchCoverageTests.cs @@ -0,0 +1,79 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AppSettingsKeyReaderBranchCoverageTests +{ + private static Task VerifyAsync(string json, string read) + { + return AnalyzerTestRunner.VerifyAsync( + $$""" + using Microsoft.Extensions.Configuration; + class C + { + string? M(IConfiguration configuration) => {{read}}; + } + namespace Microsoft.Extensions.Configuration + { + public interface IConfiguration + { + string? this[string key] { get; set; } + } + } + """, + options: new AnalyzerTestOptions { AdditionalFiles = [("appsettings.json", json)] }); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("-12.34e+56")] + [InlineData("0.0E-1")] + [InlineData("false")] + [InlineData("\"\\b\\f\\n\\r\\t\\/\\u0041\"")] + [InlineData("[ ]")] + [InlineData("{ }")] + [InlineData("1 // comment")] + public Task ReportsMissingKey_WhenSettingsContainAValidValue(string value) + { + return VerifyAsync("{ \"Known\": " + value + "\n}", "{|E128195:configuration[\"Missing\"]|}"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("-")] + [InlineData("1e")] + [InlineData("1e+")] + [InlineData("1eX")] + [InlineData("1.2e-")] + [InlineData("\"\\u12\"")] + [InlineData("\"\\uZZZZ\"")] + [InlineData("\"\\q\"")] + [InlineData("[1 2]")] + [InlineData("[1,")] + public Task Silent_WhenSettingsAreMalformed(string value) + { + return VerifyAsync("{ \"Known\": " + value + " }", "configuration[\"Missing\"]"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnEscapedPropertyNameMatchesTheKey() + { + return VerifyAsync( + //lang=json + """{ "\u004bnown": 1 }""", + "configuration[\"Known\"]"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnArrayIndexIsPresent() + { + return VerifyAsync( + //lang=json + """[ 0, { "Name": true } ]""", + "configuration[\"1:Name\"]"); + } +} diff --git a/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeBranchCoverageTests.cs new file mode 100644 index 00000000..de07a8ca --- /dev/null +++ b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeBranchCoverageTests.cs @@ -0,0 +1,159 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ArrayPoolSqliteParameterSizeBranchCoverageTests +{ + private const string Preamble = """ + using System; + using System.Buffers; + using Microsoft.Data.Sqlite; + namespace Microsoft.Data.Sqlite + { + public class SqliteParameter { public object Value { get; set; } public int Size { get; set; } } + public class SqliteParameterCollection + { + public SqliteParameter AddWithValue(string name, object value) => new SqliteParameter(); + public SqliteParameter AddWithValue(string name, object value, int size) => new SqliteParameter(); + } + public class SqliteCommand { public SqliteParameterCollection Parameters { get; } = new SqliteParameterCollection(); } + } + class OtherCollection { public void AddWithValue(string name, object value) { } } + class Holder { public object Value { get; set; } public object Field; } + class Pool { public static T[] Rent(int size) => new T[size]; } + class Plain { public static byte[] Rent(int size) => new byte[size]; } + """; + + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + Preamble + "\nclass C\n{\n void M(byte[] argument)\n {\n var cmd = new SqliteCommand();\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTheThreeArgumentAddWithValueOverload() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + cmd.Parameters.AddWithValue("@p", buffer, 4); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAddWithValueOnAnotherCollectionType() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + new OtherCollection().AddWithValue("@p", buffer); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueIsNotALocalBuffer() + { + return VerifyAsync(""" + cmd.Parameters.AddWithValue("@p", ArrayPool.Shared.Rent(8)); + cmd.Parameters.AddWithValue("@p", argument); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalDoesNotComeFromArrayPoolRent() + { + return VerifyAsync(""" + byte[] declared; + declared = ArrayPool.Shared.Rent(8); + var viaAlias = argument; + var viaPool = Pool.Rent(8); + var viaPlain = Plain.Rent(8); + var viaShared = ArrayPool.Shared.Rent(8).AsSpan().ToArray(); + cmd.Parameters.AddWithValue("@a", declared); + cmd.Parameters.AddWithValue("@b", viaAlias); + cmd.Parameters.AddWithValue("@c", viaPool); + cmd.Parameters.AddWithValue("@d", viaPlain); + cmd.Parameters.AddWithValue("@e", viaShared); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResultIsAssignedAndNoSizeFollows() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + SqliteParameter parameter; + parameter = {|E128086:cmd.Parameters.AddWithValue("@p", buffer)|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAssignedResultReceivesASizeLater() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + SqliteParameter parameter; + parameter = cmd.Parameters.AddWithValue("@p", buffer); + parameter.Size = 8; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSizeIsSetBeforeTheCallOrOnAnotherParameter() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + var other = new SqliteParameter(); + var parameter = new SqliteParameter(); + parameter.Size = 8; + var added = {|E128086:cmd.Parameters.AddWithValue("@p", buffer)|}; + other.Size = 8; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValuePropertyIsFollowedByASize() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + var parameter = new SqliteParameter(); + parameter.Value = buffer; + parameter.Size = 8; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForValueAssignmentsOnOtherTypesAndMembers() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + var holder = new Holder(); + holder.Value = buffer; + holder.Field = buffer; + var parameter = new SqliteParameter(); + parameter.Value = new byte[8]; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherParameterReceivesTheSizeAfterTheValue() + { + return VerifyAsync(""" + var buffer = ArrayPool.Shared.Rent(8); + var first = new SqliteParameter(); + var second = new SqliteParameter(); + {|E128086:first.Value = buffer|}; + second.Size = 8; + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..f660c251 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ArrayPoolSqliteParameterSizeCodeFixBranchCoverageTests.cs @@ -0,0 +1,93 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ArrayPoolSqliteParameterSizeCodeFixBranchCoverageTests +{ + private const string Preamble = """ + using System.Buffers; + using Microsoft.Data.Sqlite; + namespace Microsoft.Data.Sqlite + { + public class SqliteParameter { public object Value { get; set; } public int Size { get; set; } } + public class SqliteParameterCollection { public SqliteParameter AddWithValue(string name, object value) => new SqliteParameter(); } + public class SqliteCommand { public SqliteParameterCollection Parameters { get; } = new SqliteParameterCollection(); } + } + """; + + private static Task VerifyFixAsync(string body, string fixedBody) + { + return CodeFixTestRunner.RunAsync( + Wrap(body), + Wrap(fixedBody)); + } + + private static string Wrap(string body) + { + return Preamble + "\nclass C\n{\n void M(bool flag, SqliteParameter parameter)\n {\n" + + " var buffer = ArrayPool.Shared.Rent(16);\n var cmd = new SqliteCommand();\n" + + body + "\n }\n}\n"; + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_PicksTheNextFreeParameterName() + { + return VerifyFixAsync( + """ + var sqliteParam = 1; + _ = {|E128086:cmd.Parameters.AddWithValue("@p", buffer)|}; + """, + """ + var sqliteParam = 1; + var sqliteParam2 = cmd.Parameters.AddWithValue("@p", buffer); + sqliteParam2.Size = 16; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_SkipsEveryTakenParameterName() + { + return VerifyFixAsync( + """ + var sqliteParam = 1; + var sqliteParam2 = 2; + _ = {|E128086:cmd.Parameters.AddWithValue("@p", buffer)|}; + """, + """ + var sqliteParam = 1; + var sqliteParam2 = 2; + var sqliteParam3 = cmd.Parameters.AddWithValue("@p", buffer); + sqliteParam3.Size = 16; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsAnAssignmentThatUsesTheResult() + { + return VerifyFixAsync( + """ + parameter = {|E128086:cmd.Parameters.AddWithValue("@p", buffer)|}; + """, + """ + var sqliteParam = cmd.Parameters.AddWithValue("@p", buffer); + sqliteParam.Size = 16; + parameter = sqliteParam; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheBufferIsReassigned() + { + return CodeFixTestRunner.NoFixAsync( + Wrap(""" + buffer = ArrayPool.Shared.Rent(32); + {|E128086:parameter.Value = buffer|}; + """)); + } +} diff --git a/tests/E128.Analyzers.Tests/AsyncDbIoBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AsyncDbIoBranchCoverageTests.cs new file mode 100644 index 00000000..09940e35 --- /dev/null +++ b/tests/E128.Analyzers.Tests/AsyncDbIoBranchCoverageTests.cs @@ -0,0 +1,183 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AsyncDbIoBranchCoverageTests +{ + private const string Prefix = """ + using System; + using System.Data; + using System.Data.Common; + using System.Threading.Tasks; + + sealed class FakeConnection : DbConnection + { + public override string ConnectionString { get; set; } = string.Empty; + public override string Database => string.Empty; + public override string DataSource => string.Empty; + public override string ServerVersion => string.Empty; + public override ConnectionState State => ConnectionState.Closed; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + public void Ping() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => throw new NotSupportedException(); + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + Prefix + "\n" + code, + options: new AnalyzerTestOptions { MarkupOptions = MarkupOptions.UseFirstDescriptor }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForASyncLambdaInsideAnAsyncMethod() + { + return VerifyAsync(""" + class C + { + async Task M(FakeConnection connection) + { + await Task.Yield(); + Action open = () => {|E128093:connection.Open()|}; + open(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAConstructorAndInSyncLocalFunctionAndAnonymousMethod() + { + return VerifyAsync(""" + class C + { + public C(FakeConnection connection) + { + {|E128093:connection.Open()|}; + } + + void M(FakeConnection connection) + { + void Local() => {|E128093:connection.Open()|}; + Action anon = delegate { {|E128093:connection.Open()|}; }; + Local(); + anon(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_InsideAsyncLocalFunctionAndAsyncLambdas() + { + return VerifyAsync(""" + class C + { + void M(FakeConnection connection) + { + async Task Local() { await Task.Yield(); connection.Open(); } + Func simple = async () => { await Task.Yield(); connection.Open(); }; + Func single = async x => { await Task.Yield(); connection.Open(); }; + Func anon = async delegate { await Task.Yield(); connection.Open(); }; + _ = (Local(), simple, single, anon); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAConditionalAccessCall() + { + return VerifyAsync(""" + class C + { + void M(FakeConnection? connection) + { + connection?{|E128093:.Open()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAConditionalAccessCallThatAlreadyUsesAsync() + { + return VerifyAsync(""" + class C + { + void M(FakeConnection? connection) + { + _ = connection?.OpenAsync(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNameofAndAnAlreadyAsyncCall() + { + return VerifyAsync(""" + class C + { + void M(FakeConnection connection) + { + var name = nameof(connection); + _ = connection.OpenAsync(); + _ = name; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAMethodWithoutAnAsyncSibling() + { + return VerifyAsync(""" + class C + { + void M(FakeConnection connection) + { + connection.Ping(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForATypeNamedDbConnectionOutsideTheDataNamespace() + { + return VerifyAsync(""" + namespace Other + { + class DbConnection + { + public void Open() { } + public Task OpenAsync() => Task.CompletedTask; + } + + class C + { + void M(DbConnection connection) + { + connection.Open(); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceBranchCoverageTests.cs new file mode 100644 index 00000000..488ca9fa --- /dev/null +++ b/tests/E128.Analyzers.Tests/AsyncEnumerableConsumedTwiceBranchCoverageTests.cs @@ -0,0 +1,162 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AsyncEnumerableConsumedTwiceBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAnExpressionBodiedMethod() + { + return VerifyAsync(""" + class C + { + (IAsyncEnumerator, IAsyncEnumerator) M(IAsyncEnumerable source) => + (source.GetAsyncEnumerator(), {|E128182:source|}.GetAsyncEnumerator()); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAnExpressionBodiedLocalFunctionAndAccessor() + { + return VerifyAsync(""" + class C + { + IAsyncEnumerable Source = default!; + + void M(IAsyncEnumerable source) + { + (IAsyncEnumerator, IAsyncEnumerator) Local() => + (source.GetAsyncEnumerator(), {|E128182:source|}.GetAsyncEnumerator()); + _ = Local(); + } + + int Other + { + get => Take(this.Source.GetAsyncEnumerator(), {|E128182:this.Source|}.GetAsyncEnumerator()); + } + + static int Take(IAsyncEnumerator a, IAsyncEnumerator b) => 0; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ThroughParenthesesAndConfigureAwait() + { + return VerifyAsync(""" + class C + { + async Task M(IAsyncEnumerable source) + { + await foreach (var item in (source)) + { + } + + await foreach (var item in ({|E128182:source|}).ConfigureAwait(false)) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForALocalWhoseTypeImplementsTheInterface() + { + return VerifyAsync(""" + sealed class Numbers : IAsyncEnumerable + { + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + + class C + { + async Task M(Numbers source) + { + await foreach (var item in source) + { + } + + await foreach (var item in {|E128182:source|}) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForSynchronousForeachOverAList() + { + return VerifyAsync(""" + class C + { + void M(List source) + { + foreach (var item in source) + { + } + + foreach (var item in source) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForMembersOfAnotherInstanceCallsAndProperties() + { + return VerifyAsync(""" + class C + { + IAsyncEnumerable Source { get; } = default!; + + IAsyncEnumerable Make() => Source; + + async Task M(C other) + { + await foreach (var item in other.Source) + { + } + + await foreach (var item in other.Source) + { + } + + await foreach (var item in Make()) + { + } + + await foreach (var item in Make()) + { + } + + await foreach (var item in this.Source) + { + } + + await foreach (var item in this.Source) + { + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AsyncFileIoBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AsyncFileIoBranchCoverageTests.cs new file mode 100644 index 00000000..b482e744 --- /dev/null +++ b/tests/E128.Analyzers.Tests/AsyncFileIoBranchCoverageTests.cs @@ -0,0 +1,183 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AsyncFileIoBranchCoverageTests +{ + private static AnalyzerTestOptions Options => new() { MarkupOptions = MarkupOptions.UseFirstDescriptor }; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync("using System;\nusing System.IO;\nusing System.Threading.Tasks;\n" + code, options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForASyncLambdaInsideAnAsyncMethod() + { + return VerifyAsync(""" + class C + { + async Task M(string path) + { + await Task.Yield(); + Action read = () => {|E128092:File.ReadAllText(path)|}; + read(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAConstructor() + { + return VerifyAsync(""" + class C + { + public C(string path) + { + {|E128092:File.ReadAllText(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InASyncLocalFunctionAndASyncAnonymousMethod() + { + return VerifyAsync(""" + class C + { + void M(string path) + { + void Local() => {|E128092:File.ReadAllText(path)|}; + Action anon = delegate { {|E128092:File.ReadAllText(path)|}; }; + Local(); + anon(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_InsideAsyncLocalFunctionAndAsyncLambdas() + { + return VerifyAsync(""" + class C + { + void M(string path) + { + async Task Local() { await Task.Yield(); File.ReadAllText(path); } + Func simple = async () => { await Task.Yield(); File.ReadAllText(path); }; + Func parenthesized = async (int x) => { await Task.Yield(); File.ReadAllText(path); }; + Func single = async x => { await Task.Yield(); File.ReadAllText(path); }; + Func anon = async delegate { await Task.Yield(); File.ReadAllText(path); }; + _ = (Local(), simple, parenthesized, single, anon); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnUnqualifiedCallThroughUsingStatic() + { + return AnalyzerTestRunner.VerifyAsync(""" + using static System.IO.File; + + class C + { + void M(string path) + { + {|E128092:ReadAllText(path)|}; + } + } + """, options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCalledNameAlreadyEndsInAsync() + { + return VerifyAsync(""" + class C + { + void M(string path) + { + _ = File.ReadAllTextAsync(path); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNameofAndDelegateInvocations() + { + return VerifyAsync(""" + class C + { + void M(string path, Func factory) + { + var name = nameof(path); + factory()(); + _ = name; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAFileTypeOutsideSystemIo() + { + return AnalyzerTestRunner.VerifyAsync(""" + namespace Other + { + static class File + { + public static string ReadAllText(string path) => path; + public static System.Threading.Tasks.Task ReadAllTextAsync(string path) => null!; + } + + class C + { + void M(string path) + { + File.ReadAllText(path); + } + } + } + """, options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAFileMethodWithoutAnAsyncSibling() + { + return VerifyAsync(""" + class C + { + bool M(string path) => File.Exists(path); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForANonFileTypeInSystemIo() + { + return VerifyAsync(""" + class C + { + string M(string path) => Path.GetFullPath(path); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AsyncSiblingCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AsyncSiblingCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..512610dc --- /dev/null +++ b/tests/E128.Analyzers.Tests/AsyncSiblingCodeFixBranchCoverageTests.cs @@ -0,0 +1,177 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AsyncSiblingCodeFixBranchCoverageTests +{ + private const string DbPrefix = """ + using System; + using System.Data; + using System.Data.Common; + + sealed class FakeConnection : DbConnection + { + public override string ConnectionString { get; set; } = string.Empty; + public override string Database => string.Empty; + public override string DataSource => string.Empty; + public override string ServerVersion => string.Empty; + public override ConnectionState State => ConnectionState.Closed; + public override void ChangeDatabase(string databaseName) { } + public override void Close() { } + public override void Open() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + protected override DbCommand CreateDbCommand() => throw new NotSupportedException(); + } + """; + + [Fact] + [Trait("Category", "CI")] + public Task FileFix_Declines_ForAnUnqualifiedCall() + { + return CodeFixTestRunner.NoFixAsync( + """ + using static System.IO.File; + + class C + { + void M(string path) + { + {|E128092:ReadAllText(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task FileFix_Declines_InALocalFunction() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.IO; + + class C + { + void M(string path) + { + void Local() => {|E128092:File.ReadAllText(path)|}; + Local(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task FileFix_Declines_InAConstructor() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.IO; + + class C + { + public C(string path) + { + {|E128092:File.ReadAllText(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task FileFix_Declines_InALambdaInsideAMethod() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + using System.IO; + + class C + { + void M(string path) + { + Action read = () => {|E128092:File.ReadAllText(path)|}; + read(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task FileFix_Declines_InAnAnonymousMethodAndSimpleLambda() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + using System.IO; + + class C + { + void M(string path) + { + Action anon = delegate { {|E128092:File.ReadAllText(path)|}; }; + Action simple = x => {|E128092:File.ReadAllText(path)|}; + anon(); + simple(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DbFix_Declines_ForAConditionalAccessCall() + { + return CodeFixTestRunner.NoFixAsync( + DbPrefix + """ + + class C + { + void M(FakeConnection? connection) + { + connection?{|E128093:.Open()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DbFix_Declines_InAConstructor() + { + return CodeFixTestRunner.NoFixAsync( + DbPrefix + """ + + class C + { + public C(FakeConnection connection) + { + {|E128093:connection.Open()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DbFix_Declines_InALocalFunction() + { + return CodeFixTestRunner.NoFixAsync( + DbPrefix + """ + + class C + { + void M(FakeConnection connection) + { + void Local() => {|E128093:connection.Open()|}; + Local(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/AwaitInFinallyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/AwaitInFinallyBranchCoverageTests.cs new file mode 100644 index 00000000..65c0b364 --- /dev/null +++ b/tests/E128.Analyzers.Tests/AwaitInFinallyBranchCoverageTests.cs @@ -0,0 +1,59 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class AwaitInFinallyBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnAwaitUsingDeclaration() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + + class C + { + static async Task M(IAsyncDisposable d) + { + try + { + } + finally + { + {|E128186:await|} using var scope = d; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAwaitInAnAnonymousMethodInsideFinally() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + + class C + { + static async Task M() + { + try + { + } + finally + { + Func later = async delegate { await Task.Yield(); }; + _ = later; + } + + await Task.Yield(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/BareParseBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/BareParseBranchCoverageTests.cs new file mode 100644 index 00000000..5e4ba427 --- /dev/null +++ b/tests/E128.Analyzers.Tests/BareParseBranchCoverageTests.cs @@ -0,0 +1,148 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class BareParseBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.IO;\n" + + "class NoTryParse { public static int Parse(string text) => 0; }\n" + + "class InstanceTryParse { public static int Parse(string text) => 0; public bool TryParse(string text) => true; }\n" + + "class VoidTryParse { public static int Parse(string text) => 0; public static void TryParse(string text) { } }\n" + + "class WithTryParse { public static int Parse(string text) => 0; public static bool TryParse(string text, out int value) { value = 0; return true; } }\n" + + "class C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTypesWithoutAUsableTryParse() + { + return VerifyAsync(""" + void M(string text) + { + var a = NoTryParse.Parse(text); + var b = InstanceTryParse.Parse(text); + var c = VoidTryParse.Parse(text); + Local(text); + + static void Local(string value) { } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForMembersThatAreNotNamedParse() + { + return VerifyAsync(""" + void M(string text) + { + var a = int.TryParse(text, out var value); + var b = WithTryParse.TryParse(text, out value); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAUserTypeWithAStaticBoolTryParse() + { + return VerifyAsync(""" + void M(string text) + { + var a = {|E128089:WithTryParse.Parse(text)|}; + } + + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("catch (FormatException) { }")] + [InlineData("catch (Exception) { }")] + [InlineData("catch { }")] + [InlineData("catch (IOException) { } catch (FormatException) { }")] + public Task Silent_WhenACatchGuardsTheParse(string catches) + { + return VerifyAsync($$""" + void M(string text) + { + try + { + var a = int.Parse(text); + } + {{catches}} + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyAnUnrelatedCatchGuardsTheParse() + { + return VerifyAsync(""" + void M(string text) + { + try + { + var a = {|E128089:int.Parse(text)|}; + } + catch (IOException) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheParseSitsInTheCatchBlock() + { + return VerifyAsync(""" + void M(string text) + { + try + { + } + catch (FormatException) + { + var a = {|E128089:int.Parse(text)|}; + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnOuterTryGuardsAnInnerTryWithoutAFormatCatch() + { + return VerifyAsync(""" + void M(string text) + { + try + { + try + { + var a = int.Parse(text); + } + catch (IOException) + { + } + } + catch (FormatException) + { + } + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ByteSizeForDataSizeCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..332d607e --- /dev/null +++ b/tests/E128.Analyzers.Tests/ByteSizeForDataSizeCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,142 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ByteSizeForDataSizeCodeFixProviderBranchCoverageTests +{ + // The rule and the fix both target Pug.Core.Classes.ByteSize. A stub keeps the test off the package. + private const string ByteSizeStub = """ + namespace Pug.Core.Classes + { + public readonly struct ByteSize + { + public static ByteSize FromBytes(long bytes) => default; + } + } + """; + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + options: new CodeFixTestOptions { Sources = [ByteSizeStub] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsThePropertyInitializer() + { + return VerifyFixAsync( + """ + class C + { + public int {|E128080:MaxSizeBytes|} { get; set; } = 1024; + } + """, + """ + using Pug.Core.Classes; + + class C + { + public ByteSize MaxSizeBytes { get; set; } = Pug.Core.Classes.ByteSize.FromBytes(1024); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ChangesTheTypeOfAParameterWithoutADefault() + { + return VerifyFixAsync( + """ + class C + { + void M(int {|E128080:bufferBytes|}) + { + } + } + """, + """ + using Pug.Core.Classes; + + class C + { + void M(ByteSize bufferBytes) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsTheInitializerOfAField() + { + return VerifyFixAsync( + """ + class C + { + private int {|E128080:_maxBufferSize|} = 4096, {|E128080:_minBufferSize|}; + } + """, + """ + using Pug.Core.Classes; + + class C + { + private ByteSize _maxBufferSize = Pug.Core.Classes.ByteSize.FromBytes(4096), _minBufferSize; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_TurnsAConstFieldIntoAStaticReadonlyField() + { + return VerifyFixAsync( + """ + class C + { + private const int {|E128080:MaxBufferSize|} = 4096; + } + """, + """ + using Pug.Core.Classes; + + class C + { + private static readonly ByteSize MaxBufferSize = Pug.Core.Classes.ByteSize.FromBytes(4096); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_DropsConstFromALocal() + { + return VerifyFixAsync( + """ + class C + { + void M() + { + const int {|E128080:bufferBytes|} = 4096; + } + } + """, + """ + using Pug.Core.Classes; + + class C + { + void M() + { + ByteSize bufferBytes = Pug.Core.Classes.ByteSize.FromBytes(4096); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..39555c22 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ByteSizeUnwrapViaCastAnalyzerBranchCoverageTests.cs @@ -0,0 +1,86 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ByteSizeUnwrapViaCastAnalyzerBranchCoverageTests +{ + private const string Stubs = """ + namespace Pug.Core.Classes + { + public struct ByteSize + { + public double Bytes { get; set; } + public long Bits { get; set; } + public double Kilobytes { get; set; } + public double Megabytes { get; set; } + public double Gigabytes { get; set; } + public double Terabytes { get; set; } + public double Other { get; set; } + public double BytesField; + } + } + + class Measure + { + public double Bytes { get; set; } + } + + """; + + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using Pug.Core.Classes;\n" + Stubs + "class C { void M(ByteSize size, Measure measure) { " + body + " } }"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Bits")] + [InlineData("Kilobytes")] + [InlineData("Megabytes")] + [InlineData("Gigabytes")] + [InlineData("Terabytes")] + public Task Reports_ForEachUnitProperty(string property) + { + return VerifyAsync("var x = {|E128082:(long)size." + property + "|};"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("byte")] + [InlineData("short")] + [InlineData("int")] + [InlineData("long")] + [InlineData("float")] + [InlineData("double")] + [InlineData("decimal")] + public Task Reports_ForEachNumericTarget(string type) + { + return VerifyAsync("var x = {|E128082:(" + type + ")size.Bytes|};"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ThroughParentheses() + { + return VerifyAsync("var x = {|E128082:(long)((size.Bytes))|};"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCastsThatAreNotAnUnwrap() + { + return VerifyAsync(""" + var a = (long)(size.Bytes + 1); + var b = (object)size.Bytes; + var c = (long)measure.Bytes; + var d = (long)size.Other; + var e = (long)size.BytesField; + var f = (long)Value(); + var g = (double)(size.Bytes * 2); + long Value() { return 1; } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageTests.cs new file mode 100644 index 00000000..a1b66b72 --- /dev/null +++ b/tests/E128.Analyzers.Tests/CaptiveDependencyBranchCoverageTests.cs @@ -0,0 +1,170 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class CaptiveDependencyBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithDi = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.14") + ]); + + private static readonly ReferenceAssemblies Net100WithEfCore = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.14"), + new PackageIdentity("Microsoft.EntityFrameworkCore", "10.0.14") + ]); + + private static Task VerifyAsync(ReferenceAssemblies references, string code) + { + // Two descriptors share the E128154 id, so markup names the first one. + var test = new CSharpAnalyzerTest + { + TestCode = code, + ReferenceAssemblies = references, + MarkupOptions = MarkupOptions.UseFirstDescriptor + }; + + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NextToAnUnqualifiedCall() + { + return VerifyAsync(Net100WithDi, """ + using Microsoft.Extensions.DependencyInjection; + class Repository { } + class Worker { public Worker(Repository repository) { } } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddScoped(); + services.AddSingleton<{|E128154:Worker|}>(); + Helper(); + } + + static void Helper() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForSingletonsThatNameNoConcreteImplementation() + { + return VerifyAsync(Net100WithEfCore, """ + using Microsoft.Extensions.DependencyInjection; + interface IWorker { } + abstract class AbstractWorker { } + class Repository { } + class Worker : IWorker { public Worker(Repository repository) { } } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(typeof(IWorker)); + services.AddSingleton(typeof(AbstractWorker)); + services.AddSingleton(typeof(IWorker), typeof(Worker[])); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForScopedRegistrationsOfTypeParametersAndArrays() + { + return VerifyAsync(Net100WithDi, """ + using Microsoft.Extensions.DependencyInjection; + class Repository { } + class Worker { public Worker(Repository repository) { } } + class Startup + { + void Configure(IServiceCollection services) where T : class + { + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WithoutAnyDependencyInjectionPackage() + { + return VerifyAsync(ReferenceAssemblies.Net.Net100, """ + interface IServiceCollection { } + static class Registrations + { + public static IServiceCollection AddScoped(this IServiceCollection services) where T : class => services; + + public static IServiceCollection AddSingleton(this IServiceCollection services) where T : class => services; + } + class Repository { } + class Worker { public Worker(Repository repository) { } } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddScoped(); + services.AddSingleton<{|E128154:Worker|}>(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForATypeofContextOnAUserRegistrationHelper() + { + return VerifyAsync(Net100WithEfCore, """ + using System; + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.DependencyInjection; + class StoreContext : DbContext { } + static class Helpers + { + public static IServiceCollection AddDbContext( + this IServiceCollection services, + Type contextType, + ServiceLifetime contextLifetime) => services; + } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddDbContext({|E128154:typeof(StoreContext)|}, ServiceLifetime.Singleton); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAContextLifetimeThatIsNotAConstant() + { + return VerifyAsync(Net100WithEfCore, """ + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.DependencyInjection; + class StoreContext : DbContext { } + class Startup + { + void Configure(IServiceCollection services, ServiceLifetime lifetime) + { + services.AddDbContext((DbContextOptionsBuilder builder) => { }, lifetime); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/CatchFilterOceBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/CatchFilterOceBranchCoverageTests.cs new file mode 100644 index 00000000..0cfcaa66 --- /dev/null +++ b/tests/E128.Analyzers.Tests/CatchFilterOceBranchCoverageTests.cs @@ -0,0 +1,77 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class CatchFilterOceBranchCoverageTests +{ + private static Task VerifyAsync(string catches) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nclass C\n{\n void M(bool flag)\n {\n try { }\n" + + catches + "\n }\n}\n"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("ex is not OutOfMemoryException and not IOException")] + [InlineData("ex is not (OutOfMemoryException or IOException)")] + [InlineData("ex is IOException or not OutOfMemoryException")] + public Task Reports_ForFiltersThatExcludeTypesWithoutTheCancellationType(string filter) + { + return VerifyAsync($$""" + {|E128039:catch (Exception ex) when ({{filter}})|} + { + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("ex is IOException or FileNotFoundException")] + [InlineData("flag")] + [InlineData("ex.Message.Length > 0")] + [InlineData("ex is IOException")] + public Task Silent_ForFiltersThatAreNotExclusionPatterns(string filter) + { + return VerifyAsync($$""" + catch (Exception ex) when ({{filter}}) + { + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("OperationCanceledException")] + [InlineData("TaskCanceledException")] + public Task Silent_WhenAnEarlierCatchHandlesCancellation(string handled) + { + return VerifyAsync($$""" + catch ({{handled}}) + { + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenEarlierCatchesAreUnrelatedOrFiltered() + { + return VerifyAsync(""" + catch (IOException) + { + } + catch when (flag) + { + } + {|E128039:catch (Exception ex) when (ex is not OutOfMemoryException)|} + { + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ChainedStringReplaceBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ChainedStringReplaceBranchCoverageTests.cs new file mode 100644 index 00000000..c40c8edf --- /dev/null +++ b/tests/E128.Analyzers.Tests/ChainedStringReplaceBranchCoverageTests.cs @@ -0,0 +1,236 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ChainedStringReplaceBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_ReportsOnlyTheOutermostCallOfALongerChain() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + void M(string value) + { + var result = {|E128098:value.Replace('a', 'b').Replace('c', 'd').Replace('e', 'f')|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenAReplaceFollowsAnotherCall() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + void M(string value) + { + var result = value.Trim().Replace('a', 'b'); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenAnotherTypeDefinesReplace() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Editor + { + public Editor Replace(string search, string replacement) + { + return this; + } + } + + class C + { + void M(Editor editor, string value) + { + var result = editor.Replace("a", "b").Replace("c", "d"); + var mixed = value.Replace("a", "b"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_ReportsAnUnbracedReplaceUntilStableLoop() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + void M(string value) + { + {|E128098:while (value.Contains("--")) + value = value.Replace("--", "-");|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheWhileLoopIsNotAReplaceUntilStableLoop() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + bool Contains(string text) => text.Length > 0; + + void M(string value, string other, bool flag, List items) + { + while (flag) + { + value = value.Replace("--", "-"); + } + + while (items.Contains("--")) + { + items[0] = items[0].Replace("--", "-"); + } + + while (Contains("--")) + { + value = value.Replace("--", "-"); + } + + while (value.Contains("--")) + { + other = value.Replace("--", "-"); + } + + while (value.Contains("--")) + { + value = other.Replace("--", "-"); + } + + while (value.Contains("--")) + { + value += "x"; + } + + while (value.Contains("--")) + { + value = value.Trim(); + } + + while (value.Contains("--")) + { + _ = value.Length; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_CollapsesAnUnbracedLoopThatUsesTheShortOverloads() + { + return VerifyFixAsync( + """ + class C + { + void M(string value) + { + {|E128098:while (value.Contains("--")) + value = value.Replace("--", "-");|} + } + } + """, + """ + class C + { + void M(string value) + { + { + var __buffer = new char[value.Length]; + var __pos = 0; + var __collapsing = false; + foreach (var __c in value) + { + if (__c == '-') + { + if (!__collapsing) + { + __buffer[__pos++] = __c; + __collapsing = true; + } + } + else + { + __buffer[__pos++] = __c; + __collapsing = false; + } + } + + value = new string(__buffer, 0, __pos); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLoopUsesNamesOrValuesTheFixCannotSee() + { + return VerifyNoFixAsync(""" + class C + { + void M(string value, string search, string replacement, int count) + { + {|E128098:while (value.Contains(search)) + { + value = value.Replace("--", "-"); + }|} + + {|E128098:while (value.Contains("--")) + { + value = value.Replace(search, "-"); + }|} + + {|E128098:while (value.Contains("--")) + { + value = value.Replace("--", replacement); + }|} + + {|E128098:while (value.Contains("--")) + { + value = value.Replace("--", "--"); + }|} + + {|E128098:while (value.Contains("--")) + { + value = value.Replace("xx", "x"); + }|} + + {|E128098:while (value.Contains("--")) + { + count = count + 1; + value = value.Replace("--", "-"); + }|} + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageTests.cs new file mode 100644 index 00000000..6f9ad851 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ClosedHierarchyBranchCoverageTests.cs @@ -0,0 +1,169 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ClosedHierarchyBranchCoverageTests +{ + private static AnalyzerTestOptions Options => new() + { + LanguageVersion = LanguageVersion.Latest, + Sources = [UnionTestRuntime.StubSource], + }; + + private static Task VerifyMembersAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code, options: Options); + } + + private static Task VerifyMemberlessAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code, options: Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheBaseCarriesAnAttributeWithTheSameNameInAnotherNamespace() + { + return VerifyMembersAsync( + """ + namespace Other + { + [System.AttributeUsage(System.AttributeTargets.Class)] + internal sealed class IsClosedTypeAttribute : System.Attribute + { + } + } + + [Other.IsClosedType] + internal abstract class {|E128225:Shape|} + { + internal string Label() => "shape"; + } + + internal sealed class Circle : Shape + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenEveryPartOfAPartialBaseDeclaresMembers() + { + return VerifyMembersAsync( + """ + internal abstract partial class {|E128225:Shape|} + { + internal string Label() => "shape"; + } + + internal abstract partial class Shape + { + internal int Sides() => 0; + } + + internal sealed class Circle : Shape + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAGenericBaseWithAClosedDerivedType() + { + return VerifyMembersAsync( + """ + internal abstract class {|E128225:Shape|} + { + internal T Value() => default!; + } + + internal sealed class Circle : Shape + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForBasesThatAreNotInternalAbstractClasses() + { + return VerifyMembersAsync( + """ + public abstract class PublicShape + { + internal string Label() => "shape"; + } + + internal class OpenShape + { + internal string Label() => "shape"; + } + + internal interface IShape + { + string Label(); + } + + internal abstract record RecordShape + { + internal string Label() => "shape"; + } + + internal sealed class A : PublicShape + { + } + + internal sealed class B : OpenShape + { + } + + internal sealed class C : IShape + { + public string Label() => "c"; + } + + internal sealed record D : RecordShape; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAbstractBaseWithoutDerivedTypes() + { + return VerifyMemberlessAsync( + """ + internal abstract class Shape + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAMemberlessRecordWithoutAParameterList() + { + return VerifyMemberlessAsync( + """ + internal abstract record {|E128219:Shape|}; + + internal sealed record Circle : Shape; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAMemberlessRecordWithAParameterList() + { + return VerifyMemberlessAsync( + """ + internal abstract record Shape(int Id); + + internal sealed record Circle(int Id) : Shape(Id); + """); + } +} diff --git a/tests/E128.Analyzers.Tests/CollectionMutationInEnumerationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/CollectionMutationInEnumerationBranchCoverageTests.cs new file mode 100644 index 00000000..34bbd7ca --- /dev/null +++ b/tests/E128.Analyzers.Tests/CollectionMutationInEnumerationBranchCoverageTests.cs @@ -0,0 +1,161 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class CollectionMutationInEnumerationBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "using System.Collections.Concurrent;\nusing System.Collections.Generic;\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAParameterMutatedByABracelessStatement() + { + return VerifyAsync(""" + class C + { + void M(List items) + { + foreach (var item in {|E128155:items|}) + items.Remove(item); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForADeconstructingForeach() + { + return VerifyAsync(""" + class C + { + void M(List<(int, int)> pairs) + { + foreach (var (a, b) in {|E128155:pairs|}) + { + pairs.Clear(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAConcurrentCollection() + { + return VerifyAsync(""" + class C + { + void M(ConcurrentBag bag) + { + foreach (var item in bag) + { + bag.Add(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAStringReceiver() + { + return VerifyAsync(""" + class C + { + void M(string text) + { + foreach (var c in text) + { + _ = text.Insert(0, "x"); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopSourceIsAMethodCall() + { + return VerifyAsync(""" + class C + { + List items = new(); + + List Get() => items; + + void M() + { + foreach (var item in Get()) + { + items.Add(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMutationIsAnAssignmentFollowedByAnExit() + { + return VerifyAsync(""" + class C + { + void M(List items) + { + foreach (var item in items) + { + items[0] = item; + break; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AddsLinqForACollectionWithoutAnInstanceToArray() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Collections.Generic; + + class C + { + void M(ICollection items) + { + foreach (var item in {|E128155:items|}) + { + items.Add(item); + } + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + void M(ICollection items) + { + foreach (var item in items.ToArray()) + { + items.Add(item); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/CollectionPathBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/CollectionPathBranchCoverageTests.cs new file mode 100644 index 00000000..64d0991c --- /dev/null +++ b/tests/E128.Analyzers.Tests/CollectionPathBranchCoverageTests.cs @@ -0,0 +1,95 @@ +using System.Threading.Tasks; +using E128.Analyzers.FileSystem; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class CollectionPathBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAQualifiedCollectionType() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + void M(System.Collections.Generic.List {|E128053:paths|}) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForARecordPrimaryConstructorParameter() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record R(IReadOnlyList {|E128053:paths|}); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAConstructorParameter() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class C + { + public C(IEnumerable {|E128053:directories|}) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTypesThatAreNotAStringCollection() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class List + { + } + + class C + { + void M( + string paths, + HashSet setPaths, + List intPaths, + List pairPaths, + System.Collections.Generic.IList qualifiedPaths, + System.Text.StringBuilder builderPaths, + List names) + { + } + + delegate void Handler(string paths); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesTheTypeArgumentOfAQualifiedCollection() + { + return CodeFixTestRunner.RunAsync( + """ + class C + { + void M(System.Collections.Generic.List {|E128053:filePaths|}) { } + } + """, + """ + using System.IO; + + class C + { + void M(System.Collections.Generic.List filePaths) { } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ComparerSetConstructionBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ComparerSetConstructionBranchCoverageTests.cs new file mode 100644 index 00000000..d16606c3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ComparerSetConstructionBranchCoverageTests.cs @@ -0,0 +1,128 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ComparerSetConstructionBranchCoverageTests +{ + [Theory] + [Trait("Category", "CI")] + [InlineData("while (index < items.Length)\n {\n set.Add(items[index++]);\n }")] + [InlineData("do\n {\n set.Add(items[index++]);\n }\n while (index < items.Length);")] + public Task Reports_WhenAWhileOrDoLoopFillsTheSet(string loop) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System; + using System.Collections.Generic; + + class C + { + void M(string[] items) + { + var index = 0; + var set = {|E128226:new HashSet(StringComparer.Ordinal)|}; + {{loop}} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSetIsOnlyReadAfterTheLoop() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Collections.Generic; + + class C + { + bool M(string[] items, string key) + { + var set = {|E128226:new HashSet(StringComparer.Ordinal)|}; + foreach (var item in items) + { + set.Add(item); + } + + return set.Contains(key) && set.TryGetValue(key, out _) && set.Count > 0; + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("_ = set.Remove(key);")] + [InlineData("set.Clear();")] + [InlineData("_ = set.Comparer;")] + [InlineData("_ = set.Overlaps(items);")] + public Task Silent_WhenTheSetIsUsedInAnyOtherWay(string use) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System; + using System.Collections.Generic; + + class C + { + void M(string[] items, string key) + { + var set = new HashSet(StringComparer.Ordinal); + foreach (var item in items) + { + set.Add(item); + } + + {{use}} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheConstructorArgumentIsNotAComparer() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + class C + { + void M(string[] items, List seed) + { + var fromList = new HashSet(seed); + var sized = new HashSet(16); + foreach (var item in items) + { + fromList.Add(item); + sized.Add(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSetIsAssignedAfterItsDeclaration() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Collections.Generic; + + class C + { + void M(string[] items) + { + HashSet set; + set = new HashSet(StringComparer.Ordinal); + foreach (var item in items) + { + set.Add(item); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageTests.cs new file mode 100644 index 00000000..087f95aa --- /dev/null +++ b/tests/E128.Analyzers.Tests/ComplexityCeilingBranchCoverageTests.cs @@ -0,0 +1,603 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ComplexityCeilingBranchCoverageTests +{ + private static DiagnosticResult Warning(int line, int column) + { + return new DiagnosticResult("E128152", DiagnosticSeverity.Warning).WithLocation(line, column); + } + + private static Task VerifyWithCeilingAsync(string ceiling, string code, params DiagnosticResult[] expected) + { + var test = new CSharpAnalyzerTest + { + TestCode = code, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100 + }; + test.TestState.AnalyzerConfigFiles.Add( + ("/.globalconfig", "is_global = true\ne128_max_complexity = " + ceiling)); + test.ExpectedDiagnostics.AddRange(expected); + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenWhileConditionDeclaresTheElementTheInnerLoopWalks() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(Queue queue) + { + while (queue.TryDequeue(out var item)) + { + foreach (var value in item) + { + _ = value; + } + } + } + } + """, + Warning(8, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Silent_WhenInnerBoundIndexesTheOuterCounterThroughAnIndexer() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(List> rows) + { + for (var i = 0; i < rows.Count; i++) + { + for (var j = 0; j < rows[i].Count; j++) + { + _ = rows[i][j]; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Silent_WhenInnerWhileWalksAVariableDeclaredInTheOuterBody() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(string[] rows) + { + foreach (var row in rows) + { + var k = 0; + while (k < row.Length) + { + k++; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenForeachRunsInsideAWhileLoop() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items, bool again) + { + while (again) + { + foreach (var item in items) + { + again = item > 0; + } + } + } + } + """, + Warning(7, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenOuterForUsesNotEqualsBound() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + for (var i = 0; i != 10; i++) + { + foreach (var item in items) + { + _ = item + i; + } + } + } + } + """, + Warning(7, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Silent_WhenOuterForHasConstantOnTheLeft() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + for (var i = 10; 0 < i; i--) + { + foreach (var item in items) + { + _ = item + i; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenOuterForHasNoCondition() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + for (var i = 0; ; i++) + { + foreach (var item in items) + { + _ = item; + } + + if (i > 3) + { + break; + } + } + } + } + """, + Warning(7, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Silent_WhenOuterForeachRunsOverAFixedSizeArray() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + foreach (var fixedItem in new int[4]) + { + foreach (var item in items) + { + _ = item + fixedItem; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenOuterForeachRunsOverAnArrayWithVariableSize() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items, int size) + { + foreach (var sized in new int[size]) + { + foreach (var item in items) + { + _ = item + sized; + } + } + } + } + """, + Warning(7, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_Flagged_WhenOuterForeachRunsOverAMultiDimensionalArrayCreation() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + foreach (var cell in new int[2, 3]) + { + foreach (var item in items) + { + _ = item + cell; + } + } + } + } + """, + Warning(7, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Loop_ReportsCubicOrWorse_WhenFourLoopsNest() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] items) + { + foreach (var a in items) + { + foreach (var b in items) + { + foreach (var c in items) + { + foreach (var d in items) + { + _ = a + b + c + d; + } + } + } + } + } + } + """, + [Warning(7, 13), Warning(9, 17), Warning(11, 21)]); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenCeilingIsExponential() + { + return VerifyWithCeilingAsync( + "exponential", + """ + class C + { + int Fib(int n) + { + return n < 2 ? n : Fib(n - 1) + Fib(n - 2); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenArgumentsComeFromAnUnknownCall() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n) + { + return n < 2 ? n : F(Next(n)) + F(Next(n)); + } + + static int Next(int n) => n - 1; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenAnUnknownArgumentSitsBesideASubtractiveOne() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int a, int b) + { + return a < 2 ? a : F(Next(a), b - 1) + F(a, b - 1); + } + + static int Next(int n) => n / 2; + } + """, + Warning(3, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenEveryArgumentIsDivisiveOrUnchanged() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int a, int b) + { + return a < 2 ? a : F(a / 2, b / 2) + F(a, b / 2) + F(a, b); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenBinaryArgumentDoesNotStartWithTheParameter() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n) + { + return n < 2 ? n : F(1 + n) + F(2 * n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenAnIntegerAddsANegativeConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n) + { + return n < 2 ? n : F(n + -1) + F(n + -2); + } + } + """, + Warning(3, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenALongAddsANegativeConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + long F(long n) + { + return n < 2 ? n : F(n + -1L) + F(n + -2L); + } + } + """, + Warning(3, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenADoubleAddsANegativeConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + double F(double x) + { + return x < 2 ? x : F(x + -1.0) + F(x + -2.0); + } + } + """, + Warning(3, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenConstantsAreNotNegative() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n) + { + return n < 2 ? n : F(n + 1) + F(n + 2); + } + + long G(long n) + { + return n < 2 ? n : G(n + 1L) + G(n + 2L); + } + + double H(double x) + { + return x < 2 ? x : H(x + 1.0) + H(x + 2.0); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenAddedOperandIsNotConstant() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n, int step) + { + return n < 2 ? n : F(n + step, step) + F(n + step, step); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenDivisorTypesAreLongOrDouble() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + long F(long n) + { + return n < 2 ? n : F(n / 2L) + F(n / 3L); + } + + double G(double x) + { + return x < 2 ? x : G(x / 2.0) + G(x / 4.0); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenDivisorIsBelowTwoOrOfAnotherType() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int F(int n) + { + return n < 2 ? n : F(n / 1) + F(n / 1); + } + + uint G(uint n) + { + return n < 2 ? n : G(n / 2u) + G(n / 2u); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenLongAndDoubleSubtractConstants() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + long F(long n) + { + return n < 2 ? n : F(n - 1) + F(n - 2); + } + + double G(double x) + { + return x < 2 ? x : G(x - 1.0) + G(x - 2.0); + } + } + """, + Warning(3, 5), + Warning(8, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Silent_WhenTheCacheIsIncrementedAndRead() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int[] seen = new int[64]; + + int F(int n) + { + if (seen[n] > 0) + { + return seen[n]; + } + + seen[n]++; + return F(n - 1) + F(n - 2); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenTheCacheBelongsToAnotherType() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Cache + { + public static int[] Values = new int[64]; + } + + class C + { + int F(int n) + { + Cache.Values[n] = F(n - 1) + F(n - 2); + return Cache.Values[n]; + } + } + """, + Warning(8, 5)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Recursion_Flagged_WhenTheFieldIsNotACollection() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int total; + + int F(int n) + { + total = F(n - 1) + F(n - 2); + return total; + } + } + """, + Warning(5, 5)); + } +} diff --git a/tests/E128.Analyzers.Tests/ComplexityCeilingCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ComplexityCeilingCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..da4dbb32 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ComplexityCeilingCodeFixBranchCoverageTests.cs @@ -0,0 +1,431 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ComplexityCeilingCodeFixBranchCoverageTests +{ + private static DiagnosticResult Warning(int line, int column) + { + return new DiagnosticResult("E128152", DiagnosticSeverity.Warning).WithLocation(line, column); + } + + private static Task VerifyMembershipAsync(string source, string fixedCode, params DiagnosticResult[] expected) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + expected: expected, + options: new CodeFixTestOptions { FixAllIterations = 1 }); + } + + private static Task VerifyNoMembershipAsync(string source, params DiagnosticResult[] expected) + { + return CodeFixTestRunner.NoFixAsync( + source, + expected: expected); + } + + private static Task VerifySuppressionAsync(string source, string fixedCode, params DiagnosticResult[] expected) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + expected: expected); + } + + [Fact] + [Trait("Category", "CI")] + public Task Membership_UsesTheOuterSideWhenItIsOnTheRight() + { + return VerifyMembershipAsync( + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(string[] items, string[] expected) + { + foreach (var a in items) + { + foreach (var b in expected) + { + if (b == a) + { + return true; + } + } + } + + return false; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(string[] items, string[] expected) + { + var expectedSet = expected.ToHashSet(); + foreach (var a in items) + { + if (expectedSet.Contains(a)) + { + return true; + } + } + + return false; + } + } + """, + Warning(10, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Membership_UsesAMemberOfTheOuterElement() + { + return VerifyMembershipAsync( + """ + using System.Collections.Generic; + using System.Linq; + + class Item + { + public string Name = ""; + } + + class C + { + bool Has(Item[] items, string[] names) + { + foreach (var item in items) + { + foreach (var name in names) + { + if (item.Name == name) + { + return true; + } + } + } + + return false; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class Item + { + public string Name = ""; + } + + class C + { + bool Has(Item[] items, string[] names) + { + var namesSet = names.ToHashSet(); + foreach (var item in items) + { + if (namesSet.Contains(item.Name)) + { + return true; + } + } + + return false; + } + } + """, + Warning(15, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Membership_UsesAnElementOfTheOuterElement() + { + return VerifyMembershipAsync( + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(string[][] rows, string[] names) + { + foreach (var row in rows) + { + foreach (var name in names) + { + if ((row[0]) == name) + { + return true; + } + } + } + + return false; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(string[][] rows, string[] names) + { + var namesSet = names.ToHashSet(); + foreach (var row in rows) + { + if (namesSet.Contains((row[0]))) + { + return true; + } + } + + return false; + } + } + """, + Warning(10, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Membership_HandlesAnEmbeddedReturnInTheGuard() + { + return VerifyMembershipAsync( + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(int[] items, int[] expected) + { + foreach (var a in items) + { + foreach (var b in expected) + { + if (a == b) return true; + } + } + + return false; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(int[] items, int[] expected) + { + var expectedSet = expected.ToHashSet(); + foreach (var a in items) + { + if (expectedSet.Contains(a)) return true; + } + + return false; + } + } + """, + Warning(10, 13)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("string[] items, string[] expected, string key", "expected", "{ if (key == b) { return true; } }", "")] + [InlineData("string[] items, string[] expected", "expected", "{ if (a == b) { return true; } else { continue; } }", "")] + [InlineData("string[] items, string[] expected", "expected", "{ if (a != b) { return true; } }", "")] + [InlineData("string[] items, string[] expected", "expected", "{ if (a == b) { items = expected; return true; } }", "")] + [InlineData("string[] items, string[] expected", "expected", "if (a == b) { return true; }", "")] + [InlineData("string[] items", "_field", "{ if (a == b) { return true; } }", "private readonly string[] _field = new string[2];")] + [InlineData("string[] items", "new List()", "{ if (a == b) { return true; } }", "")] + [InlineData("string[] items, string[] expected", "expected", "{ if (Next(a) == b) { return true; } }", "static string Next(string value) => value;")] + [InlineData("string[] items, string[] expected", "expected", "{ if (a == b + \"x\") { return true; } }", "")] + [InlineData("object[] items, object[] expected", "expected", "{ if (a == b) { return true; } }", "")] + [InlineData("Money[] items, Money[] expected", "expected", "{ if (a == b) { return true; } }", "class Money { public static bool operator ==(Money l, Money r) => true; public static bool operator !=(Money l, Money r) => false; public override bool Equals(object? o) => true; public override int GetHashCode() => 0; }")] + public Task Membership_NoAction_WhenTheScanIsNotASafeSetLookup( + string parameters, + string innerSource, + string innerBody, + string members) + { + var source = $$""" + using System.Collections.Generic; + + class C + { + bool Has({{parameters}}) + { + foreach (var a in items) + { + foreach (var b in {{innerSource}}) + {{innerBody}} + } + + return false; + } + + {{members}} + } + """; + + return VerifyNoMembershipAsync(source, Warning(9, 13)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Membership_FixesTheScanInsideASwitchSection() + { + return VerifyMembershipAsync( + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(int mode, string[] items, string[] expected) + { + switch (mode) + { + case 1: + foreach (var a in items) + { + foreach (var b in expected) + { + if (a == b) + { + return true; + } + } + } + + break; + } + + return false; + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + + class C + { + bool Has(int mode, string[] items, string[] expected) + { + switch (mode) + { + case 1: + var expectedSet = expected.ToHashSet(); + foreach (var a in items) + { + if (expectedSet.Contains(a)) + { + return true; + } + } + + break; + } + + return false; + } + } + """, + Warning(13, 21)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Suppression_NoAction_WhenTheLoopIsAnEmbeddedStatement() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + void M(string[] items, bool flag) + { + foreach (var a in items) + if (flag) + foreach (var b in items) + { + _ = a.Length + b.Length; + } + } + } + """, + expected: Warning(7, 17)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Suppression_WrapsALoopInASwitchSection() + { + return VerifySuppressionAsync( + """ + class C + { + void M(int mode, string[] items) + { + switch (mode) + { + case 1: + foreach (var a in items) + { + foreach (var b in items) + { + _ = a.Length + b.Length; + } + } + + break; + } + } + } + """, + """ + class C + { + void M(int mode, string[] items) + { + switch (mode) + { + case 1: + foreach (var a in items) + { + #pragma warning disable E128152 // Justification: state why this site is output-bound + foreach (var b in items) + { + _ = a.Length + b.Length; + } + #pragma warning restore E128152 + } + + break; + } + } + } + """, + Warning(10, 21)); + } +} diff --git a/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityBranchCoverageTests.cs new file mode 100644 index 00000000..181738b3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/CompositeDetectionSpecificityBranchCoverageTests.cs @@ -0,0 +1,75 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class CompositeDetectionSpecificityBranchCoverageTests +{ + private static Task VerifyAsync(string statement) + { + return AnalyzerTestRunner.VerifyAsync($$""" + abstract record DetectionRule; + sealed record ResourceDetection(string Selector) : DetectionRule; + sealed record DomainDetection(string Domain) : DetectionRule; + sealed record CompositeDetection(DetectionRule[] Branches) : DetectionRule; + class C + { + void M(string selector, DetectionRule[] existing) + { + {{statement}} + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("#A")] + [InlineData("#item42")] + [InlineData("#item-name")] + [InlineData("#item_name")] + public Task Reports_WhenASingleSelectorContainsValidIdCharacters(string selector) + { + return VerifyAsync($$"""var rule = {|E128079:new CompositeDetection([new ResourceDetection("{{selector}}")])|};"""); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("")] + [InlineData("#")] + [InlineData("content")] + [InlineData(".content")] + [InlineData("#content .item")] + [InlineData("#content:hover")] + public Task Silent_WhenTheSelectorIsNotASingleGenericId(string selector) + { + return VerifyAsync($$"""var rule = new CompositeDetection([new ResourceDetection("{{selector}}")]);"""); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCompositeUsesTargetTypedCreation() + { + return VerifyAsync("CompositeDetection rule = {|E128079:new([new ResourceDetection(\"#content\")])|};"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("var rule = new CompositeDetection([]);")] + [InlineData("var rule = new CompositeDetection([..existing]);")] + [InlineData("var rule = new CompositeDetection(existing);")] + [InlineData("var rule = new CompositeDetection([new DomainDetection(\"example.test\")]);")] + [InlineData("var rule = new CompositeDetection([new ResourceDetection(selector)]);")] + public Task Silent_WhenTheBranchIsNotASingleLiteralResourceSelector(string statement) + { + return VerifyAsync(statement); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTargetTypedCreationNamesAnotherType() + { + return VerifyAsync("ResourceDetection rule = new(\"#content\");"); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..df29d5e2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcreteOnlyDiRegistrationCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,128 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcreteOnlyDiRegistrationCodeFixProviderBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithDi = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.6")]); + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + references: Net100WithDi); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync( + source, + references: Net100WithDi); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAParameterlessFactory() + { + return VerifyFixAsync( + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + void Configure(IServiceCollection services) + { + services.{|E128032:AddSingleton(sp => new Service())|}; + } + } + """, + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddSingleton(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAParenthesizedFactoryLambda() + { + return VerifyFixAsync( + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + void Configure(IServiceCollection services) + { + services.{|E128032:AddScoped((sp) => new Service())|}; + } + } + """, + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddScoped(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForAFactoryThatUsesABlockBody() + { + return VerifyNoFixAsync(""" + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + void Configure(IServiceCollection services) + { + services.{|E128032:AddSingleton(sp => { return new Service(); })|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForAFactoryMethodGroup() + { + return VerifyNoFixAsync(""" + using System; + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Startup + { + Service Create(IServiceProvider provider) => new(); + void Configure(IServiceCollection services) + { + services.{|E128032:AddSingleton(Create)|}; + } + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..cc1a1943 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixBranchCoverageTests.cs @@ -0,0 +1,58 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcreteTypeDiDependencyCodeFixBranchCoverageTests +{ + private static readonly ReferenceAssemblies References = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.6")]); + + [Theory] + [Trait("Category", "CI")] + [InlineData("Singleton")] + [InlineData("Scoped")] + [InlineData("Transient")] + public Task Fix_AddsConcreteAndForwardingRegistrations(string lifetime) + { + return CodeFixTestRunner.RunAsync( + $$""" + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Consumer + { + public Consumer({|E128035:Service service|}) { } + } + class Startup + { + void Configure(IServiceCollection services) + { + services.Add{{lifetime}}(); + } + } + """, + $$""" + using Microsoft.Extensions.DependencyInjection; + interface IService { } + class Service : IService { } + class Consumer + { + public Consumer(Service service) { } + } + class Startup + { + void Configure(IServiceCollection services) + { + services.Add{{lifetime}}(); + services.Add{{lifetime}}(sp => sp.GetRequiredService()); + } + } + """, + references: References, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { FixAllIterations = 1 }); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixNoiseBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixNoiseBranchCoverageTests.cs new file mode 100644 index 00000000..f131105a --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcreteTypeDiDependencyCodeFixNoiseBranchCoverageTests.cs @@ -0,0 +1,97 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcreteTypeDiDependencyCodeFixNoiseBranchCoverageTests +{ + private static readonly ReferenceAssemblies References = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.DependencyInjection", "10.0.6")]); + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesTheMatchingRegistrationAmongOtherCalls() + { + return CodeFixTestRunner.RunAsync( + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + interface IOther { } + class Service : IService { } + class Other : IOther { } + class Consumer + { + public Consumer({|E128035:Service service|}) { } + } + class Startup + { + void Configure(IServiceCollection services) + { + Helper(); + services.Clear(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + } + + static void Helper() { } + } + """, + """ + using Microsoft.Extensions.DependencyInjection; + interface IService { } + interface IOther { } + class Service : IService { } + class Other : IOther { } + class Consumer + { + public Consumer(Service service) { } + } + class Startup + { + void Configure(IServiceCollection services) + { + Helper(); + services.Clear(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + } + + static void Helper() { } + } + """, + references: References, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { FixAllIterations = 1 }); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheRegistrationIsPartOfAFluentChain() + { + return CodeFixTestRunner.NoFixAsync( + """ + using Microsoft.Extensions.DependencyInjection; + class Other { } + interface IService { } + class Service : IService { } + class Consumer + { + public Consumer({|E128035:Service service|}) { } + } + class Startup + { + void Configure(IServiceCollection services) + { + services.AddSingleton().AddScoped(); + } + } + """, + References, + CodeFixTestBehaviors.SkipLocalDiagnosticCheck); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcurrencyLimitBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcurrencyLimitBranchCoverageTests.cs new file mode 100644 index 00000000..946ca93f --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcurrencyLimitBranchCoverageTests.cs @@ -0,0 +1,164 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcurrencyLimitBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSemaphoreCountIsAConstantExpression() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading; + class C + { + const int Limit = 1 - 3; + SemaphoreSlim M() => {|E128040:new SemaphoreSlim(Limit, 4)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenATargetTypedSemaphoreHasANegativeCount() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading; + class C + { + SemaphoreSlim M() => {|E128040:new(-2)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFullyQualifiedSemaphoreHasANegativeCount() + { + return AnalyzerTestRunner.VerifyAsync(""" + class C + { + System.Threading.SemaphoreSlim M() => {|E128040:new global::System.Threading.SemaphoreSlim(-2)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSemaphoreCountIsNotAConstant() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading; + class C + { + SemaphoreSlim M(int count) => new(count); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherTypeHasTheSemaphoreName() + { + return AnalyzerTestRunner.VerifyAsync(""" + class SemaphoreSlim + { + public SemaphoreSlim(int count) { } + } + class C + { + SemaphoreSlim M() => new SemaphoreSlim(-2); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenParallelDegreeIsANegativeConstantExpression() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Tasks; + class C + { + const int Degree = 1 - 3; + ParallelOptions M() => new ParallelOptions { MaxDegreeOfParallelism = {|E128040:Degree|} }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenParallelDegreeIsPositiveOrNotConstant() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Tasks; + class C + { + void M(ParallelOptions options, int degree) + { + options.MaxDegreeOfParallelism = 4; + options.MaxDegreeOfParallelism = degree; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherTypeHasAPropertyWithTheSameName() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Options { public int MaxDegreeOfParallelism { get; set; } } + class C + { + void M(Options options) { options.MaxDegreeOfParallelism = 0; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenChannelCapacityIsANegativeConstant() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Channels; + class C + { + const int Capacity = 1 - 3; + Channel M() => {|E128040:Channel.CreateBounded(Capacity)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenChannelCapacityIsNotAnIntConstant() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Channels; + class C + { + Channel M(int capacity) => Channel.CreateBounded(capacity); + Channel N(BoundedChannelOptions options) => Channel.CreateBounded(options); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherTypeHasACreateBoundedMethod() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Channel + { + public static int CreateBounded(int capacity) => capacity; + } + class C + { + int M() => Channel.CreateBounded(0); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcurrencyLimitCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcurrencyLimitCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..c2ec2c88 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcurrencyLimitCodeFixBranchCoverageTests.cs @@ -0,0 +1,84 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcurrencyLimitCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesTheZeroCapacityOfABoundedChannel() + { + return CodeFixTestRunner.RunAsync( + """ + using System; + using System.Threading.Channels; + class C + { + Channel M() => {|E128040:Channel.CreateBounded(0)|}; + } + """, + """ + using System; + using System.Threading.Channels; + class C + { + Channel M() => Channel.CreateBounded(Environment.ProcessorCount); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesTheZeroInAnObjectInitializer() + { + return CodeFixTestRunner.RunAsync( + """ + using System; + using System.Threading.Tasks; + class C + { + ParallelOptions M() => new ParallelOptions { MaxDegreeOfParallelism = {|E128040:0|} }; + } + """, + """ + using System; + using System.Threading.Tasks; + class C + { + ParallelOptions M() => new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForANegativeLimit() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Threading; + class C + { + SemaphoreSlim M() => {|E128040:new SemaphoreSlim(-5)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLimitIsAConstantName() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Threading.Tasks; + class C + { + const int None = 0; + + ParallelOptions M() => new ParallelOptions { MaxDegreeOfParallelism = {|E128040:None|} }; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcurrencyLimitShapeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcurrencyLimitShapeBranchCoverageTests.cs new file mode 100644 index 00000000..db904695 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcurrencyLimitShapeBranchCoverageTests.cs @@ -0,0 +1,117 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcurrencyLimitShapeBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCreationsThatAreNotSemaphores() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class C + { + void M() + { + var a = new object(); + var b = new List(5); + var c = new List(-1 + 3); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForASemaphoreNamedTypeInTheGlobalNamespace() + { + return AnalyzerTestRunner.VerifyAsync(""" + class SemaphoreSlim { public SemaphoreSlim(int count) { } } + class C + { + void M() + { + var a = new global::SemaphoreSlim(-1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForASemaphoreInAForeignThreadingNamespace() + { + return AnalyzerTestRunner.VerifyAsync(""" + namespace Other.Threading + { + public class SemaphoreSlim { public SemaphoreSlim(int count) { } } + } + class C + { + void M() + { + var a = new Other.Threading.SemaphoreSlim(-1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAssignmentsThatAreNotTheDegreeProperty() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + class Options { public int MaxDegreeOfParallelism; } + class C + { + void M(List list, Options options) + { + list[0] = 0; + options.MaxDegreeOfParallelism = 0; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCallsThatAreNotBoundedChannelCreation() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Factory { public int CreateBounded() => 0; public int Other(int n) => n; } + class C + { + void M(Factory factory) + { + Helper(0); + factory.CreateBounded(); + factory.Other(0); + } + + static void Helper(int value) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAPositiveConstantWrittenWithAUnaryPlus() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading; + using System.Threading.Tasks; + class C + { + void M(ParallelOptions options) + { + options.MaxDegreeOfParallelism = +4; + var semaphore = new SemaphoreSlim(+1); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupBranchCoverageTests.cs new file mode 100644 index 00000000..12818dd5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConcurrentDictionaryDoubleLookupBranchCoverageTests.cs @@ -0,0 +1,110 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConcurrentDictionaryDoubleLookupBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + var code = "using System.Collections.Concurrent;\n\n" + + "class Own : ConcurrentDictionary\n{\n" + + " public bool Has(string key)\n {\n return ContainsKey(key);\n }\n}\n\n" + + "class C\n{\n" + + " static string GetKey() => \"k\";\n\n" + + " int M(ConcurrentDictionary map, ConcurrentDictionary other, string key, int index)\n {\n" + + body + + " return 0;\n }\n}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheIndexerBelongsToAnotherDictionary() + { + return VerifyAsync(""" + if (map.ContainsKey(key)) + { + return other[key]; + } + + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("map[key]++;")] + [InlineData("++map[key];")] + [InlineData("map[key]--;")] + [InlineData("--map[key];")] + [InlineData("map[key] += 1;")] + public Task Silent_WhenTheIndexerIsWritten(string write) + { + return VerifyAsync($$""" + if (map.ContainsKey(key)) + { + {{write}} + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheIndexerValueIsReadIntoAnAssignment() + { + return VerifyAsync(""" + var value = 0; + if ({|E128208:map.ContainsKey(key)|}) + { + value = map[key]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheKeyIsTheSameCall() + { + return VerifyAsync(""" + if ({|E128208:map.ContainsKey(GetKey())|}) + { + return map[GetKey()]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheKeysAreDifferentConstants() + { + return VerifyAsync(""" + if (map.ContainsKey("a")) + { + return map["b"]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCheckIsNegatedOrCombined() + { + return VerifyAsync(""" + if (!map.ContainsKey(key)) + { + return map[key]; + } + + if (map.ContainsKey(key) && index > 0) + { + return map[key]; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ConstructorNewDiRegisteredBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ConstructorNewDiRegisteredBranchCoverageTests.cs new file mode 100644 index 00000000..d3485978 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ConstructorNewDiRegisteredBranchCoverageTests.cs @@ -0,0 +1,137 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ConstructorNewDiRegisteredBranchCoverageTests +{ + private const string Stubs = """ + interface IServices { } + static class Registrations + { + public static IServices AddSingleton(this IServices services) where T : class => services; + + public static IServices AddScoped(this IServices services) where T : class => services; + + public static IServices AddHttpClient(this IServices services, string name) => services; + } + class Service { } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + "\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnrelatedUnqualifiedCallAndANonGenericRegistrationAppearInTheCompilation() + { + return VerifyAsync(""" + class Consumer + { + public Consumer() + { + var service = {|E128034:new Service()|}; + } + } + class Startup + { + void Configure(IServices services) + { + Helper(); + services.AddHttpClient("named"); + services.AddSingleton(); + } + + static void Helper() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRegisteredTypeIsATypeParameter() + { + return VerifyAsync(""" + class Consumer + { + public Consumer() + { + var service = new Service(); + } + } + class Startup + { + void Configure(IServices services) where T : class + { + services.AddSingleton(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreationSitsInAMethodOrALocalFunctionInsideAConstructor() + { + return VerifyAsync(""" + class Consumer + { + public Consumer() + { + Service Local() => new Service(); + Local(); + } + + Service Create() => new Service(); + } + class Startup + { + void Configure(IServices services) + { + services.AddScoped(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNoTypeIsRegistered() + { + return VerifyAsync(""" + class Consumer + { + public Consumer() + { + var service = new Service(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForACreationOfAnUnregisteredType() + { + return VerifyAsync(""" + class Other { } + class Consumer + { + public Consumer() + { + var other = new Other(); + } + } + class Startup + { + void Configure(IServices services) + { + services.AddSingleton(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DateTimeParseRoundtripBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DateTimeParseRoundtripBranchCoverageTests.cs new file mode 100644 index 00000000..ea387703 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DateTimeParseRoundtripBranchCoverageTests.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DateTimeParseRoundtripBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Globalization;\nclass Parser { public static DateTime Parse(string text, IFormatProvider provider) => default; }\n" + + "class C\n{\n void M(string text)\n {\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForDateTimeOffsetParseAndParseExactWithoutStyles() + { + return VerifyAsync(""" + var a = {|E128016:DateTimeOffset.Parse(text, CultureInfo.InvariantCulture)|}; + var b = {|E128016:DateTimeOffset.ParseExact(text, "O", CultureInfo.InvariantCulture)|}; + var c = {|E128016:DateTime.ParseExact(text, "O", CultureInfo.InvariantCulture)|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForOtherArgumentCountsAndMethodNames() + { + return VerifyAsync(""" + var a = DateTime.Parse(text); + var b = DateTime.ParseExact(text, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + var c = DateTime.TryParse(text, CultureInfo.InvariantCulture, out var parsed); + var d = DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.None); + Local(); + + static void Local() { } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAParseMethodOnAnotherType() + { + return VerifyAsync(""" + var a = Parser.Parse(text, CultureInfo.InvariantCulture); + var b = int.Parse(text, CultureInfo.InvariantCulture); + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..e712310f --- /dev/null +++ b/tests/E128.Analyzers.Tests/DirectHttpClientInstantiationCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,160 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DirectHttpClientInstantiationCodeFixProviderBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithHttp = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Http", "10.0.6")]); + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + references: Net100WithHttp); + } + + private static Task VerifyNoFixAsync(string code) + { + return CodeFixTestRunner.NoFixAsync( + code, + references: Net100WithHttp); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AddsAConstructorBeforeTheFirstMethodAfterOtherMembers() + { + return VerifyFixAsync( + """ + using System.Net.Http; + class C + { + private readonly int _value; + public int Value => _value; + void M() + { + var client = {|E128004:new HttpClient()|}; + } + } + """, + """ + using System.Net.Http; + class C + { + private readonly int _value; + public int Value => _value; + + private readonly IHttpClientFactory _httpClientFactory; + + public C(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + void M() + { + var client = _httpClientFactory.CreateClient(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReusesAFactoryFieldAfterOtherMembers() + { + return VerifyFixAsync( + """ + using System.Net.Http; + class C + { + private readonly int _value; + private readonly IHttpClientFactory _factory; + + public C(IHttpClientFactory factory) + { + _factory = factory; + } + + void M() + { + var client = {|E128004:new HttpClient()|}; + } + } + """, + """ + using System.Net.Http; + class C + { + private readonly int _value; + private readonly IHttpClientFactory _factory; + + public C(IHttpClientFactory factory) + { + _factory = factory; + } + + void M() + { + var client = _factory.CreateClient(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForACreationInAStaticField() + { + return VerifyNoFixAsync(""" + using System.Net.Http; + class C + { + private static readonly HttpClient Client = {|E128004:new HttpClient()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForACreationInAStruct() + { + return VerifyNoFixAsync(""" + using System.Net.Http; + struct C + { + HttpClient M() => {|E128004:new HttpClient()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForACreationInARecord() + { + return VerifyNoFixAsync(""" + using System.Net.Http; + record C + { + HttpClient M() => {|E128004:new HttpClient()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForACreationInAStaticProperty() + { + return VerifyNoFixAsync(""" + using System.Net.Http; + class C + { + public static HttpClient Client => {|E128004:new HttpClient()|}; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DiskIoCatalogBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DiskIoCatalogBranchCoverageTests.cs new file mode 100644 index 00000000..6bcf2209 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DiskIoCatalogBranchCoverageTests.cs @@ -0,0 +1,123 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DiskIoCatalogBranchCoverageTests +{ + [Theory] + [Trait("Category", "CI")] + [InlineData("File.OpenRead(path)")] + [InlineData("File.OpenText(path)")] + public Task Reports_WhenAStaticReadFactoryFollowsAWrite(string read) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.IO; + class C + { + void M(string path, string value) + { + File.WriteAllText(path, value); + using var reader = {|E128064:{{read}}|}; + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("FileMode.CreateNew")] + [InlineData("FileMode.Append")] + public Task Reports_WhenAWriteModePrecedesARead(string mode) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.IO; + class C + { + string M(string path) + { + using (var stream = new FileStream(path, {{mode}})) { } + return {|E128064:File.ReadAllText(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAReadWriteStreamPrecedesARead() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + string M(string path) + { + using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) { } + return {|E128064:File.ReadAllText(path)|}; + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("if (flag) { File.WriteAllText(path, value); }")] + [InlineData("while (flag) { File.WriteAllText(path, value); break; }")] + [InlineData("for (int i = 0; i < 1; i++) { File.WriteAllText(path, value); }")] + [InlineData("foreach (var item in new[] { 1 }) { File.WriteAllText(path, value); }")] + [InlineData("switch (flag) { case true: File.WriteAllText(path, value); break; }")] + [InlineData("try { } catch (IOException) { File.WriteAllText(path, value); }")] + public Task Silent_WhenAConditionalWritePrecedesARead(string write) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.IO; + class C + { + string M(string path, string value, bool flag) + { + {{write}} + return File.ReadAllText(path); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnrelatedAssignmentFallsBetweenWriteAndRead() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + string M(string path, string other, string value) + { + File.WriteAllText(path, value); + other = value; + return {|E128064:File.ReadAllText(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAPathAssignmentFollowsTheRead() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + string M(string path, string other, string value) + { + File.WriteAllText(path, value); + var result = {|E128064:File.ReadAllText(path)|}; + path = other; + return result; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DiskIoCatalogHelperBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DiskIoCatalogHelperBranchCoverageTests.cs new file mode 100644 index 00000000..99bdcfe7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DiskIoCatalogHelperBranchCoverageTests.cs @@ -0,0 +1,505 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; +using static E128.Analyzers.Reliability.DiskIoCatalog; + +namespace E128.Analyzers.Tests; + +public sealed class DiskIoCatalogHelperBranchCoverageTests +{ + private static ExpressionSyntax Expr(string text) + { + return SyntaxFactory.ParseExpression(text); + } + + private static MethodDeclarationSyntax Method(string body) + { + var tree = CSharpSyntaxTree.ParseText("class C { void M() {\n" + body + "\n} }", cancellationToken: TestContext.Current.CancellationToken); + return tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes().OfType().Single(); + } + + private static StatementSyntax Statement(SyntaxNode root, string text) + { + return root.DescendantNodes().OfType().First(s => string.Equals(s.ToString(), text, StringComparison.Ordinal)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("WriteAllText", "Text")] + [InlineData("ReadAllBytes", "Bytes")] + [InlineData("AppendAllLines", "Lines")] + [InlineData("OpenWrite", "Stream")] + [InlineData("AppendText", "Writer")] + [InlineData("Delete", "Unknown")] + public void FileMethodKind_MapsTheMethodNameToItsKind(string name, string expected) + { + Assert.Equal(expected, FileMethodKind(name).ToString()); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("WriteAllText", true, false)] + [InlineData("AppendAllLinesAsync", true, false)] + [InlineData("WriteAllBytes", true, false)] + [InlineData("ReadAllText", false, true)] + [InlineData("ReadAllLines", false, true)] + [InlineData("Create", false, false)] + [InlineData("OpenRead", false, false)] + [InlineData("Delete", false, false)] + public void ValueMethods_SplitIntoWriteAndReadByPrefix(string name, bool isWrite, bool isRead) + { + Assert.Equal(isWrite, IsFileWriteValueMethod(name)); + Assert.Equal(isRead, IsFileReadValueMethod(name)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Create", true, false)] + [InlineData("OpenWrite", true, false)] + [InlineData("CreateText", true, false)] + [InlineData("AppendText", true, false)] + [InlineData("OpenRead", false, true)] + [InlineData("OpenText", false, true)] + [InlineData("WriteAllText", false, false)] + [InlineData("Delete", false, false)] + public void Factories_SplitIntoWriteAndReadByName(string name, bool isWrite, bool isRead) + { + Assert.Equal(isWrite, IsFileWriteFactory(name)); + Assert.Equal(isRead, IsFileReadFactory(name)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("SaveToDisk", true)] + [InlineData("exportTOFILE", true)] + [InlineData("SaveTo", true)] + [InlineData("WriteTo", true)] + [InlineData("DownloadTo", true)] + [InlineData("Compute", false)] + public void IsOpaqueWriteMethodName_MatchesWriteHintsIgnoringCase(string name, bool expected) + { + Assert.Equal(expected, IsOpaqueWriteMethodName(name)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData(0, "text")] + [InlineData(1, "bytes")] + [InlineData(2, "lines")] + [InlineData(3, "stream")] + [InlineData(4, "writer")] + [InlineData(5, "reader")] + [InlineData(6, "binary")] + [InlineData(7, "value")] + [InlineData(99, "value")] + public void KindDescription_NamesEachKind(int kind, string expected) + { + Assert.Equal(expected, KindDescription((IoKind)kind)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("StreamWriter", "StreamWriter")] + [InlineData("System.IO.StreamReader", "StreamReader")] + [InlineData("List", "List")] + [InlineData("int", null)] + public void ExtractCtorTypeName_ReturnsTheSimpleTypeName(string type, string? expected) + { + Assert.Equal(expected, ExtractCtorTypeName(SyntaxFactory.ParseTypeName(type))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("FileMode.Open", "FileAccess.Write", true)] + [InlineData("FileMode.Create", "FileAccess.Read", false)] + [InlineData("FileMode.Open", "FileAccess.ReadWrite", true)] + [InlineData("FileMode.Create", "FileAccess.Unknown", true)] + [InlineData("FileMode.Open", "FileAccess.Unknown", false)] + [InlineData("FileMode.Append", null, true)] + [InlineData("FileMode.Open", null, false)] + [InlineData("mode", "access", false)] + [InlineData(null, null, false)] + public void IsFileStreamWriteIntent_PrefersAccessAndFallsBackToMode(string? mode, string? access, bool expected) + { + var modeExpr = mode is null ? null : Expr(mode); + var accessExpr = access is null ? null : Expr(access); + + Assert.Equal(expected, IsFileStreamWriteIntent(modeExpr, accessExpr)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("File.Create(path)", "path")] + [InlineData("File.Create(path, 4096)", "path")] + [InlineData("File.Create()", null)] + [InlineData("Other.Create(path)", null)] + [InlineData("Create(path)", null)] + [InlineData("a.File.Create(path)", null)] + [InlineData("path", null)] + public void ExtractPathFromStreamArg_ReadsTheFileCreatePath(string arg, string? expected) + { + var path = ExtractPathFromStreamArg(Expr(arg)); + + Assert.Equal(expected, path?.ToString()); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("path", "Ident:path")] + [InlineData("info.FullName", "Member:info.FullName")] + [InlineData("a.b.Name", "OpaqueWriteRoot:a")] + [InlineData("Make().Inner.Name", "Expr:Make().Inner.Name")] + [InlineData("1 + 2", "Expr:1 + 2")] + public void Normalize_BuildsAKeyForEachPathShape(string expression, string expected) + { + Assert.Equal(expected, Normalize(Expr(expression))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Member:info.FullName", "Member:info.FullName|FileInfo:info")] + [InlineData("FileInfo:info", "FileInfo:info|Member:info.FullName")] + [InlineData("Member:info.Name", "Member:info.Name")] + [InlineData("Ident:p", "Ident:p")] + public void CompatibleKeys_ExpandsFileInfoAndFullNameKeys(string key, string expected) + { + Assert.Equal(expected, string.Join('|', CompatibleKeys(key))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Ident:p", "Ident:p", true)] + [InlineData("Member:info.FullName", "FileInfo:info", true)] + [InlineData("FileInfo:info", "Member:info.FullName", true)] + [InlineData("OpaqueWriteResult:r", "OpaqueWriteRoot:r", true)] + [InlineData("OpaqueWriteRoot:r", "OpaqueWriteResult:r", true)] + [InlineData("Ident:p", "Ident:q", false)] + [InlineData("OpaqueWriteResult:r", "Ident:r", false)] + public void KeysOverlap_MatchesEqualCompatibleAndOpaqueKeys(string a, string b, bool expected) + { + Assert.Equal(expected, KeysOverlap(a, b)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("OpaqueWriteResult:r", "OpaqueWriteRoot:r", true)] + [InlineData("OpaqueWriteResult:r", "OpaqueWriteRoot:other", false)] + [InlineData("OpaqueWriteResult:r", "Member:r.Path", true)] + [InlineData("OpaqueWriteResult:r", "Member:rr.Path", false)] + [InlineData("OpaqueWriteResult:r", "Ident:r", false)] + [InlineData("Ident:r", "OpaqueWriteRoot:r", false)] + public void OpaqueWriteResultOverlap_ComparesTheResultVariableToTheReadKey(string writeKey, string readKey, bool expected) + { + Assert.Equal(expected, OpaqueWriteResultOverlap(writeKey, readKey)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Ident:p", "p")] + [InlineData("Member:info.FullName", "info")] + [InlineData("Member:info", null)] + [InlineData("FileInfo:info", "info")] + [InlineData("OpaqueWriteResult:r", "r")] + [InlineData("OpaqueWriteRoot:root", "root")] + [InlineData("Expr:1 + 2", null)] + public void ExtractIdentifier_ReadsTheNameFromEachKeyKind(string key, string? expected) + { + Assert.Equal(expected, ExtractIdentifier(key)); + } + + [Fact] + [Trait("Category", "CI")] + public void FindFactoryIndex_ReturnsThePositionOrMinusOne() + { + var first = Expr("File.Create(a)"); + var second = Expr("File.Create(b)"); + var writes = new List + { + new(first, first, "Ident:a", null, IoKind.Stream, false), + new(second, second, "Ident:b", null, IoKind.Stream, false) + }; + + Assert.Equal(0, FindFactoryIndex(writes, first)); + Assert.Equal(1, FindFactoryIndex(writes, second)); + Assert.Equal(-1, FindFactoryIndex(writes, Expr("File.Create(c)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void TrackWriterVariable_MapsOnlyVariablesInitializedFromAKnownFactory() + { + var method = Method(""" + StreamWriter declared; + var known = File.CreateText(a); + var unknown = File.CreateText(b); + """); + var declarations = method.DescendantNodes().OfType().ToArray(); + var factory = declarations[1].Variables[0].Initializer!.Value; + var writes = new List { new(factory, factory, "Ident:a", null, IoKind.Writer, false) }; + var map = new Dictionary(StringComparer.Ordinal); + + TrackWriterVariable(declarations[0], writes, map); + TrackWriterVariable(declarations[1], writes, map); + TrackWriterVariable(declarations[2], writes, map); + + Assert.Equal(new KeyValuePair("known", 0), Assert.Single(map)); + } + + [Fact] + [Trait("Category", "CI")] + public void TryTrackOpaqueWriteResult_RecordsOnlyOpaqueWriteInvocations() + { + var method = Method(""" + int none; + var plain = value; + var local = Compute(); + var other = client.Compute(); + var sync = client.SaveToDisk(a); + var asynchronous = await client.DownloadToFile(b); + """); + var writes = new List(); + + foreach (var declaration in method.DescendantNodes().OfType()) + { + TryTrackOpaqueWriteResult(declaration, writes); + } + + Assert.Equal("OpaqueWriteResult:sync|OpaqueWriteResult:asynchronous", string.Join('|', writes.Select(static w => w.PathKey))); + Assert.All(writes, static w => Assert.Equal(IoKind.Unknown, w.Kind)); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteLinearlyPrecedesRead_IsTrueForSiblingStatementsInOrder() + { + var method = Method("write(); read();"); + + Assert.True(WriteLinearlyPrecedesRead(Statement(method, "write();"), Statement(method, "read();"))); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteLinearlyPrecedesRead_IsFalseWhenTheReadComesFirst() + { + var method = Method("read(); write();"); + + Assert.False(WriteLinearlyPrecedesRead(Statement(method, "write();"), Statement(method, "read();"))); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteLinearlyPrecedesRead_IsTrueThroughANonConditionalWrapper() + { + var method = Method("using (x) { write(); } read();"); + + Assert.True(WriteLinearlyPrecedesRead(Statement(method, "write();"), Statement(method, "read();"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("if (c) { write(); } read();")] + [InlineData("while (c) { write(); } read();")] + [InlineData("try { } catch { write(); } read();")] + [InlineData("try { } finally { write(); } read();")] + public void WriteLinearlyPrecedesRead_IsFalseWhenTheWriteIsConditional(string body) + { + var method = Method(body); + + Assert.False(WriteLinearlyPrecedesRead(Statement(method, "write();"), Statement(method, "read();"))); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteLinearlyPrecedesRead_IsFalseForStatementsOutsideAnyBlock() + { + var root = CSharpSyntaxTree.ParseText("write(); read();", cancellationToken: TestContext.Current.CancellationToken).GetRoot(TestContext.Current.CancellationToken); + + Assert.False(WriteLinearlyPrecedesRead(Statement(root, "write();"), Statement(root, "read();"))); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteBlockChildPrecedesReadBlockChild_ComparesTheTopLevelChildren() + { + var method = Method("{ write(); } read(); other();"); + var block = method.Body!; + var write = Statement(method, "write();"); + var read = Statement(method, "read();"); + var outside = SyntaxFactory.ParseStatement("outside();"); + + Assert.True(WriteBlockChildPrecedesReadBlockChild(block, write, read)); + Assert.False(WriteBlockChildPrecedesReadBlockChild(block, read, write)); + Assert.False(WriteBlockChildPrecedesReadBlockChild(block, write, write)); + Assert.False(WriteBlockChildPrecedesReadBlockChild(block, outside, read)); + Assert.False(WriteBlockChildPrecedesReadBlockChild(block, write, outside)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsConditionalConstruct_AcceptsEachConstructKind() + { + var method = Method(""" + if (c) { } else { } + switch (v) { case 1: break; } + do { } while (c); + while (c) { } + for (;;) { } + foreach (var i in xs) { } + try { } catch { } finally { } + using (x) { } + """); + var kinds = method.DescendantNodes().Where(IsConditionalConstruct).Select(static n => n.GetType().Name).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + + Assert.Equal( + [ + nameof(CatchClauseSyntax), + nameof(DoStatementSyntax), + nameof(ElseClauseSyntax), + nameof(FinallyClauseSyntax), + nameof(ForEachStatementSyntax), + nameof(ForStatementSyntax), + nameof(IfStatementSyntax), + nameof(SwitchSectionSyntax), + nameof(SwitchStatementSyntax), + nameof(WhileStatementSyntax) + ], + kinds); + } + + [Fact] + [Trait("Category", "CI")] + public void BuildAssignmentPositions_IndexesSimpleAssignmentsInSourceOrder() + { + var method = Method(""" + p = 1; + q = 2; + p = 3; + this.r = 4; + """); + + var positions = BuildAssignmentPositions(method); + + Assert.Equal("p|q", string.Join('|', positions.Keys.Order(StringComparer.Ordinal))); + Assert.Equal(2, positions["p"].Count); + Assert.True(positions["p"][0] < positions["p"][1]); + _ = Assert.Single(positions["q"]); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("p = 1; write(); p = 2; read();", "Ident:p", "Ident:p", true)] + [InlineData("write(); read(); p = 2;", "Ident:p", "Ident:p", false)] + [InlineData("p = 1; write(); read();", "Ident:p", "Ident:p", false)] + [InlineData("write(); other = 2; read();", "Ident:p", "Ident:p", false)] + [InlineData("write(); p = 2; read();", "Expr:a", "Expr:b", false)] + [InlineData("write(); p = 2; read();", "Expr:a", "Ident:p", true)] + public void IsIdentifierReassignedBetween_FindsAnAssignmentBetweenWriteAndRead( + string body, + string writeKey, + string readKey, + bool expected) + { + var method = Method(body); + var write = new WriteOp(Statement(method, "write();"), null, writeKey, null, IoKind.Text, false); + var read = new ReadOp(Statement(method, "read();"), readKey, IoKind.Text, false, false); + + Assert.Equal(expected, IsIdentifierReassignedBetween(BuildAssignmentPositions(method), write, read)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsIdentifierReassignedBetween_IgnoresAnAssignmentAtTheWritePosition() + { + var method = Method("p = Save(); read();"); + var assignment = method.DescendantNodes().OfType().Single(); + var write = new WriteOp(assignment, null, "Ident:p", null, IoKind.Text, false); + var read = new ReadOp(Statement(method, "read();"), "Ident:p", IoKind.Text, false, false); + + Assert.False(IsIdentifierReassignedBetween(BuildAssignmentPositions(method), write, read)); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteOp_ComparesByEveryField() + { + var node = Expr("File.Create(a)"); + var source = Expr("data"); + var baseline = new WriteOp(node, node, "Ident:a", source, IoKind.Text, false); + var same = new WriteOp(node, node, "Ident:a", source, IoKind.Text, false); + + Assert.True(baseline.Equals(same)); + Assert.True(baseline == same); + Assert.False(baseline != same); + Assert.True(baseline.Equals((object)same)); + Assert.Equal(baseline.GetHashCode(), same.GetHashCode()); + Assert.False(baseline.Equals("text")); + Assert.False(baseline.Equals(new WriteOp(Expr("File.Create(a)"), node, "Ident:a", source, IoKind.Text, false))); + Assert.False(baseline.Equals(new WriteOp(node, Expr("x"), "Ident:a", source, IoKind.Text, false))); + Assert.False(baseline.Equals(new WriteOp(node, node, "Ident:b", source, IoKind.Text, false))); + Assert.False(baseline.Equals(new WriteOp(node, node, "Ident:a", Expr("data"), IoKind.Text, false))); + Assert.False(baseline.Equals(new WriteOp(node, node, "Ident:a", source, IoKind.Bytes, false))); + Assert.False(baseline.Equals(new WriteOp(node, node, "Ident:a", source, IoKind.Text, true))); + Assert.False(baseline.Equals(baseline.WithMergedSource(Expr("more")).WithMergedSource(Expr("again")))); + } + + [Fact] + [Trait("Category", "CI")] + public void WriteOp_HashCodeHandlesMissingOptionalNodes() + { + var node = Expr("File.Create(a)"); + var bare = new WriteOp(node, null, "Ident:a", null, IoKind.Text, true); + + Assert.Equal(bare.GetHashCode(), new WriteOp(node, null, "Ident:a", null, IoKind.Text, true).GetHashCode()); + Assert.NotEqual(bare.GetHashCode(), new WriteOp(node, null, "Ident:a", null, IoKind.Text, false).GetHashCode()); + Assert.Equal("WriteOp(Ident:a, Text)", bare.ToString()); + } + + [Fact] + [Trait("Category", "CI")] + public void WithMergedSource_KeepsTheFirstSourceThenMarksMultipleWrites() + { + var node = Expr("File.Create(a)"); + var first = Expr("one"); + var write = new WriteOp(node, node, "Ident:a", null, IoKind.Text, false); + + var withSource = write.WithMergedSource(first); + var merged = withSource.WithMergedSource(Expr("two")); + var mergedAgain = merged.WithMergedSource(Expr("three")); + + Assert.Same(first, withSource.SourceExpr); + Assert.False(withSource.HasMultipleWrites); + Assert.Null(merged.SourceExpr); + Assert.True(merged.HasMultipleWrites); + Assert.Null(mergedAgain.SourceExpr); + Assert.True(mergedAgain.HasMultipleWrites); + Assert.NotEqual(withSource.GetHashCode(), merged.GetHashCode()); + } + + [Fact] + [Trait("Category", "CI")] + public void ReadOp_ComparesByEveryField() + { + var node = Expr("File.ReadAllText(a)"); + var baseline = new ReadOp(node, "Ident:a", IoKind.Text, false, false); + var same = new ReadOp(node, "Ident:a", IoKind.Text, false, false); + + Assert.True(baseline.Equals(same)); + Assert.True(baseline == same); + Assert.False(baseline != same); + Assert.True(baseline.Equals((object)same)); + Assert.Equal(baseline.GetHashCode(), same.GetHashCode()); + Assert.False(baseline.Equals("text")); + Assert.False(baseline.Equals(new ReadOp(Expr("File.ReadAllText(a)"), "Ident:a", IoKind.Text, false, false))); + Assert.False(baseline.Equals(new ReadOp(node, "Ident:b", IoKind.Text, false, false))); + Assert.False(baseline.Equals(new ReadOp(node, "Ident:a", IoKind.Bytes, false, false))); + Assert.False(baseline.Equals(new ReadOp(node, "Ident:a", IoKind.Text, true, false))); + Assert.False(baseline.Equals(new ReadOp(node, "Ident:a", IoKind.Text, false, true))); + Assert.NotEqual(baseline.GetHashCode(), new ReadOp(node, "Ident:a", IoKind.Text, true, false).GetHashCode()); + Assert.NotEqual(baseline.GetHashCode(), new ReadOp(node, "Ident:a", IoKind.Text, false, true).GetHashCode()); + Assert.Equal("ReadOp(Ident:a, Text)", baseline.ToString()); + } +} diff --git a/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageTests.cs new file mode 100644 index 00000000..4620ec86 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DiskRoundtripBranchCoverageTests.cs @@ -0,0 +1,311 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DiskRoundtripBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.IO;\nusing System.Threading.Tasks;\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAConstructor() + { + return VerifyAsync(""" + string text; + C(string path, string content) + { + File.WriteAllText(path, content); + text = {|E128064:File.ReadAllText(path)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForALocalFunctionWithoutARoundTrip() + { + return VerifyAsync(""" + void M(string path) + { + Local(); + + void Local() { File.Delete(path); } + string Expression() => File.ReadAllText(path); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAbstractMethodWithoutABody() + { + return AnalyzerTestRunner.VerifyAsync(""" + abstract class C + { + public abstract string M(string path); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnExpressionBodiedReadWithoutAWrite() + { + return VerifyAsync("string M(string path) => File.ReadAllText(path) + File.ReadAllText(path);\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWriteSitsOutsideEveryStatement() + { + return VerifyAsync(""" + static string Use(Action write, Func read) => read(); + + string M(string path, string content) => + Use(() => File.WriteAllText(path, content), () => { return File.ReadAllText(path); }); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCallsThatAreNotMemberAccessOrNotFileOperations() + { + return VerifyAsync(""" + string M(string path, string content) + { + Helper(path); + File.Delete(path); + var exists = File.Exists(path); + return exists ? File.ReadAllText(path) : content; + } + + static void Helper(string path) { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForFileInfoMethodsThatAreNotStreamFactories() + { + return VerifyAsync(""" + string M(FileInfo info, string content) + { + using (var writer = info.CreateText()) + { + writer.Write(content); + } + + info.Refresh(); + info.Delete(); + return content; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAUserDefinedFileInfoType() + { + return AnalyzerTestRunner.VerifyAsync(""" + class FileInfo + { + public object OpenWrite() => new object(); + public object OpenRead() => new object(); + } + class C + { + void M(FileInfo info) + { + info.OpenWrite(); + info.OpenRead(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAFlushFollowsTheWriterWrite() + { + return VerifyAsync(""" + string M(string path, string content) + { + using (var writer = File.CreateText(path)) + { + writer.Write(content); + writer.Flush(); + writer.WriteLine(); + } + + return {|E128064:File.ReadAllText(path)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTwoWritesPrecedeTheRead() + { + return VerifyAsync(""" + string M(string path, string first, string second) + { + using (var writer = File.CreateText(path)) + { + writer.Write(first); + writer.Write(second); + } + + return {|E128064:File.ReadAllText(path)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForWriterCallsOnUntrackedReceivers() + { + return VerifyAsync(""" + StreamWriter field = StreamWriter.Null; + + string M(string path, string content, StreamWriter other) + { + other.Write(content); + this.field.Write(content); + Make().Write(content); + return File.ReadAllText(path); + } + + StreamWriter Make() => StreamWriter.Null; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForObjectCreationsThatAreNotFileStreams() + { + return VerifyAsync(""" + string M(string path, string content) + { + File.WriteAllText(path, content); + var plain = new object(); + var sized = new System.Collections.Generic.List(4); + var initialized = new System.Collections.Generic.List { 1 }; + var empty = new System.Collections.Generic.List(); + return content; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForUserDefinedStreamTypes() + { + return AnalyzerTestRunner.VerifyAsync(""" + class StreamWriter { public StreamWriter(string path) { } } + class StreamReader { public StreamReader(string path) { } } + class C + { + void M(string path) + { + var writer = new StreamWriter(path); + var reader = new StreamReader(path); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForABinaryWriterOverAFileCreateFollowedByARead() + { + return VerifyAsync(""" + byte[] M(string path) + { + using (var writer = new BinaryWriter(File.Create(path))) + { + writer.Write(1); + } + + return {|E128064:File.ReadAllBytes(path)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForABinaryReaderOverAFileOpenReadAfterAWrite() + { + return VerifyAsync(""" + void M(string path, string content) + { + File.WriteAllText(path, content); + using (var reader = {|E128064:new BinaryReader({|E128064:File.OpenRead(path)|})|}) + { + reader.ReadInt32(); + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForBinaryStreamsOverNonFileSources() + { + return VerifyAsync(""" + string M(string path, string content) + { + File.WriteAllText(path, content); + using (var writer = new BinaryWriter(new MemoryStream())) + { + writer.Write(1); + } + + using (var reader = new BinaryReader(new MemoryStream())) + { + reader.ReadInt32(); + } + + return content; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAFileStreamWithTheModeAlone() + { + return VerifyAsync(""" + string M(string path) + { + using (var stream = new FileStream(path, FileMode.Create)) { } + return {|E128064:File.ReadAllText(path)|}; + } + + string N(string path) + { + using (var stream = new FileStream(path, FileMode.Open)) { } + File.WriteAllText(path, "x"); + return {|E128064:File.ReadAllText(path)|}; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DiskRoundtripCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DiskRoundtripCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..695de0cc --- /dev/null +++ b/tests/E128.Analyzers.Tests/DiskRoundtripCodeFixBranchCoverageTests.cs @@ -0,0 +1,104 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DiskRoundtripCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_ConvertsBytesToTextWithUtf8GetString() + { + return CodeFixTestRunner.RunAsync( + """ + using System.IO; + class C + { + string M(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + return {|E128064:File.ReadAllText(path)|}; + } + } + """, + """ + using System.IO; + using System.Text; + + class C + { + string M(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + return Encoding.UTF8.GetString(bytes); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesTheReadWithTheLinesSource() + { + return CodeFixTestRunner.RunAsync( + """ + using System.IO; + class C + { + string[] M(string path, string[] lines) + { + File.WriteAllLines(path, lines); + return {|E128064:File.ReadAllLines(path)|}; + } + } + """, + """ + using System.IO; + class C + { + string[] M(string path, string[] lines) + { + File.WriteAllLines(path, lines); + return lines; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheWriteKindCannotConvertToTheReadKind() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.IO; + class C + { + string[] M(string path, string content) + { + File.WriteAllText(path, content); + return {|E128064:File.ReadAllLines(path)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheWriteHasNoSourceValue() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.IO; + class C + { + string M(string path) + { + using (var stream = File.Create(path)) { } + return {|E128064:File.ReadAllText(path)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DisposableFieldInLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DisposableFieldInLoopBranchCoverageTests.cs new file mode 100644 index 00000000..3ccb596a --- /dev/null +++ b/tests/E128.Analyzers.Tests/DisposableFieldInLoopBranchCoverageTests.cs @@ -0,0 +1,121 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DisposableFieldInLoopBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System; + class Resource : IDisposable { public void Dispose() { } } + class C + { + IDisposable current = new Resource(); + IDisposable other = new Resource(); + void M(int count, bool flag) + { + {{body}} + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (int i = 0; i < count; i++) { {|E128193:current|} = new Resource(); }")] + [InlineData("do { {|E128193:current|} = new Resource(); count--; } while (count > 0);")] + public Task Reports_WhenALoopOverwritesADisposableField(string body) + { + return VerifyAsync(body); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAssignmentAppearsInTheForInitializer() + { + return VerifyAsync("for (current = new Resource(); count > 0; count--) { }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAssignmentAppearsInTheWhileCondition() + { + return VerifyAsync("while ((current = new Resource()) == null) { }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASeparateLocalFunctionOwnsTheAssignment() + { + return VerifyAsync("for (int i = 0; i < count; i++) { void Set() { current = new Resource(); } Set(); }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyAnotherFieldIsDisposedAfterTheAssignment() + { + return VerifyAsync("for (int i = 0; i < count; i++) { {|E128193:current|} = new Resource(); other.Dispose(); }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheDisposeBelongsToAnUninvokedLambda() + { + return VerifyAsync("for (int i = 0; i < count; i++) { {|E128193:current|} = new Resource(); Action release = () => current.Dispose(); GC.KeepAlive(release); }"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("if (flag) break;")] + [InlineData("if (flag) return;")] + [InlineData("if (flag) throw new InvalidOperationException();")] + public Task Reports_WhenAnExitCanSkipTheLaterDispose(string exit) + { + return VerifyAsync($$"""for (int i = 0; i < count; i++) { {|E128193:current|} = new Resource(); {{exit}} current.Dispose(); }"""); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFieldImplementsAsyncDisposable() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + class Resource : IAsyncDisposable { public ValueTask DisposeAsync() => default; } + class C + { + IAsyncDisposable current = new Resource(); + void M(int count) + { + for (int i = 0; i < count; i++) { {|E128193:current|} = new Resource(); } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopDisposesTheAsyncFieldBeforeReplacement() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + class Resource : IAsyncDisposable { public ValueTask DisposeAsync() => default; } + class C + { + IAsyncDisposable current = new Resource(); + async Task M(int count) + { + for (int i = 0; i < count; i++) + { + await current.DisposeAsync(); + current = new Resource(); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DisposableSingletonFactoryBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DisposableSingletonFactoryBranchCoverageTests.cs new file mode 100644 index 00000000..fa1cf187 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DisposableSingletonFactoryBranchCoverageTests.cs @@ -0,0 +1,115 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DisposableSingletonFactoryBranchCoverageTests +{ + private const string Prefix = """ + using System; + + class MyService : IDisposable + { + public void Dispose() { } + } + + """; + + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + Prefix + "class Startup\n{\n static void AddSingleton(Func factory) { }\n\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnUnqualifiedAddSingletonCall() + { + return VerifyAsync(""" + void Configure() + { + AddSingleton({|E128031:sp => new MyService()|}); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFactoryIsAMethodGroup() + { + return VerifyAsync(""" + static object? Build(IServiceProvider provider) => new MyService(); + + void Configure() + { + AddSingleton(Build); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLambdaHasABlockBody() + { + return VerifyAsync(""" + void Configure() + { + AddSingleton(sp => { return new MyService(); }); + AddSingleton((IServiceProvider sp) => { return new MyService(); }); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLambdaBodyHasNoType() + { + return VerifyAsync(""" + void Configure() + { + AddSingleton(sp => null); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInvokedResultAndForOtherMethodNames() + { + return VerifyAsync(""" + static Action> Pick() => static _ => { }; + + static void AddScoped(Func factory) { } + + void Configure() + { + Pick()(sp => new MyService()); + AddScoped(sp => new MyService()); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAddSingletonTakesTwoArguments() + { + return AnalyzerTestRunner.VerifyAsync( + Prefix + """ + class Startup + { + static void AddSingleton(Func factory, int lifetime) { } + + void Configure() + { + AddSingleton(sp => new MyService(), 1); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageTests.cs new file mode 100644 index 00000000..8f8a20f1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/DuplicateJsonPropertyNameBranchCoverageTests.cs @@ -0,0 +1,218 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class DuplicateJsonPropertyNameBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Text.Json.Serialization;\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForADuplicateInAStruct() + { + return VerifyAsync(""" + public struct Widget + { + [JsonPropertyName("id")] + public int First { get; set; } + + [{|E128178:JsonPropertyName("id")|}] + public int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForInterfacesAndEnums() + { + return VerifyAsync(""" + public interface IWidget + { + [JsonPropertyName("id")] + int First { get; } + + [JsonPropertyName("id")] + int Second { get; } + } + + public enum Kind { A, B } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForATypeWithoutAnyJsonPropertyName() + { + return VerifyAsync(""" + public sealed class Widget + { + public int First { get; set; } + + [Obsolete] + public int Second { get; set; } + + public void Method() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherAttributePrecedesTheJsonPropertyName() + { + return VerifyAsync(""" + public sealed class Widget + { + [Obsolete] + [JsonPropertyName("id")] + public int First { get; set; } + + [Obsolete] + [{|E128178:JsonPropertyName("id")|}] + public int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheJsonNameIsEmpty() + { + return VerifyAsync(""" + public sealed class Widget + { + [JsonPropertyName("")] + public int First { get; set; } + + [JsonPropertyName("")] + public int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForIndexersAndExplicitInterfaceImplementations() + { + return VerifyAsync(""" + public interface IHasId { int Id { get; } } + + public sealed class Widget : IHasId + { + [JsonPropertyName("id")] + public int First { get; set; } + + [JsonPropertyName("id")] + public int this[int index] => index; + + [JsonPropertyName("id")] + int IHasId.Id => 1; + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("[JsonIgnore]")] + [InlineData("[JsonIgnore(Condition = JsonIgnoreCondition.Always)]")] + public Task Silent_WhenTheDuplicateMemberIsAlwaysIgnored(string ignore) + { + return VerifyAsync($$""" + public sealed class Widget + { + [JsonPropertyName("id")] + public int First { get; set; } + + {{ignore}} + [JsonPropertyName("id")] + public int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheIgnoreConditionIsNever() + { + return VerifyAsync(""" + public sealed class Widget + { + [JsonPropertyName("id")] + public int First { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.Never)] + [{|E128178:JsonPropertyName("id")|}] + public int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenANonPublicMemberHasJsonIncludeAndAnotherAttribute() + { + return VerifyAsync(""" + public sealed class Widget + { + [JsonPropertyName("id")] + public int First { get; set; } + + [Obsolete] + [JsonInclude] + [{|E128178:JsonPropertyName("id")|}] + internal int Second { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AgainstTheNearestBaseTypeThatDeclaresTheName() + { + return VerifyAsync(""" + public class Grandparent + { + [JsonPropertyName("id")] + public int GrandparentId { get; set; } + } + + public class Parent : Grandparent + { + [{|E128178:JsonPropertyName("id")|}] + public int ParentId { get; set; } + } + + public sealed class Child : Parent + { + [{|E128178:JsonPropertyName("id")|}] + public int ChildId { get; set; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnOverrideReusesTheBaseJsonName() + { + return VerifyAsync(""" + public class Base + { + [JsonPropertyName("id")] + public virtual int Id { get; set; } + } + + public sealed class Derived : Base + { + [JsonPropertyName("id")] + public override int Id { get; set; } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/EfQueryInLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/EfQueryInLoopBranchCoverageTests.cs new file mode 100644 index 00000000..6fc390f5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/EfQueryInLoopBranchCoverageTests.cs @@ -0,0 +1,153 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class EfQueryInLoopBranchCoverageTests +{ + // The test project carries no EF Core package. Each snippet declares the query surface as a stub. + private const string EfStub = """ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + + namespace Microsoft.EntityFrameworkCore + { + public abstract class DbSet : IQueryable + { + public Type ElementType => typeof(T); + public System.Linq.Expressions.Expression Expression => throw new NotImplementedException(); + public IQueryProvider Provider => throw new NotImplementedException(); + public IEnumerator GetEnumerator() => throw new NotImplementedException(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + } + + namespace Microsoft.EntityFrameworkCore.Query + { + public abstract class RawQuery : IQueryable + { + public Type ElementType => typeof(T); + public System.Linq.Expressions.Expression Expression => throw new NotImplementedException(); + public IQueryProvider Provider => throw new NotImplementedException(); + public IEnumerator GetEnumerator() => throw new NotImplementedException(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + } + + class Item + { + public int Id { get; set; } + } + + """; + + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(EfStub + code, expected: null, options: options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAParenthesizedAsEnumerableFeedsANestedForeach() + { + return VerifyAsync(""" + class C + { + void M(DbSet items, int[] ids) + { + foreach (var id in ids) + { + foreach (var item in ({|E128180:items.AsEnumerable()|})) + { + _ = item.Id + id; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAnOrderedQueryOverADbSetMaterializes() + { + return VerifyAsync(""" + class C + { + void M(DbSet items, int[] ids) + { + foreach (var id in ids) + { + var ordered = {|E128180:items.OrderBy(i => i.Id).ToList()|}; + var casted = {|E128180:((IQueryable)items).Where(i => i.Id == id).ToList()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheQueryTypeLivesInAnEntityFrameworkNamespace() + { + return VerifyAsync(""" + class C + { + void M(Microsoft.EntityFrameworkCore.Query.RawQuery rows, int[] ids) + { + foreach (var id in ids) + { + var all = {|E128180:rows.ToList()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheQueryableHasNoEntityFrameworkRoot() + { + return VerifyAsync(""" + class C + { + void M(List local, int[] ids) + { + foreach (var id in ids) + { + var plain = local.AsQueryable().ToList(); + var query = (from i in local.AsQueryable() where i.Id > id select i).ToList(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAMemberAccessOrDoesNotBind() + { + return VerifyAsync( + """ + class C + { + static int ToList() => 0; + + void M(DbSet items, int[] ids) + { + foreach (var id in ids) + { + _ = ToList(); + _ = items.ToList(1, 2, 3); + } + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = Microsoft.CodeAnalysis.Testing.CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanBranchCoverageTests.cs new file mode 100644 index 00000000..eb855598 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanBranchCoverageTests.cs @@ -0,0 +1,428 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ElementLoopToBulkSpanBranchCoverageTests +{ + private static DiagnosticResult Expected(string method) + { + return new DiagnosticResult("E128140", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments(method); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("byte", "0", "Clear")] + [InlineData("byte", "7", "Fill")] + [InlineData("sbyte", "0", "Clear")] + [InlineData("sbyte", "-3", "Fill")] + [InlineData("short", "0", "Clear")] + [InlineData("short", "5", "Fill")] + [InlineData("ushort", "0", "Clear")] + [InlineData("ushort", "5", "Fill")] + [InlineData("int", "0", "Clear")] + [InlineData("int", "5", "Fill")] + [InlineData("uint", "0", "Clear")] + [InlineData("uint", "5", "Fill")] + [InlineData("long", "0", "Clear")] + [InlineData("long", "5", "Fill")] + [InlineData("ulong", "0", "Clear")] + [InlineData("ulong", "5", "Fill")] + [InlineData("char", "'\\0'", "Clear")] + [InlineData("char", "'a'", "Fill")] + [InlineData("float", "0f", "Clear")] + [InlineData("float", "1.5f", "Fill")] + [InlineData("double", "0d", "Clear")] + [InlineData("double", "1.5d", "Fill")] + [InlineData("decimal", "0m", "Clear")] + [InlineData("decimal", "1.5m", "Fill")] + [InlineData("bool", "false", "Clear")] + [InlineData("bool", "true", "Fill")] + public Task ConstantFillValue_ClearsOnlyWhenTheConstantIsZero(string elementType, string constant, string method) + { + var code = $$""" + class C + { + const {{elementType}} Value = {{constant}}; + + void M({{elementType}}[] values) + { + {|#0:for (var i = 0; i < values.Length; i++) + { + values[i] = Value; + }|} + } + } + """; + + return AnalyzerTestRunner.VerifyAsync(code, Expected(method)); + } + + [Fact] + [Trait("Category", "CI")] + public Task NullLiteral_Clears_WhenTheElementCanHoldNull() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(string[] names, int?[] numbers) + { + {|#0:for (var i = 0; i < names.Length; i++) + { + names[i] = null; + }|} + + {|#1:for (var i = 0; i < numbers.Length; i++) + { + numbers[i] = null; + }|} + } + } + """, + Expected("Clear"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(1).WithArguments("Clear")); + } + + [Fact] + [Trait("Category", "CI")] + public Task DefaultValues_Clear() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] literal, int[] expression) + { + {|#0:for (var i = 0; i < literal.Length; i++) + { + literal[i] = default; + }|} + + {|#1:for (var i = 0; i < expression.Length; i++) + { + expression[i] = default(int); + }|} + } + } + """, + Expected("Clear"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(1).WithArguments("Clear")); + } + + [Fact] + [Trait("Category", "CI")] + public Task VariableValues_Fill_WhenTheyAreLocalsParametersOrFields() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int field; + + void M(int[] values, int parameter) + { + var local = 3; + + {|#0:for (var i = 0; i < values.Length; i++) + { + values[i] = local; + }|} + + {|#1:for (var i = 0; i < values.Length; i++) + { + values[i] = parameter; + }|} + + {|#2:for (var i = 0; i < values.Length; i++) + { + values[i] = this.field; + }|} + } + } + """, + [ + Expected("Fill"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(1).WithArguments("Fill"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(2).WithArguments("Fill"), + ]); + } + + [Fact] + [Trait("Category", "CI")] + public Task NonVariableValues_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Property { get; } = 1; + + void M(int[] values, C other) + { + for (var i = 0; i < values.Length; i++) + { + values[i] = Property; + } + + for (var i = 0; i < values.Length; i++) + { + values[i] = this.Property; + } + + for (var i = 0; i < values.Length; i++) + { + values[i] = other.Property; + } + + for (var i = 0; i < values.Length; i++) + { + values[i] = 1 + 1; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ReferenceAndManagedElements_Fill() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Pair + { + public string Name; + } + + class C + { + void M(string[] names, Pair[] pairs, string name, Pair pair) + { + {|#0:for (var i = 0; i < names.Length; i++) + { + names[i] = name; + }|} + + {|#1:for (var i = 0; i < pairs.Length; i++) + { + pairs[i] = pair; + }|} + } + } + """, + Expected("Fill"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(1).WithArguments("Fill")); + } + + [Fact] + [Trait("Category", "CI")] + public Task UserDefinedConversionFromZero_Fill() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Wrapper + { + public int Value; + + public static implicit operator Wrapper(int value) + { + return new Wrapper { Value = value + 1 }; + } + } + + class C + { + const int Zero = 0; + + void M(Wrapper[] values) + { + {|#0:for (var i = 0; i < values.Length; i++) + { + values[i] = Zero; + }|} + } + } + """, + Expected("Fill")); + } + + [Fact] + [Trait("Category", "CI")] + public Task SpanDestination_Fills() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + class C + { + void M(Span values, int seed) + { + {|#0:for (var i = 0; i < values.Length; i++) + { + values[i] = seed; + }|} + } + } + """, + Expected("Fill")); + } + + [Fact] + [Trait("Category", "CI")] + public Task CopyFromASpan_Reports() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + class C + { + void M(Span source, int[] destination, Span spanDestination) + { + {|#0:for (var i = 0; i < source.Length; i++) + { + destination[i] = source[i]; + }|} + + {|#1:for (var i = 0; i < source.Length; i++) + { + spanDestination[i] = source[i]; + }|} + } + } + """, + Expected("CopyTo"), + new DiagnosticResult("E128140", DiagnosticSeverity.Warning).WithLocation(1).WithArguments("CopyTo")); + } + + [Fact] + [Trait("Category", "CI")] + public Task CopyThatDoesNotMatchTheSourceLength_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] source, int[] destination, long[] wide, string[] names) + { + for (var i = 0; i < destination.Length; i++) + { + destination[i] = source[i]; + } + + for (var i = 0; i < source.Length; i++) + { + wide[i] = source[i]; + } + + for (var i = 0; i < names.Length; i++) + { + destination[i] = source[i]; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task LoopBodiesThatAreNotASingleAssignment_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] values, int count) + { + for (var i = 0; i < values.Length; i++) + { + values[i] = 1; + count++; + } + + for (var i = 0; i < values.Length; i++) + { + values[i] += 1; + } + + for (var i = 0; i < values.Length; i++) + { + count++; + } + + for (var i = 0; i < values.Length; i++) + { + if (count > 0) + { + values[i] = 1; + } + } + + for (var i = 0; i < values.Length; i++) + { + } + + for (var i = 0; i < count; i++) + { + values[i] = 1; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DestinationThatIsNotAnArrayOrSpan_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class Grid + { + public int Length { get; } + + public int this[int index] + { + get => 0; + set { } + } + } + + class C + { + void M(Grid grid, int[,] matrix) + { + for (var i = 0; i < grid.Length; i++) + { + grid[i] = 1; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task UnbracedLoopBody_Reports() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] values) + { + {|#0:for (var i = 0; i < values.Length; i++) + values[i] = 1;|} + } + } + """, + Expected("Fill")); + } +} diff --git a/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..34ee12fa --- /dev/null +++ b/tests/E128.Analyzers.Tests/ElementLoopToBulkSpanCodeFixBranchCoverageTests.cs @@ -0,0 +1,167 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ElementLoopToBulkSpanCodeFixBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesClearOnAnArray() + { + return VerifyFixAsync( + """ + class C + { + void M(int[] values) + { + {|E128140:for (var i = 0; i < values.Length; i++) + { + values[i] = 0; + }|} + } + } + """, + """ + using System; + + class C + { + void M(int[] values) + { + values.AsSpan().Clear(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesFillOnASpanWithoutAddingAUsing() + { + return VerifyFixAsync( + """ + using System; + + class C + { + void M(Span values, int seed) + { + {|E128140:for (var i = 0; i < values.Length; i++) + { + values[i] = seed; + }|} + } + } + """, + """ + using System; + + class C + { + void M(Span values, int seed) + { + values.Fill(seed); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_CopiesFromASpanWithoutWrappingIt() + { + return VerifyFixAsync( + """ + using System; + + class C + { + void M(Span source, int[] destination) + { + {|E128140:for (var i = 0; i < source.Length; i++) + { + destination[i] = source[i]; + }|} + } + } + """, + """ + using System; + + class C + { + void M(Span source, int[] destination) + { + source.CopyTo(destination); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_CopiesAnArrayIntoASpan() + { + return VerifyFixAsync( + """ + using System; + + class C + { + void M(int[] source, Span destination) + { + {|E128140:for (var i = 0; i < source.Length; i++) + { + destination[i] = source[i]; + }|} + } + } + """, + """ + using System; + + class C + { + void M(int[] source, Span destination) + { + source.AsSpan().CopyTo(destination); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheLoopWithoutBraces() + { + return VerifyFixAsync( + """ + class C + { + void M(int[] values, int seed) + { + {|E128140:for (var i = 0; i < values.Length; i++) + values[i] = seed;|} + } + } + """, + """ + using System; + + class C + { + void M(int[] values, int seed) + { + values.AsSpan().Fill(seed); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/EnclosingBodyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/EnclosingBodyBranchCoverageTests.cs new file mode 100644 index 00000000..c5c7cef3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/EnclosingBodyBranchCoverageTests.cs @@ -0,0 +1,55 @@ +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class EnclosingBodyBranchCoverageTests +{ + private static BlockSyntax? Find(string members) + { + var tree = CSharpSyntaxTree.ParseText( + "using System; class C { " + members + " }", + cancellationToken: TestContext.Current.CancellationToken); + var node = tree.GetRoot(TestContext.Current.CancellationToken) + .DescendantNodes() + .OfType() + .First(static name => string.Equals(name.Identifier.ValueText, "Probe", System.StringComparison.Ordinal)); + return EnclosingBody.Find(node); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("void M() { Probe(); }")] + [InlineData("C() { Probe(); }")] + [InlineData("void M() { void Local() { Probe(); } }")] + [InlineData("int P { get { Probe(); return 0; } }")] + [InlineData("int P { set { Probe(); } }")] + [InlineData("void M() { Action a = () => { Probe(); }; }")] + [InlineData("void M() { Action a = delegate { Probe(); }; }")] + public void Find_ReturnsTheBlockOfTheNearestEnclosingBody(string members) + { + Assert.NotNull(Find(members)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("int M() => Probe();")] + [InlineData("int P => Probe();")] + [InlineData("int F = Probe();")] + [InlineData("void M() { Func a = () => Probe(); }")] + [InlineData("void M() { int Local() => Probe(); }")] + public void Find_ReturnsNullForExpressionBodiesAndMembersWithoutABlock(string members) + { + Assert.Null(Find(members)); + } + + [Fact] + [Trait("Category", "CI")] + public void Find_PrefersTheInnermostBody() + { + var block = Find("void M() { void Local() { Probe(); } }"); + _ = Assert.IsType(block?.Parent); + } +} diff --git a/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..2ceb622d --- /dev/null +++ b/tests/E128.Analyzers.Tests/EnumIfElseChainCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,110 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class EnumIfElseChainCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_MapsTheFinalElseToDefaultAndAddsBreaks() + { + return VerifyFixAsync( + """ + enum Color { Red, Green, Blue } + + class C + { + void Log(int value) { } + + void M(Color c) + { + {|E128048:if (c == Color.Red) + Log(1); + else if (c == Color.Green) + { + } + else if (c == Color.Blue) + { + throw new System.InvalidOperationException(); + } + else + Log(4);|} + } + } + """, + """ + enum Color { Red, Green, Blue } + + class C + { + void Log(int value) { } + + void M(Color c) + { + switch (c) + { + case Color.Red: + Log(1); + break; + case Color.Green: + break; + case Color.Blue: + throw new System.InvalidOperationException(); + default: + Log(4); + break; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_IsNotOfferedForAChainOfInequalities() + { + const string unchanged = """ + enum Color { Red, Green, Blue } + + class C + { + int M(Color c) + { + if (c != Color.Red) + { + return 1; + } + else if (c != Color.Green) + { + return 2; + } + else if (c != Color.Blue) + { + return 3; + } + return 0; + } + } + """; + + return CodeFixTestRunner.RunAsync( + unchanged, + unchanged, + expected: [Remaining()], + options: new CodeFixTestOptions { FixedExpected = [Remaining()] }); + } + + private static DiagnosticResult Remaining() + { + return new DiagnosticResult("E128048", DiagnosticSeverity.Warning).WithSpan(7, 9, 18, 10).WithArguments("Color", "3"); + } +} diff --git a/tests/E128.Analyzers.Tests/EventSubscriptionLeakBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/EventSubscriptionLeakBranchCoverageTests.cs new file mode 100644 index 00000000..48a37483 --- /dev/null +++ b/tests/E128.Analyzers.Tests/EventSubscriptionLeakBranchCoverageTests.cs @@ -0,0 +1,187 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class EventSubscriptionLeakBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nclass Publisher : IDisposable\n{\n public event EventHandler? Changed;\n public static event EventHandler? Shared;\n" + + " public int Count;\n public void Dispose() { }\n}\n" + + "class C : IDisposable\n{\n private readonly Publisher _publisher = new();\n private int _count;\n private static int s_total;\n" + + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCompoundAssignmentsThatAreNotEvents() + { + return VerifyAsync(""" + public void Run() + { + _count += 1; + _count -= 1; + } + + public void Dispose() { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyANestedTypeRemovesTheStaticEvent() + { + return VerifyAsync(""" + public void Start() + { + {|E128176:Publisher.Shared += (s, e) => _count++|}; + } + + public void Dispose() { } + + private sealed class Cleaner + { + public void Remove() + { + Publisher.Shared -= (s, e) => { }; + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheHandlerReadsThisExplicitly() + { + return VerifyAsync(""" + private void Handle() { } + + public void Start() + { + {|E128176:_publisher.Changed += (s, e) => this.Handle()|}; + } + + public void Dispose() { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenANestedLambdaReadsInstanceState() + { + return VerifyAsync(""" + public void Start() + { + {|E128176:_publisher.Changed += (s, e) => { Action inner = () => _count++; inner(); }|}; + } + + public void Dispose() { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheHandlerReadsNoInstanceState() + { + return VerifyAsync(""" + public void Start(Publisher other) + { + _publisher.Changed += (s, e) => other.Count++; + _publisher.Changed += (s, e) => { var local = 1; local++; }; + _publisher.Changed += (s, e) => s_total++; + _publisher.Changed += (s, e) => Console.WriteLine(nameof(Publisher)); + } + + public void Dispose() { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheDisposeCallSitsInALocalFunction() + { + return VerifyAsync(""" + public void Start() + { + {|E128176:_publisher.Changed += (s, e) => _count++|}; + } + + public void Dispose() + { + void Release() { _publisher.Dispose(); } + Release(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheDisposeCallSitsInAPropertyAccessor() + { + return VerifyAsync(""" + public void Start() + { + {|E128176:_publisher.Changed += (s, e) => _count++|}; + } + + private bool Closed + { + get + { + _publisher.Dispose(); + return true; + } + } + + public void Dispose() { } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheDisposedPublisherIsAnOwnedField() + { + return VerifyAsync(""" + public void Start() + { + _publisher.Changed += (s, e) => _count++; + } + + public void Dispose() + { + _publisher.Dispose(); + Console.WriteLine(); + ((IDisposable)this).ToString(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStaticEventIsRemovedThroughAnyReceiver() + { + return VerifyAsync(""" + public void Start() + { + Publisher.Shared += (s, e) => _count++; + } + + public void Dispose() + { + Publisher.Shared -= (s, e) => _count++; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ExclusiveBranchesBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ExclusiveBranchesBranchCoverageTests.cs new file mode 100644 index 00000000..f5d6075b --- /dev/null +++ b/tests/E128.Analyzers.Tests/ExclusiveBranchesBranchCoverageTests.cs @@ -0,0 +1,53 @@ +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ExclusiveBranchesBranchCoverageTests +{ + private static InvocationExpressionSyntax[] Calls(string body) + { + var tree = CSharpSyntaxTree.ParseText( + "class C { void M(int k, bool b) { " + body + " } void A() { } void B() { } void D() { } }", + cancellationToken: TestContext.Current.CancellationToken); + return [.. tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes().OfType()]; + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("if (b) { A(); } else { B(); }", true)] + [InlineData("if (b) A(); else B();", true)] + [InlineData("if (b) { A(); } else if (k > 1) { B(); }", true)] + [InlineData("if (b) { A(); B(); }", false)] + [InlineData("if (b) { } else { A(); B(); }", false)] + [InlineData("A(); if (b) { B(); }", false)] + [InlineData("if (b) { A(); } B();", false)] + [InlineData("switch (k) { case 1: A(); break; case 2: B(); break; }", true)] + [InlineData("switch (k) { case 1: A(); B(); break; }", false)] + [InlineData("switch (k) { case 1: A(); break; } B();", false)] + [InlineData("A(); switch (k) { case 1: B(); break; }", false)] + [InlineData("switch (k) { case 1: case 2: A(); break; case 3: B(); break; }", true)] + public void Are_ComparesTheBranchesOfTheSharedStatement(string body, bool expected) + { + var calls = Calls(body); + Assert.Equal(expected, ExclusiveBranches.Are(calls[0], calls[1])); + } + + [Fact] + [Trait("Category", "CI")] + public void Are_SeesDifferentSectionsOfAnOuterSwitchAroundAnInnerIf() + { + var calls = Calls("switch (k) { case 1: if (b) { A(); } break; case 2: if (b) { B(); } break; }"); + Assert.True(ExclusiveBranches.Are(calls[0], calls[1])); + } + + [Fact] + [Trait("Category", "CI")] + public void Are_IsFalseForTheSameNodeInOneBranch() + { + var calls = Calls("if (b) { A(); } else { B(); }"); + Assert.False(ExclusiveBranches.Are(calls[0], calls[0])); + } +} diff --git a/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..3a684bfb --- /dev/null +++ b/tests/E128.Analyzers.Tests/ExecuteScalarNullGuardCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,47 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ExecuteScalarNullGuardCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesTheNextFreeNameAndKeepsTheInt64Conversion() + { + return VerifyFixAsync( + """ + using System; + using System.Data.Common; + + class C + { + long M(DbCommand cmd, int result, int result2) + { + return {|E128042:Convert.ToInt64(cmd.ExecuteScalar())|}; + } + } + """, + """ + using System; + using System.Data.Common; + + class C + { + long M(DbCommand cmd, int result, int result2) + { + var result3 = cmd.ExecuteScalar(); + return result3 is null ? 0 : Convert.ToInt64(result3); + } + } + """); + } + + +} diff --git a/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageTests.cs new file mode 100644 index 00000000..523f67c9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FileInfoToctouBranchCoverageTests.cs @@ -0,0 +1,137 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FileInfoToctouBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.IO;\nclass Config { public string Input = \"\"; public string Output = \"\"; public FileInfo Info = new FileInfo(\"x\"); }\n" + + "class Marker { public bool Exists => true; }\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAGuardOnAMemberPathAndSilentForASiblingMember() + { + return VerifyAsync(""" + string M(Config config) + { + if (!File.Exists(config.Input)) return string.Empty; + var other = File.ReadAllText(config.Output); + return {|E128056:File.ReadAllText(config.Input)|} + other; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAGuardThroughAFileInfoStoredInAMember() + { + return VerifyAsync(""" + string M(Config config) + { + if (!config.Info.Exists) return string.Empty; + return {|E128056:File.ReadAllText(config.Info.FullName)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardedValueIsTheResultOfACall() + { + return VerifyAsync(""" + static string Path() => "x"; + + string M() + { + if (!File.Exists(Path())) return string.Empty; + return File.ReadAllText(Path()); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheExistsPropertyBelongsToAnotherType() + { + return VerifyAsync(""" + string M(Marker marker, string path) + { + if (!marker.Exists) return string.Empty; + return File.ReadAllText(path); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReadSitsInsideATryCatch() + { + return VerifyAsync(""" + string M(string path) + { + if (!File.Exists(path)) return string.Empty; + try + { + return File.ReadAllText(path); + } + catch (IOException) + { + return string.Empty; + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTryHasOnlyAFinallyBlock() + { + return VerifyAsync(""" + string M(string path) + { + if (!File.Exists(path)) return string.Empty; + try + { + return {|E128056:File.ReadAllText(path)|}; + } + finally + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAReadWithoutArgumentsOrOfAnotherFileType() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class File2 + { + public static bool Exists(string path) => true; + public static string ReadAllText(string path) => path; + } + class C + { + string M(string path) + { + if (!File2.Exists(path)) return string.Empty; + return File2.ReadAllText(path); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FileInfoToctouCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FileInfoToctouCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..b7e3fd33 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FileInfoToctouCodeFixBranchCoverageTests.cs @@ -0,0 +1,102 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FileInfoToctouCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsAReturnStatementAndReturnsDefaultFromTheCatch() + { + return CodeFixTestRunner.RunAsync( + """ + using System.IO; + class Loader + { + string? Load(string path) + { + if (!File.Exists(path)) return string.Empty; + return {|E128056:File.ReadAllText(path)|}; + } + } + """, + """ + using System.IO; + class Loader + { + string? Load(string path) + { + if (!File.Exists(path)) return string.Empty; + try + { + return File.ReadAllText(path); + } + catch (System.IO.IOException) + { + return default; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsAStatementInAVoidMethodWithAnEmptyCatch() + { + return CodeFixTestRunner.RunAsync( + """ + using System.IO; + class Loader + { + void Load(string path) + { + if (!File.Exists(path)) return; + Consume({|E128056:File.ReadAllText(path)|}); + } + + static void Consume(string text) { } + } + """, + """ + using System.IO; + class Loader + { + void Load(string path) + { + if (!File.Exists(path)) return; + try + { + Consume(File.ReadAllText(path)); + } + catch (System.IO.IOException) + { + } + } + + static void Consume(string text) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAValueReturningMethodReadsIntoALocal() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.IO; + class Loader + { + string Load(string path) + { + if (!File.Exists(path)) return string.Empty; + var text = {|E128056:File.ReadAllText(path)|}; + return text; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncBranchCoverageTests.cs new file mode 100644 index 00000000..3295ef9a --- /dev/null +++ b/tests/E128.Analyzers.Tests/FileStreamWithoutUseAsyncBranchCoverageTests.cs @@ -0,0 +1,56 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FileStreamWithoutUseAsyncBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenUseAsyncIsAParenthesizedFalse() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + static void M(string path) + { + using var stream = {|E128190:new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, (false))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenOptionsAreACastOfZero() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + static void M(string path) + { + using var stream = {|E128190:new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, (FileOptions)0)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenOptionsAreACastOfTheAsynchronousBit() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + static void M(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, (FileOptions)0x40000000); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..6a09718d --- /dev/null +++ b/tests/E128.Analyzers.Tests/FileSystemPathAnalyzerBranchCoverageTests.cs @@ -0,0 +1,269 @@ +using System.Threading.Tasks; +using E128.Analyzers.FileSystem; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FileSystemPathAnalyzerBranchCoverageTests +{ + private const string CliStubs = """ + using System; + + class Option + { + public Option() { } + public Option(string name) { } + } + + class Option + { + public Option(string name) { } + } + + class Argument + { + public Argument(string name) { } + } + + namespace Q + { + class Option + { + public Option(string name) { } + } + + class Holder + { + public Holder(string name) { } + } + } + + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { MarkupOptions = MarkupOptions.UseFirstDescriptor }); + } + + private static Task VerifyCliAsync(string statements) + { + return VerifyAsync(CliStubs + "class C { void M(string name) { " + statements + " } }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAParameterThatReachesFileIoThroughTwoPathHops() + { + return VerifyAsync(""" + using System.IO; + + class C + { + string _external = ""; + + void M(string {|E128001:root|}) + { + var other = Path.Combine(_external, "y"); + var a = Path.Combine(root, "x"); + var b = Path.GetFullPath(a); + File.ReadAllText(b); + File.Exists(other); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCallsThatAreNotSystemIo() + { + return VerifyAsync(""" + static class File + { + public static string ReadAllText(string text) { return text; } + } + + class FileInfo + { + public FileInfo() { } + public FileInfo(string text) { } + } + + class Reader + { + public string ReadAllText(string text) { return text; } + } + + class C + { + Reader Get() { return new Reader(); } + + string Local(string text) { return text; } + + void M(string root, string tail) + { + Local(root); + Get().ReadAllText(root); + File.ReadAllText(root); + var info = new FileInfo(root); + var empty = new FileInfo(); + _ = info; + _ = empty; + _ = tail; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheIoArgumentIsNotAPlainName() + { + return VerifyAsync(""" + using System.IO; + using System.Collections.Generic; + using System.Text; + + class C + { + void M(string root) + { + File.ReadAllText("lit"); + File.ReadAllText(root + "x"); + var stream = new FileStream("lit", FileMode.Open); + var other = new FileStream(root + "x", FileMode.Open); + var list = new List(new[] { root }); + var builder = new StringBuilder(root); + _ = stream; + _ = other; + _ = list; + _ = builder; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForQualifiedOptionTypes() + { + return VerifyCliAsync("""var option = new Q.Option<{|E128001:string|}>("--output");"""); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForDirectoryAndFolderOptionNames() + { + return VerifyCliAsync(""" + var a = new Option<{|E128001:string|}>("--output-dir"); + var b = new Option<{|E128001:string|}>("--folder-path"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnArgumentWithAFileName() + { + return VerifyCliAsync("""var a = new Argument<{|E128001:string|}>("filename");"""); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForOptionShapesThatAreNotStringPaths() + { + return VerifyCliAsync(""" + var a = new Option("--input"); + var b = new Option("--input"); + var c = new Option("--input"); + var d = new Option("--input"); + var e = new Option(); + var f = new Option(name); + var g = new Option("--"); + var h = new Option { }; + var i = new Q.Holder("--input"); + var j = new Q.Option("--input"); + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Path.Combine(a)", true)] + [InlineData("Path.GetFullPath(a)", true)] + [InlineData("path.Combine(a)", false)] + [InlineData("Path.Missing(a)", false)] + [InlineData("Combine(a)", false)] + public void IsPathMethodCall_MatchesOnlyThePathClass(string text, bool expected) + { + var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression(text); + Assert.Equal(expected, FileSystemPathHelpers.IsPathMethodCall(invocation)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Option", "Option")] + [InlineData("Argument", "Argument")] + [InlineData("System.CommandLine.Option", "Option")] + [InlineData("System.CommandLine.Argument", "Argument")] + [InlineData("Other", null)] + [InlineData("System.CommandLine.Other", null)] + [InlineData("System.CommandLine.Option", null)] + [InlineData("string", null)] + public void ExtractGenericCliType_FindsOptionAndArgument(string text, string? expectedName) + { + var result = FileSystemPathHelpers.ExtractGenericCliType(SyntaxFactory.ParseTypeName(text)); + Assert.Equal(expectedName, result?.Identifier.ValueText); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Option", true)] + [InlineData("Option", false)] + [InlineData("Option", false)] + [InlineData("Option", false)] + public void GetCliStringTypeArg_AcceptsOnlyOneStringArgument(string text, bool expected) + { + var generic = (GenericNameSyntax)SyntaxFactory.ParseTypeName(text); + Assert.Equal(expected, FileSystemPathHelpers.GetCliStringTypeArg(generic) is not null); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("(\"--output\")", true, "--output", "output")] + [InlineData("(\"-p\")", false, "-p", "p")] + [InlineData("(\"--\")", false, "--", "")] + [InlineData("(name)", false, "", "")] + [InlineData("(5)", false, "", "")] + [InlineData("()", false, "", "")] + public void TryGetPathCliName_ReadsTheFirstStringLiteral(string text, bool expected, string raw, string stripped) + { + var list = SyntaxFactory.ParseArgumentList(text); + Assert.Equal(expected, FileSystemPathHelpers.TryGetPathCliName(list, out var rawName, out var strippedName)); + Assert.Equal(raw, rawName); + Assert.Equal(stripped, strippedName); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetPathCliName_RejectsAMissingArgumentList() + { + Assert.False(FileSystemPathHelpers.TryGetPathCliName(null, out var rawName, out var strippedName)); + Assert.Empty(rawName); + Assert.Empty(strippedName); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("output-dir", "directory path", "'Option'")] + [InlineData("folder", "directory path", "'Option'")] + [InlineData("input-file", "file path", "'Option'")] + [InlineData("path", "file system path", "'Option' or 'Option'")] + public void GetCliSuggestion_NamesTheTypeThatMatchesTheOptionName(string name, string description, string suggestion) + { + Assert.Equal((description, suggestion), FileSystemPathHelpers.GetCliSuggestion(name, "Option")); + } +} diff --git a/tests/E128.Analyzers.Tests/FileSystemPathCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FileSystemPathCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..3e87ab19 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FileSystemPathCodeFixBranchCoverageTests.cs @@ -0,0 +1,69 @@ +using System.Threading.Tasks; +using E128.Analyzers.FileSystem; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FileSystemPathCodeFixBranchCoverageTests +{ + private const string OptionStub = + "class Option { public Option(string name) { } }\n" + + "class Argument { public Argument(string name) { } }\n"; + + private static Task RunOptionAsync(string source, string typeName) + { + var fixedCode = "using System.IO;\n\n" + + OptionStub + + source.Replace("{|E128001:string|}", typeName, System.StringComparison.Ordinal); + return CodeFixTestRunner.RunAsync( + OptionStub + source, + fixedCode, + markupOptions: MarkupOptions.UseFirstDescriptor); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ChangesAFileOptionToFileInfo() + { + return RunOptionAsync( + """class C { void M() { var opt = new Option<{|E128001:string|}>("--file"); } }""", + "FileInfo"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ChangesADirectoryArgumentToDirectoryInfo() + { + return RunOptionAsync( + """class C { void M() { var arg = new Argument<{|E128001:string|}>("directory"); } }""", + "DirectoryInfo"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_OffersNothingForAParameterUsedByFileIo() + { + const string code = """ + using System.IO; + + class C + { + string M(string {|E128001:target|}) + { + return File.ReadAllText(target); + } + } + """; + + return CodeFixTestRunner.RunAsync( + code, + code.Replace("{|E128001:target|}", "target", System.StringComparison.Ordinal), + markupOptions: MarkupOptions.UseFirstDescriptor, + options: new CodeFixTestOptions + { + FixedExpected = [new DiagnosticResult("E128001", Microsoft.CodeAnalysis.DiagnosticSeverity.Warning).WithSpan(5, 21, 5, 27) + .WithArguments("target", "file path", "FileInfo")] + }); + } +} diff --git a/tests/E128.Analyzers.Tests/FinallyBlockCleanupCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FinallyBlockCleanupCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..c0c79d78 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FinallyBlockCleanupCodeFixBranchCoverageTests.cs @@ -0,0 +1,72 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FinallyBlockCleanupCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_WrapsTheCleanupCallInATryCatchOfException() + { + return CodeFixTestRunner.RunAsync( + """ + using System.IO; + class C + { + void M(string path) + { + try { } + finally + { + {|E128057:Directory.Delete(path, true)|}; + } + } + } + """, + """ + using System.IO; + class C + { + void M(string path) + { + try { } + finally + { + try + { + Directory.Delete(path, true); + } + catch (System.Exception) + { + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCleanupCallSitsInALocalDeclaration() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + using System.IO; + class C + { + void M(string path) + { + try { } + finally + { + Action cleanup = () => {|E128057:File.Delete(path)|}; + cleanup(); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsAesGcmTagSizeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsAesGcmTagSizeBranchCoverageTests.cs new file mode 100644 index 00000000..12a517c3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsAesGcmTagSizeBranchCoverageTests.cs @@ -0,0 +1,59 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsAesGcmTagSizeBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortTagBuffersAndConstructorTagSizes() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] key, byte[] nonce, byte[] plain, byte[] cipher, byte[] tag, int size) + { + var a = {|E128149:new AesGcm(key, 12)|}; + var b = new AesGcm(key, 16); + var c = new AesGcm(key, size); + a.Encrypt(nonce, plain, cipher, tag); + {|E128149:a.Encrypt(nonce, plain, cipher, new byte[12])|}; + {|E128149:a.Decrypt(nonce, cipher, new byte[8], plain)|}; + a.Encrypt(nonce, plain, cipher, new byte[16]); + a.Decrypt(nonce, cipher, tag, plain); + a.Dispose(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenEncryptOrDecryptBelongsToAnotherType() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class Own + { + public void Encrypt(byte[] tag) { } + } + + class C + { + void M(RSA rsa, byte[] data, Own own) + { + var a = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256); + own.Encrypt(new byte[4]); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsCipherModeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsCipherModeBranchCoverageTests.cs new file mode 100644 index 00000000..92d12765 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsCipherModeBranchCoverageTests.cs @@ -0,0 +1,108 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsCipherModeBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForbiddenModeFieldsButNotAuthenticatedOrCbcModes() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(Aes aes) + { + aes.Mode = {|E128144:CipherMode.ECB|}; + aes.Mode = {|E128144:CipherMode.OFB|}; + aes.Mode = {|E128144:CipherMode.CFB|}; + aes.Mode = CipherMode.CBC; + aes.Mode = CipherMode.CTS; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAForbiddenModeIsOnlyCompared() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + bool M(CipherMode mode) + { + var a = mode == CipherMode.ECB; + var b = mode != CipherMode.CFB; + var c = mode is CipherMode.OFB; + return a && b && c && mode.Equals(CipherMode.ECB); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NumericCastsToForbiddenModes() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(Aes aes, int number) + { + aes.Mode = {|E128144:(CipherMode)2|}; + aes.Mode = {|E128144:(CipherMode)3|}; + aes.Mode = {|E128144:(CipherMode)4|}; + aes.Mode = (CipherMode)1; + aes.Mode = (CipherMode)5; + aes.Mode = (CipherMode)number; + aes.Mode = (CipherMode)PaddingMode.PKCS7; + var same = aes.Mode == (CipherMode)2; + var number2 = (int)CipherMode.CBC; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EcbAndCfbHelperMethodsOfSymmetricAlgorithms() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + class C + { + void M(Aes aes, byte[] data, byte[] iv, Span destination) + { + var a = {|E128144:aes.EncryptEcb(data, PaddingMode.PKCS7)|}; + var b = {|E128144:aes.DecryptEcb(data, PaddingMode.PKCS7)|}; + var c = {|E128144:aes.TryEncryptEcb(data, destination, PaddingMode.PKCS7, out _)|}; + var d = {|E128144:aes.TryDecryptEcb(data, destination, PaddingMode.PKCS7, out _)|}; + var e = {|E128144:aes.EncryptCfb(data, iv)|}; + var f = {|E128144:aes.DecryptCfb(data, iv)|}; + var g = {|E128144:aes.TryEncryptCfb(data, iv, destination, out _)|}; + var h = {|E128144:aes.TryDecryptCfb(data, iv, destination, out _)|}; + var i = aes.EncryptCbc(data, iv); + var j = aes.CreateEncryptor(); + var k = new Own().EncryptEcb(data); + } + } + + class Own + { + public byte[] EncryptEcb(byte[] data) => data; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsDirectInstantiationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsDirectInstantiationBranchCoverageTests.cs new file mode 100644 index 00000000..ded34a94 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsDirectInstantiationBranchCoverageTests.cs @@ -0,0 +1,173 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsDirectInstantiationBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ManagedAndCngTypesThatAFactoryCanReplace() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(int size, ECCurve curve, string name) + { + var a = {|E128142:new AesManaged()|}; + var b = {|E128142:new AesCng()|}; + var c = {|E128142:new SHA256Managed()|}; + var e = {|E128142:new RSACng(3072)|}; + var f = {|E128142:new ECDsaCng(curve)|}; + var g = {|E128142:new ECDiffieHellmanCng(curve)|}; + var h = {|E128142:new DSACng(2048)|}; + var i = {|E128142:new AesCng(name)|}; + var j = {|E128142:new RSACng(size)|}; + var k = {|E128142:new RSACng()|}; + var l = {|E128142:new ECDsaCng(size)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenACngConstructorOpensAPersistedKey() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(CngKey key) + { + var a = new RSACng(key); + var b = new ECDsaCng(key); + var c = new AesCng("key", CngProvider.MicrosoftSoftwareKeyStorageProvider); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RijndaelFactoryAndTypes() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M() + { + var a = {|E128142:Rijndael.Create()|}; + var b = {|E128142:new RijndaelManaged()|}; + var c = Aes.Create(); + var d = new Other(); + } + } + + class Other + { + public static Other Create() => new Other(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AManagedNamedTypeWithNoBaseNameUsingTheGenericFactoryAdvice() + { + return VerifyAsync(""" + namespace System.Security.Cryptography + { + public class Managed + { + } + + public class Cng + { + public Cng(int value) { } + } + } + + class C + { + void M() + { + var a = {|E128142:new System.Security.Cryptography.Managed()|}; + var b = {|E128142:new System.Security.Cryptography.Cng(1)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ARijndaelSymmetricAlgorithmOutsideTheCryptographyNamespace() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + namespace Vendor + { + public sealed class Rijndael : SymmetricAlgorithm + { + public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => throw new System.NotSupportedException(); + + public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => throw new System.NotSupportedException(); + + public override void GenerateIV() { } + + public override void GenerateKey() { } + } + + public sealed class RijndaelManaged + { + } + + public sealed class Plain + { + } + } + + class C + { + void M() + { + var a = {|E128142:new Vendor.Rijndael()|}; + var b = new Vendor.RijndaelManaged(); + var c = new Vendor.Plain(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherRuleOwnsTheTypeOrTheTypeIsNotReplaceable() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class BlowfishManaged + { + } + + class C + { + void M(byte[] key) + { + var a = new SHA1Managed(); + var c = new BlowfishManaged(); + var d = new HMACSHA256(key); + var e = new System.Text.StringBuilder(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsForbiddenAlgorithmNameBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsForbiddenAlgorithmNameBranchCoverageTests.cs new file mode 100644 index 00000000..8641c6d7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsForbiddenAlgorithmNameBranchCoverageTests.cs @@ -0,0 +1,164 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsForbiddenAlgorithmNameBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CreationAndStaticFactoriesOfAnExcludedCipher() + { + return VerifyAsync(""" + using System; + + class BlowfishEngine + { + public static BlowfishEngine Create() => {|E128148:new BlowfishEngine()|}; + + public static byte[] HashData(byte[] data) => data; + + public static void Reset() { } + + public void Run() { } + } + + class C + { + void M(BlowfishEngine engine, byte[] data) + { + var a = {|E128148:new BlowfishEngine()|}; + var b = {|E128148:BlowfishEngine.Create()|}; + var c = {|E128148:BlowfishEngine.HashData(data)|}; + Func d = {|E128148:BlowfishEngine.Create|}; + BlowfishEngine.Reset(); + engine.Run(); + Action e = BlowfishEngine.Reset; + Action f = engine.Run; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NamesThatMatchAWholeWordOnly() + { + return VerifyAsync(""" + class Rc4Transform { } + + class Arcfour { } + + class Cast5Engine { } + + class Cast6_Cipher { } + + class SkipjackEngine { } + + class RC4Thing { } + + class Brc4 { } + + class Forecast5 { } + + class C + { + void M() + { + var a = {|E128148:new Rc4Transform()|}; + var b = {|E128148:new Arcfour()|}; + var c = {|E128148:new Cast5Engine()|}; + var d = {|E128148:new Cast6_Cipher()|}; + var e = {|E128148:new SkipjackEngine()|}; + var f = {|E128148:new RC4Thing()|}; + var g = new Brc4(); + var h = new Forecast5(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_IdeaOnlyWhenTheTypeLooksLikeACipher() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + interface ICipherAlgorithm { } + + class CipherBase { } + + class IdeaEngine { } + + class IdeaCng { } + + class IdeaWithBase : CipherBase { } + + class IdeaWithInterface : ICipherAlgorithm { } + + class IdeaRankingAlgorithm { } + + class IdeaBoard { } + + abstract class IdeaSymmetric : SymmetricAlgorithm + { + public static byte[] HashData(byte[] data) => data; + } + + class IDEA { } + + namespace Acme.Crypto + { + class IDEA { } + } + + namespace Acme.Cipher + { + class IdeaOnly { } + } + + class C + { + void M() + { + var a = {|E128148:new IdeaEngine()|}; + var b = {|E128148:new IdeaCng()|}; + var c = {|E128148:new IdeaWithBase()|}; + var d = {|E128148:new IdeaWithInterface()|}; + var e = new IdeaRankingAlgorithm(); + var f = new IdeaBoard(); + var g = new IDEA(); + var h = {|E128148:new Acme.Crypto.IDEA()|}; + var i = new Acme.Cipher.IdeaOnly(); + var j = {|E128148:IdeaSymmetric.HashData(new byte[1])|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTypeIsAFrameworkTypeOrNamedLikeAnAllowedAlgorithm() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] data) + { + var a = new System.Text.StringBuilder(); + var b = SHA256.HashData(data); + var c = Aes.Create(); + var d = new System.Collections.Generic.List(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsHashNameResolutionBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsHashNameResolutionBranchCoverageTests.cs new file mode 100644 index 00000000..76a2b81a --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsHashNameResolutionBranchCoverageTests.cs @@ -0,0 +1,330 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsHashNameResolutionBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_BothArmsOfConditionalCoalesceAndSwitch() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static void Use(HashAlgorithmName name) { } + + void M(bool flag, HashAlgorithmName? maybe, int kind) + { + {|E128071:Use(flag ? HashAlgorithmName.MD5 : HashAlgorithmName.SHA256)|}; + {|E128071:Use(flag ? HashAlgorithmName.SHA256 : HashAlgorithmName.MD5)|}; + {|E128071:Use(maybe ?? HashAlgorithmName.MD5)|}; + {|E128071:Use(kind switch { 0 => HashAlgorithmName.SHA256, 1 => HashAlgorithmName.MD5, _ => HashAlgorithmName.SHA384 })|}; + Use(flag ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA512); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AForbiddenNameOnlyOncePerCall() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static void Use(HashAlgorithmName name) { } + + static void Two(HashAlgorithmName first, HashAlgorithmName second) { } + + void M(bool flag) + { + {|E128071:Use(flag ? HashAlgorithmName.MD5 : HashAlgorithmName.MD5)|}; + {|E128071:Two(HashAlgorithmName.MD5, HashAlgorithmName.MD5)|}; + {|E128071:Two(second: HashAlgorithmName.MD5, first: HashAlgorithmName.SHA256)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NameHeldInUnreassignedLocalsUpToTheDepthLimit() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static void Use(HashAlgorithmName name) { } + + void M() + { + var l1 = HashAlgorithmName.MD5; + var l2 = l1; + var l3 = l2; + var l4 = l3; + var l5 = l4; + var l6 = l5; + {|E128071:Use(l4)|}; + Use(l5); + Use(l6); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALocalIsReassignedOrPassedByRef() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static void Use(HashAlgorithmName name) { } + + static void Fill(out HashAlgorithmName name) { name = HashAlgorithmName.SHA256; } + + static void Bump(ref HashAlgorithmName name) { } + + void M() + { + var reassigned = HashAlgorithmName.MD5; + reassigned = HashAlgorithmName.SHA256; + Use(reassigned); + + var byRef = HashAlgorithmName.MD5; + Bump(ref byRef); + Use(byRef); + + HashAlgorithmName viaOut = HashAlgorithmName.MD5; + Fill(out viaOut); + Use(viaOut); + + HashAlgorithmName second; + var tupleTarget = HashAlgorithmName.MD5; + (tupleTarget, second) = (HashAlgorithmName.SHA256, HashAlgorithmName.SHA384); + Use(tupleTarget); + + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ReadonlyFieldNameUnlessAConstructorWritesIt() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static readonly HashAlgorithmName Fixed = HashAlgorithmName.MD5; + + readonly HashAlgorithmName byConstructor = HashAlgorithmName.MD5; + + readonly HashAlgorithmName byInit = HashAlgorithmName.MD5; + + readonly HashAlgorithmName untouched = HashAlgorithmName.MD5; + + int Setter + { + init { byInit = HashAlgorithmName.SHA256; } + } + + C() + { + byConstructor = HashAlgorithmName.SHA256; + } + + static void Use(HashAlgorithmName name) { } + + void M() + { + {|E128071:Use(Fixed)|}; + {|E128071:Use(Fixed)|}; + {|E128071:Use(untouched)|}; + Use(byConstructor); + Use(byInit); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NameBuiltFromAStringOrAnObjectIdentifier() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static void Use(HashAlgorithmName name) { } + + void M(string text, string oid) + { + {|E128071:Use(new HashAlgorithmName("MD5"))|}; + {|E128071:Use(HashAlgorithmName.FromOid("1.3.14.3.2.26"))|}; + {|E128071:Use(HashAlgorithmName.FromOid(" 1.2.840.113549.2.5 "))|}; + Use(new HashAlgorithmName(text)); + Use(new HashAlgorithmName()); + Use(new HashAlgorithmName("SHA256")); + Use(HashAlgorithmName.FromOid("9.9.9")); + Use(HashAlgorithmName.FromOid(oid)); + Use(HashAlgorithmName.FromOid("2.16.840.1.101.3.4.2.1")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NameStoredInAMutableFieldOrAPropertyButNotAReadonlyField() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + static readonly HashAlgorithmName ReadonlyBad = HashAlgorithmName.MD5; + + static HashAlgorithmName mutableBad = {|E128071:HashAlgorithmName.MD5|}; + + static HashAlgorithmName PropertyBad { get; } = {|E128071:HashAlgorithmName.SHA1|}; + + static HashAlgorithmName mutableGood = HashAlgorithmName.SHA256; + + static HashAlgorithmName PropertyGood { get; } = HashAlgorithmName.SHA512; + + static string text = "MD5"; + + static int Number { get; } = 5; + + static int numberField = 5; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NameAssignedToAHashNameTarget() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + HashAlgorithmName field; + + HashAlgorithmName Property { get; set; } + + void M() + { + {|E128071:field = HashAlgorithmName.MD5|}; + {|E128071:Property = HashAlgorithmName.SHA1|}; + field = HashAlgorithmName.SHA256; + int number; + number = 5; + HashAlgorithmName a, b; + (a, b) = ({|E128071:HashAlgorithmName.MD5|}, HashAlgorithmName.SHA256); + (a, number) = ({|E128071:HashAlgorithmName.SHA1|}, 5); + } + + void Other(HashAlgorithmName pair) + { + var (x, y) = (HashAlgorithmName.MD5, HashAlgorithmName.SHA1); + (field, Property) = Pair(); + } + + (HashAlgorithmName, HashAlgorithmName) Pair() => (HashAlgorithmName.SHA256, HashAlgorithmName.SHA256); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAHashNameProbeReadsTheNameWithoutSelectingIt() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Security.Cryptography; + class Registry + { + public bool Contains(HashAlgorithmName name) => false; + } + + class C + { + void M(List names, Dictionary map, HashSet set, Registry registry) + { + var a = names.Contains(HashAlgorithmName.MD5); + var b = names.IndexOf(HashAlgorithmName.MD5); + var c = names.Remove(HashAlgorithmName.MD5); + var d = map.ContainsKey(HashAlgorithmName.MD5); + var e = map.TryGetValue(HashAlgorithmName.MD5, out _); + var f = HashAlgorithmName.MD5.Equals(HashAlgorithmName.SHA256); + var g = set.Contains(HashAlgorithmName.SHA1); + var h = {|E128071:registry.Contains(HashAlgorithmName.MD5)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAFieldReferenceIsAComparisonOfTheTripleDesPbeValue() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(PbeEncryptionAlgorithm algorithm, object boxed) + { + var a = algorithm == PbeEncryptionAlgorithm.TripleDes3KeyPkcs12; + var b = algorithm != PbeEncryptionAlgorithm.TripleDes3KeyPkcs12; + var c = algorithm is PbeEncryptionAlgorithm.TripleDes3KeyPkcs12; + var d = algorithm.Equals(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12); + var e = PbeEncryptionAlgorithm.TripleDes3KeyPkcs12.Equals(algorithm); + var f = algorithm.HasFlag(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12); + var g = (int)PbeEncryptionAlgorithm.TripleDes3KeyPkcs12 == 3; + var h = boxed.Equals((object)PbeEncryptionAlgorithm.TripleDes3KeyPkcs12); + switch (algorithm) + { + case PbeEncryptionAlgorithm.TripleDes3KeyPkcs12: + break; + } + + var chosen = {|E128071:PbeEncryptionAlgorithm.TripleDes3KeyPkcs12|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForbiddenTypesThroughAliasesAndBases() + { + return VerifyAsync(""" + using System.Security.Cryptography; + using Md = System.Security.Cryptography.MD5; + class MyHash : HMACSHA1 + { + } + + class C + { + void M() + { + var a = {|E128071:Md.Create()|}; + var b = {|E128071:new MyHash()|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsHmacKeyLengthBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsHmacKeyLengthBranchCoverageTests.cs new file mode 100644 index 00000000..70b7519a --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsHmacKeyLengthBranchCoverageTests.cs @@ -0,0 +1,376 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsHmacKeyLengthBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortKeyFromEachLiteralShape() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] data) + { + var a = {|E128151:new HMACSHA256(new byte[16])|}; + var b = {|E128151:new HMACSHA256(new byte[] { 1, 2, 3 })|}; + var c = {|E128151:new HMACSHA256([1, 2, 3])|}; + var d = {|E128151:HMACSHA256.HashData(stackalloc byte[16], data)|}; + var e = {|E128151:HMACSHA256.HashData(stackalloc byte[] { 1, 2 }, data)|}; + var f = {|E128151:HMACSHA256.HashData(stackalloc[] { (byte)1, (byte)2, (byte)3 }, data)|}; + var g = {|E128151:HMACSHA256.HashData(source: data, key: new byte[8])|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheKeyLengthIsUnknownOrLongEnough() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] data, byte[] key, int size) + { + var a = new HMACSHA256(key); + var b = new HMACSHA256(new byte[size]); + var c = new HMACSHA256([.. key]); + var d = new HMACSHA256(new byte[32]); + var e = new HMACSHA384(new byte[48]); + var f = new HMACSHA512(new byte[64]); + var g = new HMACSHA256(); + var h = HMACSHA256.HashData(stackalloc byte[size], data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_KeyThatDoesNotMeetTheLargerHashOutput() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M() + { + var a = {|E128151:new HMACSHA384(new byte[40])|}; + var b = {|E128151:new HMACSHA512(new byte[60])|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTypeIsNotACoveredHmac() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class HMACSHA256Wrapper + { + public HMACSHA256Wrapper(byte[] key) { } + } + + class C + { + void M() + { + var a = new HMACMD5(new byte[4]); + var b = new HMACSHA256Wrapper(new byte[4]); + var c = new System.Text.StringBuilder(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortKeyFromEncodedStrings() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + using System.Text; + class C + { + void M(byte[] data) + { + var a = {|E128151:HMACSHA256.HashData(Encoding.UTF8.GetBytes("short"), data)|}; + var b = {|E128151:HMACSHA256.HashData(Encoding.ASCII.GetBytes("short"), data)|}; + var c = {|E128151:HMACSHA256.HashData(Encoding.Unicode.GetBytes("short"), data)|}; + var d = {|E128151:HMACSHA256.HashData(Encoding.Latin1.GetBytes("short"), data)|}; + var e = {|E128151:HMACSHA256.HashData(Encoding.UTF32.GetBytes("short"), data)|}; + var f = {|E128151:HMACSHA256.HashData(Convert.FromBase64String("AAAA"), data)|}; + var g = {|E128151:HMACSHA256.HashData(Convert.FromHexString("0102"), data)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheEncodedStringIsUnreadable() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + using System.Text; + class C + { + void M(byte[] data, string text, Encoding encoding) + { + var a = HMACSHA256.HashData(Encoding.UTF8.GetBytes(text), data); + var b = HMACSHA256.HashData(encoding.GetBytes("short"), data); + var c = HMACSHA256.HashData(Encoding.Default.GetBytes("short"), data); + var d = HMACSHA256.HashData(Convert.FromBase64String("not base64!"), data); + var e = HMACSHA256.HashData(Convert.FromHexString("abc"), data); + var f = HMACSHA256.HashData(Convert.FromHexString("zz"), data); + var g = HMACSHA256.HashData(Convert.FromBase64String(text), data); + var h = HMACSHA256.HashData(Convert.FromHexString(text), data); + var i = HMACSHA256.HashData(Convert.FromBase64CharArray(new char[4], 0, 4), data); + var j = HMACSHA256.HashData(Encoding.UTF8.GetBytes(new char[4]), data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortKeyFromSlicesAndRanges() + { + return VerifyAsync(""" + using System; + using System.Runtime.CompilerServices; + using System.Security.Cryptography; + class C + { + void M(byte[] data) + { + var a = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan(0, 8), data)|}; + var b = {|E128151:HMACSHA256.HashData(new byte[34].AsSpan(8), data)|}; + var c = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan(..8), data)|}; + var d = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan(8..16), data)|}; + var e = {|E128151:HMACSHA256.HashData(new byte[40].AsSpan(^4..), data)|}; + var f = {|E128151:HMACSHA256.HashData(new byte[40].AsSpan(^36..^8), data)|}; + var h = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan().Slice(2, 8), data)|}; + var i = {|E128151:HMACSHA256.HashData(new byte[34].AsSpan().Slice(4), data)|}; + var j = {|E128151:HMACSHA256.HashData(RuntimeHelpers.GetSubArray(new byte[64], 0..8), data)|}; + var k = {|E128151:HMACSHA256.HashData((new byte[64])[..8], data)|}; + var l = {|E128151:HMACSHA256.HashData(new byte[8].AsSpan(), data)|}; + var m = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan(length: 8, start: 0), data)|}; + var n = {|E128151:HMACSHA256.HashData(new byte[64].AsSpan()[..8], data)|}; + var o = {|E128151:HMACSHA256.HashData(new byte[40].AsSpan()[^4..], data)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASliceBoundIsUnknownOrOutOfOrder() + { + return VerifyAsync(""" + using System; + using System.Runtime.CompilerServices; + using System.Security.Cryptography; + class C + { + void M(byte[] data, byte[] key, int start, int count, Range range) + { + var a = HMACSHA256.HashData(key.AsSpan(4), data); + var b = HMACSHA256.HashData(new byte[40].AsSpan(start), data); + var c = HMACSHA256.HashData(new byte[40].AsSpan(64), data); + var d = HMACSHA256.HashData(new byte[40].AsSpan(0, count), data); + var e = HMACSHA256.HashData(new byte[40].AsSpan(0, -1), data); + var f = HMACSHA256.HashData(new byte[40].AsSpan(range), data); + var g = HMACSHA256.HashData(new byte[40].AsSpan(16..8), data); + var h = HMACSHA256.HashData(new byte[40].AsSpan(^64..), data); + var i = HMACSHA256.HashData(key.AsSpan(^4..), data); + var j = HMACSHA256.HashData(key.AsSpan(..^4), data); + var k = HMACSHA256.HashData(key.AsSpan(..), data); + var l = HMACSHA256.HashData(new byte[40].AsSpan(start..), data); + var m = HMACSHA256.HashData(new byte[40].AsSpan(..start), data); + var n = HMACSHA256.HashData(RuntimeHelpers.GetSubArray(key, range), data); + var o = HMACSHA256.HashData(key.AsSpan().Slice(start), data); + var p = HMACSHA256.HashData(key[..start], data); + var q = HMACSHA256.HashData(key.AsSpan()[..start], data); + var r = HMACSHA256.HashData((new byte[40])[^64..], data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortKeyHeldInAFieldOrLocal() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + private static readonly byte[] ShortField = new byte[8]; + private static readonly byte[] CtorField; + private byte[] mutable = new byte[8]; + + static C() + { + CtorField = new byte[8]; + } + + void M(byte[] data) + { + var local = new byte[8]; + var alias = local; + var reassigned = new byte[8]; + reassigned = new byte[64]; + var a = {|E128151:HMACSHA256.HashData(local, data)|}; + var b = {|E128151:HMACSHA256.HashData(alias, data)|}; + var c = {|E128151:HMACSHA256.HashData(ShortField, data)|}; + var d = HMACSHA256.HashData(reassigned, data); + var e = HMACSHA256.HashData(CtorField, data); + var f = HMACSHA256.HashData(mutable, data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_HashNameBasedHmacHelpers() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(HashAlgorithmName dynamicName) + { + var name = HashAlgorithmName.SHA256; + var a = {|E128151:IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, new byte[8])|}; + var b = {|E128151:IncrementalHash.CreateHMAC(name, new byte[8])|}; + var c = {|E128151:IncrementalHash.CreateHMAC(HashAlgorithmName.SHA3_256, new byte[8])|}; + var d = {|E128151:IncrementalHash.CreateHMAC(HashAlgorithmName.FromOid("2.16.840.1.101.3.4.2.8"), new byte[8])|}; + var e = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, new byte[40]); + var f = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, new byte[8]); + var g = IncrementalHash.CreateHMAC(dynamicName, new byte[8]); + var h = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_HmacNamedHelpersInTheCryptographyNamespace() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + namespace System.Security.Cryptography + { + public static class HmacExtras + { + public static void NoHashNameHmac(byte[] key) { } + + public static void TwoHashNamesHmac(byte[] key, HashAlgorithmName first, HashAlgorithmName second) { } + } + } + + class C + { + void M(byte[][] jagged, HashAlgorithmName unknown) + { + HmacExtras.NoHashNameHmac(new byte[8]); + {|E128151:HmacExtras.TwoHashNamesHmac(new byte[8], unknown, HashAlgorithmName.SHA256)|}; + var a = HMACSHA256.HashData(jagged[0], new byte[1]); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnHmacNamedMethodComesFromOutsideCryptography() + { + return VerifyAsync(""" + using System.Security.Cryptography; + static class Own + { + public static void MakeHmac(HashAlgorithmName name, byte[] key) { } + } + + class C + { + void M() + { + Own.MakeHmac(HashAlgorithmName.SHA256, new byte[8]); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortKeyAssignedToTheKeyProperty() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(HMACSHA256 typed, HMAC unknown) + { + {|E128151:typed.Key = new byte[8]|}; + typed.Key = new byte[32]; + unknown.Key = new byte[8]; + + HMAC based = new HMACSHA256(new byte[32]); + {|E128151:based.Key = new byte[8]|}; + + HMAC plain = HMAC.Create("HMACSHA256"); + plain.Key = new byte[8]; + + (typed.Key, _) = ({|E128151:new byte[8]|}, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAKeyNamedMemberIsNotAnHmacKey() + { + return VerifyAsync(""" + class Holder + { + public byte[] Key { get; set; } = new byte[0]; + + public byte[] KeyField = new byte[0]; + + public int Count { get; set; } + } + + class C + { + void M(Holder holder) + { + holder.Key = new byte[8]; + holder.KeyField = new byte[8]; + holder.Count = 1; + holder.Count += 1; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsPbkdfIterationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsPbkdfIterationBranchCoverageTests.cs new file mode 100644 index 00000000..598e0985 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsPbkdfIterationBranchCoverageTests.cs @@ -0,0 +1,258 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsPbkdfIterationBranchCoverageTests +{ + // The ASP.NET Core key derivation package is not in the default reference set. + // The analyzer matches it by name and namespace, so a stub with the same shape is enough. + private const string KeyDerivationStub = """ + namespace Microsoft.AspNetCore.Cryptography.KeyDerivation + { + public enum KeyDerivationPrf + { + HMACSHA1 = 0, + HMACSHA256 = 1, + HMACSHA512 = 2, + } + + public static class KeyDerivation + { + public static byte[] Pbkdf2(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested) => new byte[0]; + } + } + + namespace Other + { + public static class Deriver + { + public static byte[] Pbkdf2(string password, int iterations) => new byte[0]; + } + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code + "\n" + KeyDerivationStub); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DefaultIterationsAndDefaultHashOfTheShortConstructor() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] salt) + { + var a = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt)|}|}; + var b = {|E128145:new Rfc2898DeriveBytes("password", salt, 600000)|}; + var c = new Rfc2898DeriveBytes("password", salt, 600000, HashAlgorithmName.SHA256); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ConstructorIterationsAndHashThatAreWeakOrUnknown() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] salt, int count, HashAlgorithmName hash) + { + var a = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt, 1000, HashAlgorithmName.SHA1)|}|}; + var b = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt, count, hash)|}|}; + var c = {|E128145:new Rfc2898DeriveBytes("password", salt, 600000, HashAlgorithmName.MD5)|}; + var d = new Rfc2898DeriveBytes("password", salt, 600000, HashAlgorithmName.SHA512); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheIterationCountIsSetByInitializerOrByTheFirstStatement() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] salt, bool flag) + { + var a = new Rfc2898DeriveBytes("password", salt, 600000, HashAlgorithmName.SHA256) { IterationCount = 700000 }; + + var b = {|E128145:new Rfc2898DeriveBytes("password", salt)|}; + b.IterationCount = 700000; + + var c = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt)|}|}; + if (flag) + { + c.IterationCount = 700000; + } + + var d = {|E128145:{|E128145:new Rfc2898DeriveBytes("password", salt)|}|}; + var unused = 1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_IterationCountAssignmentsThatAreTooLowOrUnknown() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class Holder + { + public int IterationCount { get; set; } + } + + class C + { + void M(Rfc2898DeriveBytes derive, Holder holder, int count) + { + {|E128145:derive.IterationCount = 1000|}; + derive.IterationCount = 700000; + {|E128145:derive.IterationCount = count|}; + derive.IterationCount += 5; + holder.IterationCount = 1; + int other; + (derive.IterationCount, other) = ({|E128145:10|}, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_SubclassConstructorThatTakesNamedIterationsOrHash() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + sealed class OnlyIterations : Rfc2898DeriveBytes + { + public OnlyIterations(string password, int iterations) + : base(password, new byte[16], 600000, HashAlgorithmName.SHA256) + { + } + } + + sealed class OnlyHash : Rfc2898DeriveBytes + { + public OnlyHash(string password, HashAlgorithmName hashAlgorithm) + : base(password, new byte[16], 600000, HashAlgorithmName.SHA256) + { + } + } + + sealed class Neither : Rfc2898DeriveBytes + { + public Neither(string password) + : base(password, new byte[16], 600000, HashAlgorithmName.SHA256) + { + } + } + + class C + { + void M() + { + var a = {|E128145:new OnlyIterations("password", 1000)|}; + var b = {|E128145:new OnlyHash("password", HashAlgorithmName.SHA1)|}; + var c = new Neither("password"); + var d = new OnlyIterations("password", 700000); + var e = new OnlyHash("password", HashAlgorithmName.SHA384); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_PbeParametersWithWeakIterationsOrHash() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(int count) + { + var a = {|E128145:new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 1000)|}; + var b = new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 600000); + var c = {|E128145:new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, count)|}; + var d = {|E128145:new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA1, 600000)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_StaticPbkdf2WithWeakIterationsOrHash() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] salt, int count, HashAlgorithmName hash) + { + var a = {|E128145:Rfc2898DeriveBytes.Pbkdf2("password", salt, 1000, HashAlgorithmName.SHA256, 32)|}; + var b = {|E128145:Rfc2898DeriveBytes.Pbkdf2("password", salt, 600000, HashAlgorithmName.SHA1, 32)|}; + var c = {|E128145:Rfc2898DeriveBytes.Pbkdf2("password", salt, count, HashAlgorithmName.SHA256, 32)|}; + var d = {|E128145:Rfc2898DeriveBytes.Pbkdf2("password", salt, 600000, hash, 32)|}; + var e = Rfc2898DeriveBytes.Pbkdf2("password", salt, 600000, HashAlgorithmName.SHA256, 32); + var f = Other.Deriver.Pbkdf2("password", 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_KeyDerivationWithWeakIterationsOrPrf() + { + return VerifyAsync(""" + using Microsoft.AspNetCore.Cryptography.KeyDerivation; + class C + { + void M(byte[] salt, int count, KeyDerivationPrf prf) + { + var a = {|E128145:KeyDerivation.Pbkdf2("password", salt, KeyDerivationPrf.HMACSHA256, 1000, 32)|}; + var b = {|E128145:KeyDerivation.Pbkdf2("password", salt, KeyDerivationPrf.HMACSHA1, 600000, 32)|}; + var c = KeyDerivation.Pbkdf2("password", salt, KeyDerivationPrf.HMACSHA512, 600000, 32); + var d = {|E128145:KeyDerivation.Pbkdf2("password", salt, (KeyDerivationPrf)0, 600000, 32)|}; + var e = KeyDerivation.Pbkdf2("password", salt, (KeyDerivationPrf)1, 600000, 32); + var f = {|E128145:KeyDerivation.Pbkdf2("password", salt, prf, 600000, 32)|}; + var g = {|E128145:KeyDerivation.Pbkdf2("password", salt, KeyDerivationPrf.HMACSHA256, count, 32)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAStaticPbkdf2() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(Rfc2898DeriveBytes derive) + { + var a = derive.GetBytes(16); + var b = new System.Text.StringBuilder(); + var c = new Rfc2898DeriveBytes("password", new byte[16], 600000, HashAlgorithmName.SHA256); + var d = c.Salt; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsRsaKeySizeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsRsaKeySizeBranchCoverageTests.cs new file mode 100644 index 00000000..040341b5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsRsaKeySizeBranchCoverageTests.cs @@ -0,0 +1,414 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsRsaKeySizeBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + private static Task VerifyMessageAsync(string code, string message) + { + var expected = new DiagnosticResult("E128143", DiagnosticSeverity.Error) + .WithLocation(0) + .WithArguments(message); + + return AnalyzerTestRunner.VerifyAsync(code, expected); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DefaultRsaKeyOfTheFactory() + { + return VerifyMessageAsync( + """ + using System.Security.Cryptography; + class C + { + void M() + { + using var rsa = {|#0:RSA.Create()|}; + } + } + """, + "RSA created without an explicit key size uses the platform default, which cannot be verified; use an explicit key size of at least 3072 bits or set KeySize before use"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DefaultKeyOfARsaCryptoServiceProviderWithTheProviderMessage() + { + return VerifyMessageAsync( + """ + using System.Security.Cryptography; + class C + { + void M() + { + using var rsa = {|#0:new RSACryptoServiceProvider()|}; + rsa.KeySize = 3072; + } + } + """, + "RSACryptoServiceProvider created without an explicit key size uses the platform default, which cannot be verified, and assigning KeySize afterward is not a reliable way to set it; use the constructor that takes a key size of at least 3072 bits"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFirstUseOfTheLocalSetsTheKeySizeOrInitializesIt() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] key) + { + var a = RSA.Create(); + a.KeySize = 3072; + + var b = new RSACng { KeySize = 3072 }; + + var c = RSA.Create(); + {|E128143:c.ImportRSAPrivateKey(key, out _)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheKeySizeIsSetOnlyAfterAnotherStatementOrThroughAnUpcast() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(bool flag) + { + var a = {|E128143:RSA.Create()|}; + if (flag) + { + a.KeySize = 3072; + } + + AsymmetricAlgorithm b = {|E128143:RSA.Create()|}; + b.KeySize = 3072; + + var c = {|E128143:RSA.Create()|}; + + {|E128143:RSA.Create()|}.Dispose(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheUseOfTheLocalIsAnImportInsideAnotherBlock() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] key, bool flag) + { + var a = {|E128143:RSA.Create()|}; + if (flag) + { + {|E128143:a.ImportRSAPrivateKey(key, out _)|}; + } + + using (var b = RSA.Create()) + { + b.KeySize = 3072; + } + + using (var c = {|E128143:RSA.Create()|}) + { + if (flag) + { + c.KeySize = 3072; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_KeyImportedThroughConstructorArguments() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + class C + { + void M(CngKey key, IntPtr handle, CspParameters csp) + { + var a = {|E128143:new RSACng(key)|}; + var b = {|E128143:new RSACryptoServiceProvider(csp)|}; + var c = {|E128143:new RSACryptoServiceProvider(2048)|}; + var d = new RSACryptoServiceProvider(3072); + var e = {|E128143:new RSACryptoServiceProvider(2048, csp)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RsaCreatedByNameWithTheDefaultKeySizeMessage() + { + return VerifyMessageAsync( + """ + using System.Security.Cryptography; + class C + { + void M() + { + var f = {|#0:CryptoConfig.CreateFromName(" System.Security.Cryptography.AsymmetricAlgorithm ")|}; + } + } + """, + "RSA created by name uses the platform default key size, which cannot be verified; create the key with an explicit key size of at least 3072 bits"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RsaCreatedByNameUnlessTheNextStatementImportsAKey() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(string name, byte[] key) + { + var a = (RSA)CryptoConfig.CreateFromName("RSA")!; + {|E128143:a.ImportRSAPrivateKey(key, out _)|}; + var b = AsymmetricAlgorithm.Create(name); + var c = CryptoConfig.CreateFromName("DSA"); + var d = {|E128143:CryptoConfig.CreateFromName("System.Security.Cryptography.RSACryptoServiceProvider")|}; + var e = Aes.Create("AES"); + var g = {|E128143:CryptoConfig.CreateFromName("rsa")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ImportsAndKeyGenerationOnInstances() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSA rsa, ECDsa ecdsa, ECDiffieHellman dh, byte[] data, RSAParameters parameters) + { + {|E128143:rsa.ImportParameters(parameters)|}; + {|E128143:ecdsa.ImportECPrivateKey(data, out _)|}; + {|E128143:dh.ImportFromPem("pem")|}; + {|E128143:ecdsa.GenerateKey(ECCurve.NamedCurves.nistP256)|}; + ecdsa.GenerateKey(ECCurve.NamedCurves.nistP384); + var a = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256); + var b = ecdsa.SignData(data, HashAlgorithmName.SHA256); + var c = rsa.ToString(); + var d = rsa.ExportRSAPublicKey(); + var e = ecdsa.ExportECPrivateKey(); + var f = dh.ExportParameters(false); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CertificateKeysAndIgnoresAnUnrelatedHelperWithTheSameName() + { + return VerifyAsync(""" + using System.Security.Cryptography; + using System.Security.Cryptography.X509Certificates; + + namespace System.Security.Cryptography.X509Certificates + { + public static class CertificateStubs + { + public static int GetECDiffieHellmanPublicKey(this string text) => 0; + } + } + + class C + { + void M(X509Certificate2 cert, string text) + { + var a = {|E128143:cert.GetRSAPublicKey()|}; + var b = {|E128143:cert.GetRSAPrivateKey()|}; + var c = {|E128143:cert.GetECDsaPublicKey()|}; + var d = {|E128143:cert.GetECDsaPrivateKey()|}; + var e = {|E128143:cert.GetECDiffieHellmanPublicKey()|}; + var f = text.GetECDiffieHellmanPublicKey(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RsaCreateMethodGroupButNotOtherMethodGroups() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + class C + { + string Create() => ""; + + static string Build() => ""; + + void M() + { + Func a = {|E128143:RSA.Create|}; + Func b = {|E128143:RSA.Create|}; + Func c = ECDsa.Create; + Func d = Create; + Func e = Build; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EllipticCurveFactoriesWithAnUnapprovedOrUnknownCurve() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(ECCurve parameter, string friendly) + { + var a = {|E128143:ECDsa.Create()|}; + var b = {|E128143:ECDiffieHellman.Create()|}; + var c = {|E128143:ECDsa.Create(ECCurve.NamedCurves.nistP256)|}; + var d = ECDsa.Create(ECCurve.NamedCurves.nistP384); + var e = ECDsa.Create(ECCurve.CreateFromFriendlyName("nistP521")); + var f = ECDsa.Create(ECCurve.CreateFromValue("1.3.132.0.34")); + var g = {|E128143:ECDsa.Create(ECCurve.CreateFromFriendlyName("nistP256"))|}; + var h = {|E128143:ECDsa.Create(ECCurve.CreateFromFriendlyName(friendly))|}; + var i = ECDiffieHellman.Create(ECCurve.CreateFromOid(new Oid("1.3.132.0.35"))); + var j = {|E128143:ECDiffieHellman.Create(ECCurve.CreateFromOid(new Oid("1.2.840.10045.3.1.7")))|}; + var k = {|E128143:ECDiffieHellman.Create(ECCurve.CreateFromOid(new Oid(friendly)))|}; + var l = {|E128143:ECDsa.Create(parameter)|}; + var m = {|E128143:ECDsa.Create(ECCurve.CreateFromOid(new Oid()))|}; + var n = {|E128143:ECDsa.Create(ECCurve.CreateFromOid(null!))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Resolves_CurvesHeldInLocalsAndReadonlyFieldsUpToTheDepthLimit() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + private static readonly ECCurve GoodField = ECCurve.NamedCurves.nistP384; + private static readonly ECCurve BadField = ECCurve.NamedCurves.nistP256; + private static ECCurve mutableField = ECCurve.NamedCurves.nistP384; + + void M() + { + var c1 = ECCurve.NamedCurves.nistP384; + var c2 = c1; + var c3 = c2; + var c4 = c3; + var c5 = c4; + var a = ECDsa.Create(c4); + var b = {|E128143:ECDsa.Create(c5)|}; + var c = ECDsa.Create(GoodField); + var d = {|E128143:ECDsa.Create(BadField)|}; + var e = {|E128143:ECDsa.Create(mutableField)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EllipticCurveConstructorsByCurveOrKeySize() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(int size) + { + var a = new ECDsaCng(384); + var b = {|E128143:new ECDsaCng(256)|}; + var c = {|E128143:new ECDsaCng(size)|}; + var d = {|E128143:new ECDsaCng(ECCurve.NamedCurves.nistP256)|}; + var e = new ECDsaCng(ECCurve.NamedCurves.nistP521); + var f = {|E128143:new ECDiffieHellmanCng()|}; + var g = new System.Text.StringBuilder(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_KeySizeAssignmentsAndStructCurves() + { + return VerifyAsync(""" + using System.Security.Cryptography; + + namespace System.Security.Cryptography + { + public static class StaticKeySize + { + public static int KeySize { get; set; } + } + } + + class Holder + { + public int KeySize { get; set; } + + public ECCurve Curve; + } + + class C + { + void M(RSA rsa, ECDsa ecdsa, Aes aes, Holder holder, int size, ECCurve unknown) + { + {|E128143:rsa.KeySize = 2048|}; + rsa.KeySize = 4096; + {|E128143:rsa.KeySize = size|}; + {|E128143:ecdsa.KeySize = 256|}; + ecdsa.KeySize = 384; + aes.KeySize = 128; + holder.KeySize = 1; + StaticKeySize.KeySize = 1; + rsa.KeySize += 1; + int other; + (rsa.KeySize, other) = ({|E128143:1024|}, 1); + + var parameters = new ECParameters(); + {|E128143:parameters.Curve = ECCurve.NamedCurves.nistP256|}; + parameters.Curve = ECCurve.NamedCurves.nistP521; + {|E128143:parameters.Curve = unknown|}; + holder.Curve = ECCurve.NamedCurves.nistP256; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsSha3BranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsSha3BranchCoverageTests.cs new file mode 100644 index 00000000..9725c7a7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsSha3BranchCoverageTests.cs @@ -0,0 +1,99 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsSha3BranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Sha3TypesCreatedOrCalledStatically() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] key, byte[] data) + { + var a = {|E128150:new HMACSHA3_256(key)|}; + var b = {|E128150:SHA3_256.HashData(data)|}; + var c = {|E128150:Shake128.HashData(data, 16)|}; + var d = SHA256.HashData(data); + var e = SHA512.HashData(data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Sha3PaddingButNotAnIsSupportedRead() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSA rsa, byte[] data) + { + var a = rsa.Encrypt(data, {|E128150:RSAEncryptionPadding.OaepSHA3_256|}); + var b = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256); + var c = SHA3_256.IsSupported; + var d = RSAEncryptionPadding.Pkcs1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Sha3FactoryMethodGroupButNotAnInstanceMethodGroup() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + class C + { + void M(SHA256 sha256) + { + Func a = {|E128150:SHA3_256.HashData|}; + Func b = SHA256.HashData; + Func c = sha256.ComputeHash; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Sha3HashNamesPassedAsArgumentsOrStored() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + private static HashAlgorithmName stored = {|E128150:HashAlgorithmName.SHA3_256|}; + + static void Use(HashAlgorithmName name) { } + + void M(byte[] data, byte[] salt, SHA256 sha256) + { + {|E128150:Use(HashAlgorithmName.SHA3_384)|}; + {|E128150:Use(new HashAlgorithmName("SHA3-512"))|}; + var a = {|E128150:IncrementalHash.CreateHash(HashAlgorithmName.SHA3_256)|}; + var b = {|E128150:new Rfc2898DeriveBytes("password", salt, 10, HashAlgorithmName.SHA3_256)|}; + var c = sha256.ComputeHash(data); + Use(HashAlgorithmName.SHA256); + HashAlgorithmName local; + {|E128150:local = HashAlgorithmName.SHA3_512|}; + local = HashAlgorithmName.SHA384; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsTlsVersionBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsTlsVersionBranchCoverageTests.cs new file mode 100644 index 00000000..5ddf6872 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsTlsVersionBranchCoverageTests.cs @@ -0,0 +1,185 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsTlsVersionBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WeakMembersOfBothProtocolTypes() + { + return VerifyAsync(""" + using System.Net; + using System.Security.Authentication; + class C + { + void M() + { + var a = {|E128146:SslProtocols.Ssl2|}; + var b = {|E128146:SslProtocols.Tls11|} | SslProtocols.Tls12; + var c = {|E128146:SecurityProtocolType.Ssl3|}; + var d = {|E128146:SecurityProtocolType.Tls|} | SecurityProtocolType.Tls12; + var e = SslProtocols.Tls13 | SslProtocols.None; + var f = SecurityProtocolType.SystemDefault; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAMemberOfAnotherTypeSharesAWeakName() + { + return VerifyAsync(""" + enum OwnProtocols + { + Tls, + Tls11, + Ssl3, + } + + class C + { + void M() + { + var a = OwnProtocols.Tls11; + var b = (OwnProtocols)3; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAWeakProtocolIsOnlyReadByAComparisonOrAPattern() + { + return VerifyAsync(""" + using System.Security.Authentication; + class C + { + void M(SslProtocols p) + { + var a = p == SslProtocols.Tls11; + var b = p != SslProtocols.Tls; + var c = p is SslProtocols.Ssl3; + var d = p.HasFlag(SslProtocols.Tls11); + var e = (p & SslProtocols.Tls11) != 0; + var f = (p & SslProtocols.Tls) is not SslProtocols.None; + var g = (p & SslProtocols.Tls11) == SslProtocols.Tls11; + var h = ((int)p & (int)SslProtocols.Tls11) != 0; + switch (p) + { + case SslProtocols.Ssl2: + break; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAMaskRemovesTheWeakProtocols() + { + return VerifyAsync(""" + using System.Security.Authentication; + class C + { + void M(SslProtocols p) + { + p &= ~SslProtocols.Tls11; + var a = p & ~SslProtocols.Tls; + var b = p & ~(SslProtocols.Tls | SslProtocols.Tls11); + var c = (p & ~SslProtocols.Ssl3) & SslProtocols.Tls12; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AComplementThatIsNotUsedAsAMask() + { + return VerifyAsync(""" + using System.Security.Authentication; + class C + { + void M(SslProtocols p) + { + var a = ~{|E128146:SslProtocols.Tls11|}; + var b = {|E128146:~SslProtocols.None|}; + var c = {|E128146:~SslProtocols.Tls12|}; + var d = p & ~SslProtocols.Tls12; + var e = ~p; + var f = ~(SslProtocols.Tls12 | SslProtocols.Tls13); + var g = ~5; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NumericCastsThatCarryAWeakBit() + { + return VerifyAsync(""" + using System.Net; + using System.Security.Authentication; + class C + { + void M(SslProtocols p, int number) + { + var a = {|E128146:(SslProtocols)192|}; + var b = {|E128146:(SecurityProtocolType)768|}; + var c = (SslProtocols)3072; + var d = (SslProtocols)number; + var e = p == (SslProtocols)192; + var f = (p & (SslProtocols)192) != 0; + var g = (SslProtocols)SecurityProtocolType.Tls12; + var h = (int)SslProtocols.Tls12; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TheSwitchesThatReEnableWeakTls() + { + return VerifyAsync(""" + using System; + class C + { + const string StrongCrypto = "Switch.System.Net.DontEnableSchUseStrongCrypto"; + + static bool Flag => true; + + void M(string name, bool enabled) + { + {|E128146:AppContext.SetSwitch(StrongCrypto, true)|}; + {|E128146:AppContext.SetSwitch("Switch.System.Net.DontEnableSystemDefaultTlsVersions", true)|}; + {|E128146:AppContext.SetSwitch(isEnabled: true, switchName: "Switch.System.Net.DontEnableSchUseStrongCrypto")|}; + AppContext.SetSwitch(StrongCrypto, false); + AppContext.SetSwitch("Switch.Other.Setting", true); + AppContext.SetSwitch(name, true); + AppContext.SetSwitch(StrongCrypto, enabled); + AppContext.SetSwitch(StrongCrypto, Flag); + var data = AppContext.GetData("Switch.System.Net.DontEnableSchUseStrongCrypto"); + new Own().SetSwitch("Switch.System.Net.DontEnableSchUseStrongCrypto", true); + } + } + + class Own + { + public void SetSwitch(string name, bool value) { } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsUnapprovedHashBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsUnapprovedHashBranchCoverageTests.cs new file mode 100644 index 00000000..dc17f8c2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsUnapprovedHashBranchCoverageTests.cs @@ -0,0 +1,506 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsUnapprovedHashBranchCoverageTests +{ + // The XML-DSig and CMS types live in packages that the default reference set omits. + // The analyzer matches them by name and namespace, so a stub with the same shape is enough. + private const string XmlAndCmsStubs = """ + namespace System.Security.Cryptography.Xml + { + public class SignedInfo { public string SignatureMethod { get; set; } = ""; } + + public class Reference { public string DigestMethod { get; set; } = ""; } + + public class EncryptionMethod + { + public EncryptionMethod() { } + + public EncryptionMethod(string keyAlgorithm) { KeyAlgorithm = keyAlgorithm; } + + public string KeyAlgorithm { get; set; } = ""; + } + } + + namespace System.Security.Cryptography.Pkcs + { + public class CmsSigner { public object? DigestAlgorithm { get; set; } } + } + + namespace Other + { + public class SignedInfo { public string SignatureMethod { get; set; } = ""; } + + public class CmsSigner { public object? DigestAlgorithm { get; set; } } + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code + "\n" + XmlAndCmsStubs); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForbiddenXmlUriAssignedToSignatureMethod() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + void M(SignedInfo info, Reference reference) + { + {|E128071:info.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"|}; + {|E128071:reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenXmlUriIsApprovedUnknownOrNotConstant() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + void M(SignedInfo info, Reference reference, string uri) + { + info.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; + reference.DigestMethod = uri; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSignatureMethodBelongsToAnotherType() + { + return VerifyAsync(""" + class C + { + string SignatureMethod = ""; + + void M(Other.SignedInfo info) + { + info.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; + SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForbiddenUriInCoalesceAssignment() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + void M(EncryptionMethod method) + { + {|E128071:method.KeyAlgorithm ??= "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForbiddenUriInTupleDeconstruction() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + void M(SignedInfo info, Reference reference) + { + (info.SignatureMethod, reference.DigestMethod) = ({|E128071:"http://www.w3.org/2000/09/xmldsig#rsa-sha1"|}, "http://www.w3.org/2001/04/xmlenc#sha256"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTupleDeconstructionHasNoTupleLiteralOnTheRight() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + (string, string) Pair() => ("a", "b"); + + void M(SignedInfo info, Reference reference) + { + (info.SignatureMethod, reference.DigestMethod) = Pair(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CmsSignerDigestOidForSha1() + { + return VerifyAsync(""" + using System.Security.Cryptography; + using System.Security.Cryptography.Pkcs; + class C + { + void M(CmsSigner signer, Other.CmsSigner other, string oidText) + { + {|E128071:signer.DigestAlgorithm = new Oid("1.3.14.3.2.26")|}; + signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1"); + signer.DigestAlgorithm = new Oid(oidText); + signer.DigestAlgorithm = null; + other.DigestAlgorithm = new Oid("1.3.14.3.2.26"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EncryptionMethodCreatedWithForbiddenUri() + { + return VerifyAsync(""" + using System.Security.Cryptography.Xml; + class C + { + void M(string uri) + { + var bad = {|E128071:new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#tripledes-cbc")|}; + var good = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes256-cbc"); + var dynamic = new EncryptionMethod(uri); + var empty = new EncryptionMethod(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DsaSignatureFormatterAndOaepAndPkcs1KeyExchange() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(DSA dsa, RSA rsa) + { + var formatter = {|E128071:new DSASignatureFormatter(dsa)|}; + var oaep = {|E128071:new RSAOAEPKeyExchangeFormatter(rsa)|}; + var oaepBack = {|E128071:new RSAOAEPKeyExchangeDeformatter(rsa)|}; + var pkcs = {|E128071:new RSAPKCS1KeyExchangeFormatter(rsa)|}; + var pkcsBack = {|E128071:new RSAPKCS1KeyExchangeDeformatter(rsa)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DsaSigningMembers() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + byte[] M(DSA dsa, byte[] hash, byte[] data) + { + var a = {|E128071:dsa.CreateSignature(hash)|}; + var b = {|E128071:dsa.SignData(data, HashAlgorithmName.SHA256)|}; + return a; + } + + bool V(DSA dsa, byte[] data, byte[] signature) + { + return dsa.VerifyData(data, signature, HashAlgorithmName.SHA256); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RsaCryptoServiceProviderOaepFlag() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSACryptoServiceProvider rsa, byte[] data, bool flag) + { + var a = {|E128071:rsa.Encrypt(data, true)|}; + var b = {|E128071:rsa.Decrypt(data, false)|}; + var c = {|E128071:rsa.Encrypt(data, fOAEP: flag)|}; + var d = rsa.ExportParameters(false); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_LegacySigningMemberWithForbiddenHashName() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSACryptoServiceProvider rsa, RSAPKCS1SignatureFormatter formatter, RSAPKCS1SignatureDeformatter deformatter, byte[] data, byte[] hash) + { + var a = {|E128071:rsa.SignData(data, "SHA1")|}; + var b = {|E128071:rsa.SignData(data, typeof(MD5))|}; + var c = {|E128071:rsa.SignHash(hash, "1.3.14.3.2.26")|}; + var d = {|E128071:rsa.SignHash(hash, CryptoConfig.MapNameToOID("MD5"))|}; + {|E128071:formatter.SetHashAlgorithm("SHA1")|}; + deformatter.SetHashAlgorithm("SHA1"); + var e = rsa.SignData(data, "SHA256"); + var f = rsa.SignData(data, typeof(SHA256)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenLegacyMemberReceivesNonConstantOrApprovedHash() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSACryptoServiceProvider rsa, byte[] data, string name) + { + var a = rsa.SignData(data, name); + var b = rsa.SignData(data, CryptoConfig.MapNameToOID(name)); + var c = rsa.SignData(data, CryptoConfig.MapNameToOID("SHA256")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenPbkdf2OrVerifyReceivesAForbiddenHashName() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSA rsa, byte[] data, byte[] signature, byte[] password, byte[] salt) + { + var a = Rfc2898DeriveBytes.Pbkdf2(password, salt, 1000, HashAlgorithmName.SHA1, 20); + var b = rsa.VerifyData(data, signature, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ApplicationMethodThatOnlySharesAnExemptName() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class Helper + { + public static void Pbkdf2(HashAlgorithmName name) { } + + public void VerifyAndSign(HashAlgorithmName name) { } + } + + class C + { + void M(Helper helper) + { + {|E128071:Helper.Pbkdf2(HashAlgorithmName.SHA1)|}; + {|E128071:helper.VerifyAndSign(HashAlgorithmName.MD5)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_LegacyDefaultFactoriesAndNamedFactories() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M() + { + var a = {|E128071:HashAlgorithm.Create()|}; + var b = {|E128071:HMAC.Create()|}; + var c = {|E128071:KeyedHashAlgorithm.Create()|}; + var d = {|E128071:HashAlgorithm.Create("MD5")|}; + var e = {|E128071:CryptoConfig.CreateFromName("System.Security.Cryptography.SHA1")|}; + var f = HashAlgorithm.Create("SHA256"); + var g = CryptoConfig.CreateFromName("SHA256"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFactoryNameIsNotConstantOrTakesNoString() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(string name) + { + var a = HashAlgorithm.Create(name); + var b = Aes.Create(); + var c = CryptoConfig.MapNameToOID("SHA1"); + var d = CryptoConfig.EncodeOID("1.3.14.3.2.26"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Rsa1PaddingOnlyWhenItReachesAnEncryptionCall() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void Use(RSAEncryptionPadding padding) { } + + void M(RSA rsa, byte[] data) + { + var a = rsa.Encrypt(data, {|E128071:RSAEncryptionPadding.OaepSHA1|}); + var b = rsa.Decrypt(data, {|E128071:RSAEncryptionPadding.Pkcs1|}); + var c = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256); + var kept = RSAEncryptionPadding.Pkcs1; + Use(RSAEncryptionPadding.Pkcs1); + var viaVariable = {|E128071:RSAEncryptionPadding.OaepSHA1|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TripleDesPbeAlgorithmButNotAComparison() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + bool M(PbeEncryptionAlgorithm algorithm) + { + var chosen = {|E128071:PbeEncryptionAlgorithm.TripleDes3KeyPkcs12|}; + var other = PbeEncryptionAlgorithm.Aes256Cbc; + return algorithm == PbeEncryptionAlgorithm.TripleDes3KeyPkcs12; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_StaticFactoryMethodGroupOfAForbiddenType() + { + return VerifyAsync(""" + using System; + using System.Security.Cryptography; + class C + { + void M() + { + Func create = {|E128071:MD5.Create|}; + Func fine = SHA256.Create; + Func unrelated = Helper.Next; + } + } + + static class Helper + { + public static int Next() => 1; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenCmsDigestValueIsNotAnOid() + { + return VerifyAsync(""" + using System.Security.Cryptography; + using System.Security.Cryptography.Pkcs; + class C + { + void M(CmsSigner signer) + { + signer.DigestAlgorithm = new System.Text.StringBuilder("1.3.14.3.2.26"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnInstanceMethodGroupIsNamedLikeAFactory() + { + return VerifyAsync(""" + using System; + class C + { + string Create() => ""; + + void M(C other) + { + Func a = other.Create; + Func b = other.ToString; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAStaticFactoryTakesANonStringFirstArgument() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M() + { + var rsa = RSA.Create(2048); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OneShotHelperOfAForbiddenTypeOnce() + { + return VerifyAsync(""" + using System.Security.Cryptography; + class C + { + void M(byte[] data) + { + var a = {|E128071:SHA1.HashData(data)|}; + var b = SHA256.HashData(data); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FipsUnapprovedHashCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FipsUnapprovedHashCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..ce360073 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FipsUnapprovedHashCodeFixBranchCoverageTests.cs @@ -0,0 +1,96 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FipsUnapprovedHashCodeFixBranchCoverageTests +{ + private static Task NoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheForbiddenTypeIsWrittenWithItsNamespace() + { + return NoFixAsync(""" + class C + { + void M() + { + var a = {|E128071:System.Security.Cryptography.MD5.Create()|}; + var b = {|E128071:new System.Security.Cryptography.SHA1Managed()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheForbiddenTypeHasNoApprovedReplacementInTheMap() + { + return NoFixAsync(""" + using System.Security.Cryptography; + class C + { + void M() + { + var a = {|E128071:new SHA1Managed()|}; + var b = {|E128071:new MD5CryptoServiceProvider()|}; + var c = {|E128071:TripleDES.Create()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDiagnosticIsNeitherACreationNorAMemberCall() + { + return NoFixAsync(""" + using System.Security.Cryptography; + class C + { + void M(RSA rsa, byte[] data) + { + var padding = {|E128071:RSAEncryptionPadding.OaepSHA1|}; + var a = rsa.Encrypt(data, padding); + var b = {|E128071:CryptoConfig.CreateFromName("MD5")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CodeFix_ReplacesSha1ConstructionAndKeepsTheTrivia() + { + return CodeFixTestRunner.RunAsync( + """ + using System; + using System.Security.Cryptography; + class C + { + void M(byte[] key) + { + using var a = /* before */ {|E128071:new HMACSHA1(key)|}; // after + var b = /* lead */ {|E128071:MD5.HashData(key)|}; + } + } + """, + """ + using System; + using System.Security.Cryptography; + class C + { + void M(byte[] key) + { + using var a = /* before */ new HMACSHA256(key); // after + var b = /* lead */ SHA256.HashData(key); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FixSyntaxBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FixSyntaxBranchCoverageTests.cs new file mode 100644 index 00000000..514056da --- /dev/null +++ b/tests/E128.Analyzers.Tests/FixSyntaxBranchCoverageTests.cs @@ -0,0 +1,206 @@ +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FixSyntaxBranchCoverageTests +{ + private static CompilationUnitSyntax Parse(string code) + { + return SyntaxFactory.ParseCompilationUnit(code); + } + + private static T First(SyntaxNode root) + where T : SyntaxNode + { + return root.DescendantNodes().OfType().First(); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("static class C { void M() { Probe(); } }", true)] + [InlineData("class C { static void M() { Probe(); } }", true)] + [InlineData("class C { static int P { get { Probe(); return 0; } } }", true)] + [InlineData("class C { static int F = Probe(); }", true)] + [InlineData("class C { void M() { Probe(); } }", false)] + [InlineData("class C { int P { get { Probe(); return 0; } } }", false)] + [InlineData("class C { int F = Probe(); }", false)] + [InlineData("struct S { void M() { Probe(); } }", false)] + public void IsInStaticMember_ChecksEveryEnclosingDeclaration(string code, bool expected) + { + var node = First(Parse(code)); + Assert.Equal(expected, FixSyntax.IsInStaticMember(node)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("() => new Widget()", true)] + [InlineData("x => new Widget()", true)] + [InlineData("() => new Widget { Name = \"a\" }", true)] + [InlineData("() => new Widget(1)", false)] + [InlineData("() => Widget.Create()", false)] + [InlineData("() => { return new Widget(); }", false)] + [InlineData("new Widget()", false)] + public void IsParameterlessCreation_AcceptsOnlyExpressionLambdasThatCreateAnObject(string text, bool expected) + { + Assert.Equal(expected, FixSyntax.IsParameterlessCreation(SyntaxFactory.ParseExpression(text))); + } + + [Fact] + [Trait("Category", "CI")] + public void MemberIndentation_ReadsTheLeadingWhitespace() + { + var member = First(Parse("class C\n{\n void M() { }\n}\n")); + Assert.Equal(" ", FixSyntax.MemberIndentation(member)); + } + + [Fact] + [Trait("Category", "CI")] + public void MemberIndentation_FallsBackToFourSpacesWithoutLeadingWhitespace() + { + var member = First(Parse("class C {void M() { }}")); + Assert.Equal(" ", FixSyntax.MemberIndentation(member)); + } + + [Fact] + [Trait("Category", "CI")] + public void LineBreak_ReturnsTheTrailingEndOfLine() + { + var member = First(Parse("class C\r\n{\r\n void M() { }\r\n}\r\n")); + Assert.Equal("\r\n", FixSyntax.LineBreak(member)); + } + + [Fact] + [Trait("Category", "CI")] + public void LineBreak_DefaultsToANewlineWhenNoneFollows() + { + var member = First(Parse("class C { void M() { } }")); + Assert.Equal("\n", FixSyntax.LineBreak(member)); + } + + [Fact] + [Trait("Category", "CI")] + public void InsertFieldAsFirstMember_AddsTheFieldToAnEmptyType() + { + var type = First(Parse("class C { }")); + var field = SyntaxFactory.ParseMemberDeclaration("private int _value;")!; + + var result = FixSyntax.InsertFieldAsFirstMember(type, field); + + var member = Assert.Single(result.Members); + _ = Assert.IsType(member); + } + + [Fact] + [Trait("Category", "CI")] + public void InsertFieldAsFirstMember_PutsTheFieldBeforeTheFirstMemberWithTheSameIndent() + { + var type = First(Parse("class C\n{\n void M() { }\n}\n")); + var field = SyntaxFactory.ParseMemberDeclaration("private int _value;")!; + + var result = FixSyntax.InsertFieldAsFirstMember(type, field); + + Assert.Equal(2, result.Members.Count); + _ = Assert.IsType(result.Members[0]); + Assert.Equal(" ", result.Members[0].GetLeadingTrivia().ToFullString()); + Assert.Contains("\n\n", result.Members[1].GetLeadingTrivia().ToFullString(), System.StringComparison.Ordinal); + } + + [Fact] + [Trait("Category", "CI")] + public void LastIndentation_ReturnsTheLastWhitespaceItem() + { + var trivia = SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" "), SyntaxFactory.Comment("// x"), SyntaxFactory.Whitespace(" ")); + Assert.Equal(" ", FixSyntax.LastIndentation(trivia)); + Assert.Empty(FixSyntax.LastIndentation(SyntaxFactory.TriviaList(SyntaxFactory.Comment("// x")))); + } + + [Fact] + [Trait("Category", "CI")] + public void TrailingWhitespace_KeepsOnlyAFinalWhitespaceItem() + { + var withSpace = SyntaxFactory.TriviaList(SyntaxFactory.Comment("// x"), SyntaxFactory.Whitespace(" ")); + var withComment = SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" "), SyntaxFactory.Comment("// x")); + + Assert.Equal(" ", FixSyntax.TrailingWhitespace(withSpace).ToFullString()); + Assert.Empty(FixSyntax.TrailingWhitespace(withComment)); + Assert.Empty(FixSyntax.TrailingWhitespace(SyntaxFactory.TriviaList())); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("items", "items")] + [InlineData("this.items", "this.items")] + [InlineData("Make()", "Make()")] + [InlineData("items[0]", "items[0]")] + [InlineData("this", "this")] + [InlineData("(a + b)", "(a + b)")] + [InlineData("a + b", "(a + b)")] + [InlineData("x ?? y", "(x ?? y)")] + public void ParenthesizeIfNeeded_WrapsOnlyNonPrimaryExpressions(string text, string expected) + { + Assert.Equal(expected, FixSyntax.ParenthesizeIfNeeded(SyntaxFactory.ParseExpression(text)).ToString()); + } + + [Fact] + [Trait("Category", "CI")] + public void IndexInto_ParenthesizesAnOperandThatNeedsIt() + { + var result = FixSyntax.IndexInto(SyntaxFactory.ParseExpression("a ?? b"), SyntaxFactory.ParseExpression(" i ")); + Assert.Equal("(a ?? b)[i]", result.ToString()); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Settings.Current", "x", "", "_current")] + [InlineData("client", "x", "", "_client")] + [InlineData("Client", "x", "Suffix", "_clientSuffix")] + [InlineData("a.b.C1", "x", "", "_c1")] + [InlineData("<>", "Fallback", "", "_fallback")] + [InlineData("a.()", "Other", "", "_other")] + public void BuildFieldName_LowersTheLastNameOrUsesTheFallback(string operand, string fallback, string suffix, string expected) + { + Assert.Equal(expected, FixSyntax.BuildFieldName(operand, fallback, suffix)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("class C { int _a, _b; }", "_b", false, false, true)] + [InlineData("class C { int P { get; } }", "P", true, false, true)] + [InlineData("class C { int P { get; } }", "P", false, true, false)] + [InlineData("class C { void P() { } }", "P", false, true, true)] + [InlineData("class C { void P() { } }", "P", true, false, false)] + [InlineData("class C { event System.Action P; }", "P", true, true, false)] + [InlineData("class C { int _a; }", "_z", true, true, false)] + public void HasMemberNamed_ReadsFieldsAndOptionalMembers( + string code, + string name, + bool includeProperties, + bool includeMethods, + bool expected) + { + var type = First(Parse(code)); + Assert.Equal(expected, FixSyntax.HasMemberNamed(type, name, includeProperties, includeMethods)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("class C { void M() { Probe(await x); } }", "class C { async Task M() { Probe(await x); } }")] + [InlineData("class C { int M() { Probe(await x); } }", "class C { async Task M() { Probe(await x); } }")] + [InlineData("class C { Task M() { Probe(await x); } }", "class C { async Task M() { Probe(await x); } }")] + [InlineData("class C { ValueTask M() { Probe(await x); } }", "class C { async ValueTask M() { Probe(await x); } }")] + [InlineData("class C { async void M() { Probe(await x); } }", "class C { async void M() { Probe(await x); } }")] + [InlineData("class C { int P { get { return Probe(await x); } } }", "class C { int P { get { return Probe(await x); } } }")] + public void PromoteContainingMethod_AddsAsyncAndTheTaskReturnType(string code, string expected) + { + var root = Parse(code); + var awaitExpression = First(root); + + var result = FixSyntax.PromoteContainingMethod(root, awaitExpression); + + Assert.Equal(expected, result.ToFullString().Replace(" ", " ", System.StringComparison.Ordinal)); + } +} diff --git a/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..2eada0ca --- /dev/null +++ b/tests/E128.Analyzers.Tests/FixedBufferFieldCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,114 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FixedBufferFieldCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + var test = new CSharpCodeFixTest + { + TestCode = source, + FixedCode = fixedCode, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + }; + test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe); + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesDefaultAccessibilityWhenTheFieldHasNoAccessibilityModifier() + { + return VerifyFixAsync( + """ + unsafe struct Buffer + { + {|E128119:fixed byte Data[4];|} + } + """, + """ + unsafe struct Buffer + { + DataBuffer Data; + + [System.Runtime.CompilerServices.InlineArray(4)] + struct DataBuffer + { + private byte _element0; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsInternalAccessibilityForTheGeneratedBuffer() + { + return VerifyFixAsync( + """ + unsafe struct Buffer + { + {|E128119:internal fixed int Data[8];|} + } + """, + """ + unsafe struct Buffer + { + internal DataBuffer Data; + + [System.Runtime.CompilerServices.InlineArray(8)] + internal struct DataBuffer + { + private int _element0; + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("private struct DataBuffer { }")] + [InlineData("private int DataBuffer;")] + [InlineData("private void DataBuffer() { }")] + public Task NoFix_WhenTheGeneratedTypeNameConflictsWithAMember(string member) + { + var code = "unsafe struct Buffer { {|E128119:public fixed byte Data[4];|} " + member + " }"; + return VerifyFixAsync(code, code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_IgnoresUnrelatedPropertiesMethodsAndFields() + { + return VerifyFixAsync( + """ + unsafe struct Buffer + { + private int Other; + private int Value => 1; + private void M() { } + {|E128119:public fixed byte Data[4];|} + } + """, + """ + unsafe struct Buffer + { + private int Other; + private int Value => 1; + private void M() { } + public DataBuffer Data; + + [System.Runtime.CompilerServices.InlineArray(4)] + public struct DataBuffer + { + private byte _element0; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..691dce96 --- /dev/null +++ b/tests/E128.Analyzers.Tests/FixedStringMutationAnalyzerBranchCoverageTests.cs @@ -0,0 +1,192 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class FixedStringMutationAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code, options: new AnalyzerTestOptions { AllowUnsafe = true }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnAssignmentThroughAPointerIndirection() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text) + { + {|E128126:fixed (char* pointer = text) + { + *pointer = 'a'; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAWriteThroughAnOffsetPointer() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text) + { + {|E128126:fixed (char* pointer = text) + { + *(pointer + 1) = 'a'; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnIncrementOfTheCharacter() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text) + { + {|E128126:fixed (char* pointer = text) + { + (*pointer)++; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAPreIncrementAndAPreDecrement() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text, string other) + { + {|E128126:fixed (char* pointer = text) + { + ++pointer[0]; + }|} + + {|E128126:fixed (char* pointer = other) + { + --pointer[0]; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAPostDecrement() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text) + { + {|E128126:fixed (char* pointer = text) + { + pointer[0]--; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForARefOrOutArgument() + { + return VerifyAsync(""" + unsafe class C + { + static void Touch(ref char value) { } + + static void Fill(out char value) { value = 'a'; } + + void M(string text, string other) + { + {|E128126:fixed (char* pointer = text) + { + Touch(ref pointer[0]); + }|} + + {|E128126:fixed (char* pointer = other) + { + Fill(out pointer[0]); + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALaterVariableOfTheFixedStatementIsWritten() + { + return VerifyAsync(""" + unsafe class C + { + void M(string text, string other) + { + {|E128126:fixed (char* first = text, second = other) + { + second[0] = 'a'; + }|} + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForReadsAndForOtherPointerTypes() + { + return VerifyAsync(""" + unsafe class C + { + static void Read(char value) { } + + static void Pass(in char value) { } + + void M(string text, int[] numbers, char[] buffer) + { + fixed (char* pointer = text) + { + Read(*pointer); + Read(*(pointer + 1)); + Read((pointer)[0]); + Pass(in pointer[0]); + var copy = pointer[0] + 1; + var other = pointer; + _ = copy; + _ = other; + } + + fixed (int* count = numbers) + { + count[0] = 1; + } + + fixed (char* local = buffer) + { + local[0] = 'a'; + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/GcHandleFreeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GcHandleFreeBranchCoverageTests.cs new file mode 100644 index 00000000..93923f5b --- /dev/null +++ b/tests/E128.Analyzers.Tests/GcHandleFreeBranchCoverageTests.cs @@ -0,0 +1,170 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class GcHandleFreeBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Runtime.InteropServices;\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAConstructorAndADestructor() + { + return VerifyAsync(""" + public C() + { + var handle = {|E128189:GCHandle.Alloc(new object())|}; + } + + ~C() + { + var handle = {|E128189:GCHandle.Alloc(new object())|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_InAnAccessorAndOperators() + { + return VerifyAsync(""" + public object? Value + { + get + { + var handle = {|E128189:GCHandle.Alloc(new object())|}; + return null; + } + } + + public static C operator +(C left, C right) + { + var handle = {|E128189:GCHandle.Alloc(left)|}; + return right; + } + + public static implicit operator int(C value) + { + var handle = {|E128189:GCHandle.Alloc(value)|}; + return 0; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForALambdaInsideAMethodThatNeverFrees() + { + return VerifyAsync(""" + void M() + { + Action action = () => + { + var handle = {|E128189:GCHandle.Alloc(new object())|}; + }; + action(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForALambdaInAFieldInitializer() + { + return VerifyAsync(""" + Action action = () => + { + var handle = GCHandle.Alloc(new object()); + }; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheHandleIsCopiedOrStoredInAnInitializer() + { + return VerifyAsync(""" + void Copy() + { + var handle = GCHandle.Alloc(new object()); + var copy = handle; + copy.Free(); + } + + void Array() + { + var handle = GCHandle.Alloc(new object()); + var all = new[] { handle }; + all[0].Free(); + } + + void Reassign() + { + GCHandle other = default; + var handle = GCHandle.Alloc(new object()); + other = handle; + other.Free(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyAnotherHandleIsFreed() + { + return VerifyAsync(""" + void M(GCHandle other) + { + var handle = {|E128189:GCHandle.Alloc(new object())|}; + _ = handle.IsAllocated; + other.Free(); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAllocStoredInAnArrayElementOrAnotherType() + { + return VerifyAsync(""" + static class Pool + { + public static object Alloc(object value) => value; + } + + void M(GCHandle[] handles) + { + handles[0] = GCHandle.Alloc(new object()); + var other = Pool.Alloc(new object()); + _ = other; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAllocIsAnInvokedDelegateResult() + { + return VerifyAsync(""" + void M(Func> factory) + { + var handle = factory()(new object()); + handle.Free(); + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexBranchCoverageTests.cs new file mode 100644 index 00000000..ee7c42ef --- /dev/null +++ b/tests/E128.Analyzers.Tests/GeneratedRegexBranchCoverageTests.cs @@ -0,0 +1,330 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers how the GeneratedRegex analyzer picks attributes and reads their arguments. +/// +public sealed class GeneratedRegexBranchCoverageTests +{ + private const string PartialImpl = " private static partial System.Text.RegularExpressions.Regex Probe() => null!;"; + + private static Task VerifyNoDiagnosticAsync(string source, bool compilerDiagnostics = true) + { + return AnalyzerTestRunner.VerifyAsync( + source, + options: compilerDiagnostics + ? null + : new AnalyzerTestOptions { CompilerDiagnostics = Microsoft.CodeAnalysis.Testing.CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task FullAttributeTypeName_WithoutTimeout_ReportsTimeout() + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [{|E128011:GeneratedRegexAttribute(@"\d+")|}] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task QualifiedAttributeName_WithoutTimeout_ReportsTimeout() + { + return AnalyzerTestRunner.VerifyAsync($$""" + partial class C + { + [{|E128011:System.Text.RegularExpressions.GeneratedRegex(@"\d+")|}] + private static partial System.Text.RegularExpressions.Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NamedTimeoutArgument_ReportsNothing() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [GeneratedRegex(@"\d+", RegexOptions.None, matchTimeoutMilliseconds: 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NamedOptionsOnly_ReportsMissingTimeout() + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [{|E128011:GeneratedRegex(@"\d+", options: RegexOptions.IgnoreCase)|}] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CompiledWithNamedTimeout_ReportsCompiled() + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [{|E128012:GeneratedRegex(@"\d+", RegexOptions.Compiled, matchTimeoutMilliseconds: 1000)|}] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CompiledInNamedOptions_ReportsCompiled() + { + return AnalyzerTestRunner.VerifyAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [{|E128012:GeneratedRegex(@"\d+", options: RegexOptions.Compiled, matchTimeoutMilliseconds: 1000)|}] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NamedOptionsWithoutCompiled_ReportsNothing() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [GeneratedRegex(@"\d+", options: RegexOptions.IgnoreCase, matchTimeoutMilliseconds: 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DefaultOptionsExpression_ReportsNothing() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [GeneratedRegex(@"\d+", default, 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CompiledNamedFieldOfAnotherType_ReportsNothing() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + static class Flags + { + public const RegexOptions Compiled = RegexOptions.None; + } + partial class C + { + [GeneratedRegex(@"\d+", Flags.Compiled, 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CompiledFieldOfLookAlikeRegexOptionsType_ReportsNothing() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + namespace Fake + { + static class RegexOptions + { + public const System.Text.RegularExpressions.RegexOptions Compiled = + System.Text.RegularExpressions.RegexOptions.None; + } + } + partial class C + { + [GeneratedRegex(@"\d+", Fake.RegexOptions.Compiled, 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NamedPatternArgument_SkipsQuantifierRules() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [GeneratedRegex(pattern: @"(a+)+", options: RegexOptions.None, matchTimeoutMilliseconds: 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ConstantPatternReference_SkipsQuantifierRules() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + private const string Pattern = "(a+)+"; + + [GeneratedRegex(Pattern, RegexOptions.None, 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ConcatenatedPattern_SkipsQuantifierRules() + { + return VerifyNoDiagnosticAsync($$""" + using System.Text.RegularExpressions; + partial class C + { + [GeneratedRegex("(a+)" + "+", RegexOptions.None, 1000)] + private static partial Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task AttributeThatDoesNotResolve_ReportsNothing() + { + return VerifyNoDiagnosticAsync( + """ + partial class C + { + [GeneratedRegex(@"\d+")] + private static partial int Probe(); + } + """, + compilerDiagnostics: false); + } + + [Fact] + [Trait("Category", "CI")] + public Task AliasQualifiedAttribute_ReportsNothing() + { + return VerifyNoDiagnosticAsync( + """ + class MarkerAttribute : System.Attribute + { + } + + [global::Marker] + class C + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task AliasToAnotherAttributeType_ReportsNothing() + { + return VerifyNoDiagnosticAsync( + """ + using GeneratedRegex = System.ObsoleteAttribute; + + [GeneratedRegex("old")] + class C + { + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Fake")] + [InlineData("Fake.RegularExpressions")] + [InlineData("Fake.Text.RegularExpressions")] + [InlineData("Outer.System.Text.RegularExpressions")] + [InlineData("System.Fake.RegularExpressions")] + public Task LookAlikeAttributeInAnotherNamespace_ReportsNothing(string attributeNamespace) + { + return VerifyNoDiagnosticAsync($$""" + namespace {{attributeNamespace}} + { + public sealed class GeneratedRegexAttribute : global::System.Attribute + { + public GeneratedRegexAttribute(string pattern) + { + Pattern = pattern; + } + + public string Pattern { get; } + } + } + + [{{attributeNamespace}}.GeneratedRegex("(a+)+")] + class C + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task LookAlikeAttributeInGlobalNamespace_ReportsNothing() + { + return VerifyNoDiagnosticAsync( + """ + public sealed class GeneratedRegexAttribute : global::System.Attribute + { + public GeneratedRegexAttribute(string pattern) + { + Pattern = pattern; + } + + public string Pattern { get; } + } + + [GeneratedRegex("(a+)+")] + class C + { + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..1b5db372 --- /dev/null +++ b/tests/E128.Analyzers.Tests/GeneratedRegexCodeFixBranchCoverageTests.cs @@ -0,0 +1,293 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the GeneratedRegex code fix providers for rewrites the main fix suites leave out. +/// +public sealed class GeneratedRegexCodeFixBranchCoverageTests +{ + private const string PartialImpl = " private static partial System.Text.RegularExpressions.Regex Probe() => null!;"; + + private static string Wrap(string attribute) + { + return $$""" + using System.Text.RegularExpressions; + partial class C + { + [{{attribute}}] + private static partial Regex Probe(); + {{PartialImpl}} + } + """; + } + + private static Task CompiledFixAsync(string before, string after) + { + return CodeFixTestRunner.RunAsync( + Wrap("{|E128012:" + before + "|}"), + Wrap(after)); + } + + private static Task NestedFixAsync(string before, string after) + { + return CodeFixTestRunner.RunAsync( + Wrap("{|E128014:" + before + "|}"), + Wrap(after)); + } + + private static Task OverlappingFixAsync(string before, string after) + { + return CodeFixTestRunner.RunAsync( + Wrap("{|E128013:" + before + "|}"), + Wrap(after)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_RepeatedOnBothSides_BecomesNone() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", RegexOptions.Compiled | RegexOptions.Compiled, 1000)", + "GeneratedRegex(@\"\\d+\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_OnTheRight_KeepsTheLeftOption() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Compiled, 1000)", + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_FirstOfThree_KeepsTheOtherTwo() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline, 1000)", + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Multiline, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_MiddleOfThree_KeepsTheOtherTwo() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline, 1000)", + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Multiline, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_LastOfThree_KeepsTheOtherTwo() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled, 1000)", + "GeneratedRegex(@\"\\d+\", RegexOptions.IgnoreCase | RegexOptions.Multiline, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_InNamedOptionsArgument_BecomesNone() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", options: RegexOptions.Compiled, matchTimeoutMilliseconds: 1000)", + "GeneratedRegex(@\"\\d+\", options: RegexOptions.None, matchTimeoutMilliseconds: 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Nested_LazyInnerPlus_KeepsOuterStarAndAddsNonCapturingGroup() + { + return CodeFixTestRunner.RunKeepDiagnosticAsync( + Wrap("{|E128014:GeneratedRegex(@\"(a+?)*\", RegexOptions.None, 1000)|}"), + Wrap("{|E128014:GeneratedRegex(@\"(?:a+?)*\", RegexOptions.None, 1000)|}")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Nested_LazyInnerStar_RemovesOuterStar() + { + return NestedFixAsync( + "GeneratedRegex(@\"(a*?)*\", RegexOptions.None, 1000)", + "GeneratedRegex(@\"(a*?)\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Nested_RegularStringLiteral_KeepsEscapedForm() + { + return NestedFixAsync( + "GeneratedRegex(\"(\\\\w+)+\", RegexOptions.None, 1000)", + "GeneratedRegex(\"(\\\\w+)\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Nested_VerbatimLiteralWithQuote_DoublesTheQuote() + { + return NestedFixAsync( + "GeneratedRegex(@\"(\"\"+)+\", RegexOptions.None, 1000)", + "GeneratedRegex(@\"(\"\"+)\", RegexOptions.None, 1000)"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("(a+){2,}")] + [InlineData("(a+a)+")] + [InlineData("(?:a+)*")] + public Task Nested_ShapeWithoutSafeRewrite_OffersNoFix(string pattern) + { + return CodeFixTestRunner.NoFixAsync( + Wrap("{|E128014:GeneratedRegex(@\"" + pattern + "\", RegexOptions.None, 1000)|}")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Overlapping_QuantifiedDotBeforeRequiredWhitespace_KeepsOneSpace() + { + return OverlappingFixAsync( + "GeneratedRegex(@\".*\\s+\", RegexOptions.None, 1000)", + "GeneratedRegex(@\".*\\s\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Overlapping_QuantifiedDotBeforeOptionalWhitespace_DropsTheToken() + { + return OverlappingFixAsync( + "GeneratedRegex(@\"x.*\\s*\", RegexOptions.None, 1000)", + "GeneratedRegex(@\"x.*\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Overlapping_CharacterClassBeforeToken_SkipsClassContents() + { + return OverlappingFixAsync( + "GeneratedRegex(@\"[\\s]\\s*.*\", RegexOptions.None, 1000)", + "GeneratedRegex(@\"[\\s].*\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Overlapping_RegularStringLiteral_KeepsEscapedForm() + { + return OverlappingFixAsync( + "GeneratedRegex(\"\\\\s*.*\", RegexOptions.None, 1000)", + "GeneratedRegex(\".*\", RegexOptions.None, 1000)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Timeout_FullyQualifiedAttribute_AddsBothUsings() + { + return CodeFixTestRunner.RunAsync( + $$""" + partial class C + { + [{|E128011:System.Text.RegularExpressions.GeneratedRegex(@"\d+")|}] + private static partial System.Text.RegularExpressions.Regex Probe(); + {{PartialImpl}} + } + """, + $$""" + using System.Text.RegularExpressions; + using System.Threading; + + partial class C + { + [System.Text.RegularExpressions.GeneratedRegex(@"\d+", RegexOptions.None, Timeout.Infinite)] + private static partial System.Text.RegularExpressions.Regex Probe(); + {{PartialImpl}} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_NamedOptionsAfterAnotherNamedArgument_BecomesNone() + { + return CompiledFixAsync( + "GeneratedRegex(@\"\\d+\", matchTimeoutMilliseconds: 1000, options: RegexOptions.Compiled)", + "GeneratedRegex(@\"\\d+\", matchTimeoutMilliseconds: 1000, options: RegexOptions.None)"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Compiled_NextToConstantOfAnotherType_KeepsTheOtherConstant() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Text.RegularExpressions; + static class Flags + { + public const RegexOptions Compiled = RegexOptions.IgnoreCase; + } + partial class C + { + [{|E128012:GeneratedRegex(@"\d+", Flags.Compiled | RegexOptions.Compiled, 1000)|}] + private static partial Regex Probe(); + private static partial Regex Probe() => null!; + } + """, + """ + using System.Text.RegularExpressions; + static class Flags + { + public const RegexOptions Compiled = RegexOptions.IgnoreCase; + } + partial class C + { + [GeneratedRegex(@"\d+", Flags.Compiled, 1000)] + private static partial Regex Probe(); + private static partial Regex Probe() => null!; + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Fake")] + [InlineData("Fake.RegularExpressions")] + [InlineData("Fake.Text.RegularExpressions")] + [InlineData("Outer.System.Text.RegularExpressions")] + public Task Compiled_NextToLookAlikeRegexOptionsType_KeepsTheLookAlike(string lookAlikeNamespace) + { + var declaration = $$""" + namespace {{lookAlikeNamespace}} + { + static class RegexOptions + { + public const global::System.Text.RegularExpressions.RegexOptions Compiled = + global::System.Text.RegularExpressions.RegexOptions.IgnoreCase; + } + } + """; + return CodeFixTestRunner.RunAsync( + $$""" + using System.Text.RegularExpressions; + {{declaration}} + partial class C + { + [{|E128012:GeneratedRegex(@"\d+", {{lookAlikeNamespace}}.RegexOptions.Compiled | RegexOptions.Compiled, 1000)|}] + private static partial Regex Probe(); + private static partial Regex Probe() => null!; + } + """, + $$""" + using System.Text.RegularExpressions; + {{declaration}} + partial class C + { + [GeneratedRegex(@"\d+", {{lookAlikeNamespace}}.RegexOptions.Compiled, 1000)] + private static partial Regex Probe(); + private static partial Regex Probe() => null!; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageTests.cs new file mode 100644 index 00000000..766f1cdb --- /dev/null +++ b/tests/E128.Analyzers.Tests/GeneratedRegexHelpersBranchCoverageTests.cs @@ -0,0 +1,255 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Drives the shared regex pattern scanner through the GeneratedRegex analyzer. Each row +/// states whether a pattern reports E128014 (nested quantifier) and E128013 (overlapping +/// quantifier). +/// +public sealed class GeneratedRegexHelpersBranchCoverageTests +{ + private static Task VerifyPatternAsync(string pattern, bool nested, bool overlapping) + { + var marked = $"GeneratedRegex(@\"{pattern}\", RegexOptions.None, 1000)"; + if (overlapping) + { + marked = "{|E128013:" + marked + "|}"; + } + + if (nested) + { + marked = "{|E128014:" + marked + "|}"; + } + + var source = "using System.Text.RegularExpressions;\n" + + "partial class C\n" + + "{\n" + + " [" + marked + "]\n" + + " private static partial Regex Probe();\n" + + " private static partial Regex Probe() => null!;\n" + + "}\n"; + return AnalyzerTestRunner.VerifyAsync(source); + } + + /// + /// Single-atom and multi-atom bodies that repeat an inner quantifier. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData("(a+)+")] + [InlineData("(a+)*")] + [InlineData("(a+)+?")] + [InlineData("(a+)*?")] + [InlineData("(a+){2,}")] + [InlineData("(a+){2,}?")] + [InlineData(@"(\w+)+")] + [InlineData(@"(?:\d+)+")] + [InlineData("(?:a+?)+")] + [InlineData("([ab]+)+")] + [InlineData("(?:a|b+)+")] + [InlineData("(?a+)+")] + [InlineData("(?=a+)+")] + [InlineData("(?+)+")] + [InlineData("((a)+b)+")] + [InlineData("(a+a)+")] + [InlineData(@"(a+\w)+")] + [InlineData(@"(\w+\d)+")] + [InlineData(@"(\d+\w)+")] + [InlineData(@"(\d+5)+")] + [InlineData(@"(\t+x)+")] + [InlineData("(.+x)+")] + [InlineData("(x+.)+")] + [InlineData("(a+[ab])+")] + [InlineData("(a+[a-c])+")] + [InlineData("(a+[^b])+")] + [InlineData(@"(\A+x)+")] + [InlineData(@"(\B+x)+")] + [InlineData(@"(\Z+x)+")] + [InlineData(@"(\x+x)+")] + [InlineData(@"(\z+x)+")] + [InlineData(@"(\p+x)+")] + [InlineData(@"(a+[\S])+")] + [InlineData(@"(-+[\W])+")] + [InlineData(@"(5+[\d\w])+")] + [InlineData(@"(a+[\D])+")] + [InlineData("(+)+")] + [InlineData(@"(\r+[\r])+")] + [InlineData(@"(\t+[\t])+")] + [InlineData(@"(\f+[\f])+")] + [InlineData(@"(\v+[\v])+")] + [InlineData(@"(\b+[\b])+")] + [InlineData(@"(\0+[\0])+")] + [InlineData(@"(\W+-)+")] + [InlineData(@"(\D+a)+")] + [InlineData(@"(\S+a)+")] + [InlineData(@"(\w+a)+")] + [InlineData(@"(\s+ )+")] + [InlineData("(a+)+[")] + [InlineData("(a+)+[^")] + [InlineData("(a+)+[]")] + [InlineData(@"(\d+\.)+")] + [InlineData(@"\\(a+)+")] + [InlineData(@"(5+[\d])+")] + [InlineData(@"( +[\s])+")] + [InlineData("([ab]+a)+")] + [InlineData(@"(a+[\w])+")] + [InlineData(@"(\n+[\n])+")] + [InlineData("(a+[c-a])+")] + [InlineData("(a+[]a])+")] + [InlineData("(a+[^]b])+")] + [InlineData("(a+[a-])+")] + [InlineData(@"(a+[\x-z])+")] + [InlineData(@"(a+[\-a])+")] + [InlineData("(a+x])+")] + [InlineData("(a+2})+")] + [InlineData("(a+a{2})+")] + [InlineData("(a+a{2,3}?)+")] + [InlineData(@"(a+\w[ab]+)+")] + [InlineData(@"(a+\d[a-c]*)+")] + [InlineData("([a]+[a]+)+")] + [InlineData("(.+.+)+")] + public Task NestedQuantifier_Fires(string pattern) + { + return VerifyPatternAsync(pattern, true, false); + } + + /// + /// Shapes the scanner must leave alone. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData("(?>a+)+")] + [InlineData("(?>a+")] + [InlineData("(a+")] + [InlineData("(a+){2}")] + [InlineData("(a+){2,3}")] + [InlineData("(a+){x,}")] + [InlineData("(a+){2")] + [InlineData("(a+){2,")] + [InlineData("(a+){")] + [InlineData("(a+)")] + [InlineData("(a+)?")] + [InlineData("(ab)+")] + [InlineData("(ab+)")] + [InlineData("(a+b+)+")] + [InlineData("(a+[^a])+")] + [InlineData("(a+[b-d])+")] + [InlineData(@"(\~+x)+")] + [InlineData(@"(\_+x)+")] + [InlineData(@"(\@+x)+")] + [InlineData(@"(\1+x)+")] + [InlineData(@"(z+[a-\d])+")] + [InlineData(@"(a+[\W])+")] + [InlineData(@"(a+[\s])+")] + [InlineData(@"(a+[\d])+")] + [InlineData(@"(a+[\n])+")] + [InlineData("(a+[+-])+")] + [InlineData("(a+[A])+")] + [InlineData(@"(a+[\])+")] + [InlineData(@"(a+[\.])+")] + [InlineData(@"(a+\.)+")] + [InlineData("(/+[^/])+")] + [InlineData(@"(\d+x+)+")] + [InlineData(@"(\w+-)+")] + [InlineData(@"(\s+x)+")] + [InlineData(@"(\D+5)+")] + [InlineData(@"(\W+a)+")] + [InlineData(@"(\S+ )+")] + [InlineData("(a+b{2})+")] + [InlineData("(a+b{2,})+")] + [InlineData("(?:/[^/]+)+")] + [InlineData(@"\(a+\)+")] + [InlineData("[(a+)]+")] + [InlineData("[(]a+[)]+")] + [InlineData("[ab")] + public Task NestedQuantifier_Silent(string pattern) + { + return VerifyPatternAsync(pattern, false, false); + } + + /// + /// Overlapping quantifiers that report E128013. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData(@"\s*.*")] + [InlineData(@"\s+.+")] + [InlineData(@"\s*.?")] + [InlineData(@"\s*?.*")] + [InlineData(@"\s+?(.*)")] + [InlineData(@"\s*(a.*)")] + [InlineData(@"\s*((a)b.*)")] + [InlineData(@"\s*[^a]+")] + [InlineData(@"\s*[^a]*")] + [InlineData(@"\s*[^\d]+")] + [InlineData(@"\s*[^a\\]+")] + [InlineData(@".*\s+")] + [InlineData(@".+?\s+")] + [InlineData(@"\s*(\w.*)")] + [InlineData(@"\s*([x].*)")] + [InlineData(@"([x].*)\s+")] + [InlineData(@"(\w.*)\s+")] + [InlineData(@"(.?)*\s+")] + [InlineData(@"(.*)\s+")] + [InlineData(@"(a.*)\s*")] + [InlineData(@"a.*\s*b")] + public Task OverlappingQuantifier_Fires(string pattern) + { + return VerifyPatternAsync(pattern, false, true); + } + + /// + /// Whitespace quantifiers with no overlapping neighbor. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData(@"\s*a")] + [InlineData(@"\s+")] + [InlineData(@"\s")] + [InlineData(@"\s?.")] + [InlineData(@"\s*.")] + [InlineData(@"\s*")] + [InlineData(@"\s*(a)")] + [InlineData(@"((a.*)b)\s+")] + [InlineData(@"\s*()")] + [InlineData(@"\s*(")] + [InlineData(@"\s*[^a]")] + [InlineData(@"\s*[^a")] + [InlineData(@"\s*[^\s]+")] + [InlineData(@"\s*[^a\s]+")] + [InlineData(@"\s*[a]+")] + [InlineData(@"\s*[^]")] + [InlineData(@"?\s+")] + [InlineData(@"*\s+")] + [InlineData(@"a?\s+")] + [InlineData(@"a*\s+")] + [InlineData(@"a+?\s+")] + [InlineData(@"(a)\s+")] + [InlineData(@"(a)*\s+")] + [InlineData(@"\)\s+")] + [InlineData(@"[.*]\s+")] + [InlineData(@"(a)b\s+")] + [InlineData(@"\.\*\s+")] + [InlineData(@"\s+[.*]")] + [InlineData(@"^\s+$")] + public Task WhitespaceQuantifier_Silent(string pattern) + { + return VerifyPatternAsync(pattern, false, false); + } + + /// + /// Nested and overlapping at once. + /// + [Theory] + [Trait("Category", "CI")] + [InlineData(@"(.+)+\s*")] + [InlineData(@"\s*(.+)+")] + [InlineData(@"(.*)*\s+")] + public Task NestedAndOverlapping_FireTogether(string pattern) + { + return VerifyPatternAsync(pattern, true, true); + } +} diff --git a/tests/E128.Analyzers.Tests/GetAttributeElementTypeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GetAttributeElementTypeBranchCoverageTests.cs new file mode 100644 index 00000000..cfb784e8 --- /dev/null +++ b/tests/E128.Analyzers.Tests/GetAttributeElementTypeBranchCoverageTests.cs @@ -0,0 +1,273 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers how the href rule traces a receiver back to the selector that created it. +/// +public sealed class GetAttributeElementTypeBranchCoverageTests +{ + private const string Stubs = """ + namespace AngleSharp.Dom + { + public interface IElement + { + string GetAttribute(string name); + string GetAttribute(string name, string fallback); + IElement QuerySelector(string selector); + IElement QuerySelector(string selector, string extra); + IElement QuerySelectorAll(string selector); + IElement Closest(string selector); + IElement Child { get; } + } + } + + """; + + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + Stubs + """ + class Foo + { + void Parse(AngleSharp.Dom.IElement doc, string dynamicSelector) + { + """ + "\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCallUsesPlainMemberAccess() + { + return VerifyAsync(""" + var span = doc.QuerySelector("span"); + var href = {|E128078:span.GetAttribute("href")|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSelectorComesFromQuerySelectorAll() + { + return VerifyAsync(""" + var items = doc.QuerySelectorAll("div.item"); + var href = {|E128078:items.GetAttribute("href")|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLocalIsInitializedThroughAConditionalAccess() + { + return VerifyAsync(""" + var span = doc?.QuerySelector("h1"); + var href = span?{|E128078:.GetAttribute("href")|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAHyphenatedAndDigitElementName() + { + return VerifyAsync(""" + var custom = doc.QuerySelector("custom-el2[data-x]"); + var href = {|E128078:custom.GetAttribute("href")|}; + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("span:hover")] + [InlineData("span~p")] + [InlineData("span_x")] + [InlineData("span.x")] + [InlineData("span{x")] + public Task Reports_AndStopsTheElementNameAtTheFirstSelectorSymbol(string selector) + { + return VerifyAsync($$""" + var node = doc.QuerySelector("{{selector}}"); + var href = {|E128078:node.GetAttribute("href")|}; + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("A")] + [InlineData("BASE")] + [InlineData("Area")] + public Task Silent_ForHrefElementNamesInAnyCase(string element) + { + return VerifyAsync($$""" + var node = doc.QuerySelector("{{element}}"); + var href = node.GetAttribute("href"); + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("")] + [InlineData(".link")] + [InlineData("#main")] + [InlineData("[data-x]")] + public Task Silent_WhenTheSelectorNamesNoElement(string selector) + { + return VerifyAsync($$""" + var node = doc.QuerySelector("{{selector}}"); + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsAChainedCall() + { + return VerifyAsync(""" + var href = doc.QuerySelector("span").GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsAParameter() + { + return VerifyAsync(""" + var href = doc.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalHasNoInitializer() + { + return VerifyAsync(""" + AngleSharp.Dom.IElement node; + node = doc.QuerySelector("span"); + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsInitializedFromAnotherLocal() + { + return VerifyAsync(""" + var first = doc.QuerySelector("span"); + var second = first; + var href = second.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalComesFromAForeachVariable() + { + return VerifyAsync(""" + foreach (var node in new[] { doc }) + { + var href = node.GetAttribute("href"); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInitializerIsAnUnqualifiedCall() + { + return VerifyAsync(""" + AngleSharp.Dom.IElement Find(string selector) => doc; + var node = Find("span"); + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInitializerIsAnotherMethod() + { + return VerifyAsync(""" + var node = doc.Closest("span"); + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectorIsNotALiteral() + { + return VerifyAsync(""" + var node = doc.QuerySelector(dynamicSelector); + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInitializerIsAPropertyRead() + { + return VerifyAsync(""" + var node = doc.Child; + var href = node.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheConditionalReceiverIsNotAnIdentifier() + { + return VerifyAsync(""" + var href = doc?.Child?.GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenGetAttributeHasTwoArguments() + { + return VerifyAsync(""" + var span = doc.QuerySelector("span"); + var href = span.GetAttribute("href", "none"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheAttributeNameIsNotALiteral() + { + return VerifyAsync(""" + var span = doc.QuerySelector("span"); + var href = span.GetAttribute(dynamicSelector); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAMemberCall() + { + return VerifyAsync(""" + string GetAttribute(string name) => name; + var href = GetAttribute("href"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMethodIsNotGetAttribute() + { + return VerifyAsync(""" + var span = doc.QuerySelector("span"); + var other = span.ToString(); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectorQueryHasTwoArguments() + { + return VerifyAsync(""" + var node = doc.QuerySelector("span", "extra"); + var href = node.GetAttribute("href"); + """); + } +} diff --git a/tests/E128.Analyzers.Tests/GetBufferNotVisibleBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/GetBufferNotVisibleBranchCoverageTests.cs new file mode 100644 index 00000000..482561a5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/GetBufferNotVisibleBranchCoverageTests.cs @@ -0,0 +1,212 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers how the GetBuffer rule traces a receiver back to the creation of its stream. +/// +public sealed class GetBufferNotVisibleBranchCoverageTests +{ + private const string Header = """ + using System.Collections.Generic; + using System.IO; + + class DerivedStream : MemoryStream + { + public DerivedStream(byte[] buffer) + : base(buffer) + { + } + } + + """; + + private static Task VerifyAsync(string members, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + Header + "class C\n{\n" + members + "\n}\n", + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherAssignmentFollowsTheCall() + { + return VerifyAsync(""" + void M(byte[] bytes) + { + var ms = new MemoryStream(bytes); + var buffer = {|E128192:ms.GetBuffer()|}; + ms = new MemoryStream(bytes, 0, 1, true, publiclyVisible: true); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALaterAssignmentToAnotherVariableAndAnElementPrecedeTheCall() + { + return VerifyAsync(""" + void M(byte[] bytes, MemoryStream[] streams) + { + var ms = new MemoryStream(bytes); + var other = new MemoryStream(); + other = new MemoryStream(8); + streams[0] = new MemoryStream(8); + var buffer = {|E128192:ms.GetBuffer()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheNearestAssignmentIsTheOneBeforeTheCall() + { + return VerifyAsync(""" + void M(byte[] bytes) + { + MemoryStream ms = new MemoryStream(); + ms = new MemoryStream(bytes, writable: true); + ms = new MemoryStream(bytes); + var buffer = {|E128192:ms.GetBuffer()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamIsBuiltWithAnInitializerOnly() + { + return VerifyAsync(""" + void M() + { + var ms = new MemoryStream { }; + var buffer = ms.GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenACompoundAssignmentIsTheOnlyLaterWrite() + { + return VerifyAsync(""" + void M(byte[] bytes) + { + MemoryStream? ms = new MemoryStream(); + ms ??= new MemoryStream(bytes); + var buffer = ms.GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheParameterIsNeverAssigned() + { + return VerifyAsync(""" + void M(MemoryStream ms) + { + var buffer = ms.GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverTypeDerivesFromMemoryStream() + { + return VerifyAsync(""" + void M(byte[] bytes, DerivedStream parameter) + { + var local = new DerivedStream(bytes); + var first = local.GetBuffer(); + var second = parameter.GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenADerivedStreamIsAssignedToAMemoryStreamLocal() + { + return VerifyAsync(""" + void M(byte[] bytes) + { + MemoryStream ms = new DerivedStream(bytes); + var buffer = ms.GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsALoopVariable() + { + return VerifyAsync(""" + void M(IEnumerable streams) + { + foreach (var ms in streams) + { + var buffer = ms.GetBuffer(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsACastExpression() + { + return VerifyAsync(""" + void M(Stream stream) + { + var buffer = ((MemoryStream)stream).GetBuffer(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsInAnExpressionBody() + { + return VerifyAsync(""" + byte[] M(MemoryStream ms) => ms.GetBuffer(); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalHasNoInitializer() + { + return VerifyAsync( + """ + void M() + { + MemoryStream ms; + var buffer = ms.GetBuffer(); + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreationAndTheCallDoNotBind() + { + return VerifyAsync( + """ + void M() + { + var ms = new MemoryStream(missing); + var buffer = ms.GetBuffer(); + var other = unknown.GetBuffer(); + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/HandRolledProcessCaptureBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HandRolledProcessCaptureBranchCoverageTests.cs new file mode 100644 index 00000000..830169e4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/HandRolledProcessCaptureBranchCoverageTests.cs @@ -0,0 +1,729 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the launch shapes that bind a redirect flag to the process that waits. +/// +public sealed class HandRolledProcessCaptureBranchCoverageTests +{ + private static Task VerifyAsync(string source) + { + return AnalyzerTestRunner.VerifyAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenStartInfoIsAssignedToTheProcessMember() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process(); + process.StartInfo = new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenStartInfoIsSetInTheProcessInitializer() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process + { + StartInfo = new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }, + }; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheProcessInitializerIsAssignedToAnExistingLocal() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + Process process; + process = new Process + { + StartInfo = new ProcessStartInfo(file) + { + RedirectStandardError = true, + }, + }; + process.Start(); + string error = process.StandardError.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenProcessStartResultIsAssignedToAnExistingLocal() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + Process? process; + process = Process.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + string output = process!.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStartInfoCreationIsParenthesized() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + var process = Process.Start((new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + })); + string output = process!.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStartInfoLocalIsAssignedAfterCreation() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process(); + var info = new ProcessStartInfo(file); + info.RedirectStandardError = true; + process.StartInfo = info; + process.Start(); + string error = process.StandardError.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheProcessIsAField_ReachedThroughThis() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + private readonly Process process = new Process(); + + void M(string file) + { + this.process.StartInfo.FileName = file; + this.process.StartInfo.RedirectStandardOutput = true; + this.process.Start(); + string output = this.process.StandardOutput.ReadToEnd(); + {|E128223:this.process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheProcessIsAStaticField_ReachedThroughItsType() + { + return VerifyAsync(""" + using System.Diagnostics; + class Holder + { + internal static readonly Process Child = new Process(); + } + + class C + { + void M(string file) + { + Holder.Child.StartInfo.FileName = file; + Holder.Child.StartInfo.RedirectStandardOutput = true; + Holder.Child.Start(); + string output = Holder.Child.StandardOutput.ReadToEnd(); + {|E128223:Holder.Child.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTargetTypedStartInfoIsPassedToStart() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + ProcessStartInfo info = new(file) + { + RedirectStandardOutput = true, + }; + using var process = Process.Start(info); + string output = process!.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsNotOnAProcess() + { + return VerifyAsync(""" + class Waiter + { + public void WaitForExit() + { + } + } + + class C + { + void M(Waiter waiter) + { + waiter.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsOnACallResult() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + Process Create() => new Process(); + + void M() + { + Create().WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsInAFieldInitializerLambda() + { + return VerifyAsync(""" + using System; + using System.Diagnostics; + class C + { + private static readonly Process Child = new Process(); + + private static readonly Action Wait = () => Child.WaitForExit(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagIsNotTheLiteralTrue() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file, bool capture) + { + using var process = new Process(); + process.StartInfo.FileName = file; + process.StartInfo.RedirectStandardOutput = capture; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagUsesACompoundAssignment() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process(); + process.StartInfo.FileName = file; + process.StartInfo.RedirectStandardOutput |= true; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnElementAssignmentPrecedesTheWait() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file, bool[] flags) + { + using var process = Process.Start(file); + flags[0] = true; + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagBelongsToAnotherType() + { + return VerifyAsync(""" + using System.Diagnostics; + class Options + { + public bool RedirectStandardOutput { get; set; } + } + + class C + { + void M(string file) + { + var options = new Options { RedirectStandardOutput = true }; + options.RedirectStandardOutput = true; + using var process = Process.Start(file); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartInfoCreationIsNotStoredAnywhere() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + static void Use(ProcessStartInfo info) + { + } + + void M(string file) + { + Use(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + using var process = Process.Start(file); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartInfoIsPassedToAnotherMethodNamedStart() + { + return VerifyAsync(""" + using System.Diagnostics; + class Launcher + { + public static Process? Start(ProcessStartInfo info) => null; + } + + class C + { + void M(string file) + { + var process = Launcher.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartInfoIsAssignedToAnotherProcess() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var other = new Process(); + using var process = new Process(); + other.StartInfo = new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }; + process.StartInfo = new ProcessStartInfo(file); + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamIsReadThroughALocal() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = Process.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + var reader = process!.StandardOutput; + string output = reader.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReadTargetsAnotherProcess() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = Process.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + using var other = Process.Start(file); + string output = other!.StandardOutput.ReadToEnd(); + process!.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReadIsNotOnAStandardStream() + { + return VerifyAsync(""" + using System.Diagnostics; + using System.IO; + class C + { + void M(string file) + { + using var process = Process.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + string text = process!.StandardInput.ToString(); + Stream stream = process.StandardOutput.BaseStream; + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStartInfoCreationHasASuppressionOperator() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + var process = (Process.Start((new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + })!))!; + string output = process.StandardOutput.ReadToEnd(); + {|E128223:process.WaitForExit()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartedProcessIsPassedToAnotherMethod() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + static void Use(Process? process) + { + } + + void M(string file) + { + var info = new ProcessStartInfo(file); + info.RedirectStandardOutput = true; + Use(Process.Start(info)); + using var process = Process.Start(file); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagReceiverIsAConditionalExpression() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file, bool first) + { + using var left = Process.Start(file); + using var right = Process.Start(file); + (first ? left : right)!.StartInfo.RedirectStandardOutput = true; + string output = left!.StandardOutput.ReadToEnd(); + left.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFlagIsSetInANestedInitializer() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process + { + StartInfo = { FileName = file, RedirectStandardOutput = true }, + }; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartInfoIsAnArgumentOfAConstructor() + { + return VerifyAsync(""" + using System.Diagnostics; + class Wrapper + { + public Wrapper(ProcessStartInfo info) + { + Info = info; + } + + public ProcessStartInfo Info { get; } + } + + class C + { + void M(string file) + { + var wrapper = new Wrapper(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + using var process = Process.Start(wrapper.Info); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStartInfoIsReturnedFromALambda() + { + return VerifyAsync(""" + using System; + using System.Diagnostics; + class C + { + void M(string file) + { + Func create = () => new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }; + using var process = Process.Start(create()); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreationIsAssignedToAnExistingStartInfoLocal() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string file) + { + using var process = new Process(); + ProcessStartInfo info; + info = new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }; + process.StartInfo = info; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreationIsAssignedToAMemberThatIsNotStartInfo() + { + return VerifyAsync(""" + using System.Diagnostics; + class Box + { + public ProcessStartInfo? Info { get; set; } + } + + class C + { + void M(string file) + { + var box = new Box(); + box.Info = new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }; + using var process = Process.Start(box.Info); + string output = process!.StandardOutput.ReadToEnd(); + process.WaitForExit(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAReadHasNoMemberAccessReceiver() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + string ReadToEnd() => string.Empty; + + void M(string file) + { + using var process = Process.Start(new ProcessStartInfo(file) + { + RedirectStandardOutput = true, + }); + string text = ReadToEnd(); + process!.WaitForExit(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HandlerNoDecompressionBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HandlerNoDecompressionBranchCoverageTests.cs new file mode 100644 index 00000000..e350073a --- /dev/null +++ b/tests/E128.Analyzers.Tests/HandlerNoDecompressionBranchCoverageTests.cs @@ -0,0 +1,82 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HandlerNoDecompressionBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALocalAssignedLaterGetsDecompression() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net; + using System.Net.Http; + class C + { + void M() + { + HttpClientHandler handler; + handler = new HttpClientHandler(); + handler.AutomaticDecompression = DecompressionMethods.GZip; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenLaterStatementsSetNothingOnTheHandler() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net.Http; + class C + { + void M(HttpClientHandler other, int[] numbers) + { + var handler = {|E128214:new HttpClientHandler()|}; + handler = other; + numbers[0] = 1; + handler.UseProxy = false; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenDecompressionIsSetOnAnotherHandler() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net; + using System.Net.Http; + class C + { + void M(HttpClientHandler other) + { + var handler = {|E128214:new HttpClientHandler()|}; + other.AutomaticDecompression = DecompressionMethods.GZip; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAFieldAssignmentReceivesTheHandler() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Net.Http; + class C + { + private HttpClientHandler _handler; + + void M() + { + _handler = new HttpClientHandler(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HardcodedSecretBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HardcodedSecretBranchCoverageTests.cs new file mode 100644 index 00000000..30f4de7c --- /dev/null +++ b/tests/E128.Analyzers.Tests/HardcodedSecretBranchCoverageTests.cs @@ -0,0 +1,196 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HardcodedSecretBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CredentialValuesInEachDeclarationShape() + { + return VerifyAsync(""" + using System.Collections.Generic; + class Holder + { + public string Password { get; set; } = ""; + } + + class C + { + string field = "Sup3rS3cret!"; + + string Secret { get; } = {|E128165:"Sup3rS3cret!"|}; + + string Token => {|E128165:"Sup3rS3cret!"|}; + + string ApiKey + { + get => {|E128165:"Sup3rS3cret!"|}; + } + + string Credential + { + get + { + return {|E128165:"Sup3rS3cret!"|}; + } + } + + void M(Holder holder, Dictionary map, bool flag, string other) + { + string password = {|E128165:"Sup3rS3cret!"|}; + password = {|E128165:"Sup3rS3cret!"|}; + holder.Password = {|E128165:"Sup3rS3cret!"|}; + map["Password"] = {|E128165:"Sup3rS3cret!"|}; + var copy = new Dictionary { ["Secret"] = {|E128165:"Sup3rS3cret!"|} }; + Use(secret: {|E128165:"Sup3rS3cret!"|}); + string accessKey = other ?? {|E128165:"Sup3rS3cret!"|}; + string token = flag ? {|E128165:"Sup3rS3cret!"|} : other; + string bearer = ({|E128165:"Sup3rS3cret!"|}); + } + + void Use(string secret) { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLiteralIsNotTheValueOfACredentialTarget() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + class C + { + string Secret + { + set => Use("Sup3rS3cret!"); + } + + string Other() + { + return "Sup3rS3cret!"; + } + + string Name { get; } = "Sup3rS3cret!"; + + string Password + { + get + { + Func make = () => { return "Sup3rS3cret!"; }; + string Local() { return "Sup3rS3cret!"; } + return make() + Local(); + } + } + + void M(Dictionary map, bool flag, string key, string other) + { + map[key] = "Sup3rS3cret!"; + var title = "Sup3rS3cret!"; + string password = flag ? other : "x"; + string token = (flag ? "Sup3rS3cret!" : other) + other; + Use("Sup3rS3cret!"); + string secret = Compose("Sup3rS3cret!"); + string tokenWithCondition = ("Sup3rS3cret!" == other ? other : other); + } + + void Use(string value) { } + + string Compose(string value) => value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNameOrTheValueShowsTheStringIsALabel() + { + return VerifyAsync(""" + class C + { + string passwordHeader = "Sup3rS3cret!"; + string tokenName = "Sup3rS3cret!"; + string secretHint = "Sup3rS3cret!"; + string CancellationToken = "Sup3rS3cret!"; + string cancellation_token = "Sup3rS3cret!"; + string password = "short"; + string secret = "has some spaces inside"; + string token = "X-Api-Key"; + string apiKey = "BRAVE_API_KEY"; + string credential = "Auth:Password"; + string bearer = "Some-Header-Name"; + string passwd = "some/path/value"; + string pwd = "dotted.name.value"; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ValuesThatOnlyResembleKeyNames() + { + return VerifyAsync(""" + class C + { + string a_password = {|E128165:"lowercase-hyphenated"|}; + string secret = {|E128165:"Title--Empty"|}; + string token = {|E128165:"Title-lower"|}; + string apikey = {|E128165:"LETMEINPLEASE"|}; + string accesskey = {|E128165:"Pass1-Word2"|}; + string privatekey = {|E128165:"-leading-hyphen"|}; + string api_key = {|E128165:"AbCdEfGh1"|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ConnectionStringsThatPairAServerWithAPassword() + { + return VerifyAsync(""" + class C + { + void M(string pwdValue) + { + var a = {|E128165:"Server=db;Password=hunter2hunter2"|}; + var b = {|E128165:"Data Source=db; Pwd = hunter2hunter2 ;Trusted=true"|}; + var c = {|E128165:"Host=db;Database=x;Password=hunter2hunter2;"|}; + var d = "Server=db;Password={0}"; + var e = "Server=db;Password="; + var f = "Password=hunter2hunter2;Timeout=30"; + var g = "Server=db;NoEqualsHere;Timeout=30"; + var h = "Server=db;=orphan;Timeout=30"; + var i = "https://example.test/?host=a&password=hunter2hunter2"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_Utf8LiteralsAssignedToCredentialNames() + { + return VerifyAsync(""" + using System; + class C + { + ReadOnlySpan Password => {|E128165:"Sup3rS3cret!"u8|}; + + void M() + { + ReadOnlySpan token = {|E128165:"Sup3rS3cret!"u8|}; + ReadOnlySpan title = "Sup3rS3cret!"u8; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HardcodedUrlBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HardcodedUrlBranchCoverageTests.cs new file mode 100644 index 00000000..a7581efb --- /dev/null +++ b/tests/E128.Analyzers.Tests/HardcodedUrlBranchCoverageTests.cs @@ -0,0 +1,82 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HardcodedUrlBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAFieldDeclaresOneFixedValue() + { + return VerifyAsync(""" + class C + { + const string A = "https://api.contoso.test/v1"; + + static readonly string B = "https://api.contoso.test/v2"; + + public static readonly string C2 = "https://api.contoso.test/v3"; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_FieldsAndPropertiesThatAreNotFixedDeclarations() + { + return VerifyAsync(""" + class C + { + readonly string a = {|E128164:"https://api.contoso.test/v1"|}; + + static string b = {|E128164:"https://api.contoso.test/v2"|}; + + string Property { get; } = {|E128164:"https://api.contoso.test/v3"|}; + + string Arrow => {|E128164:"https://api.contoso.test/v4"|}; + + string Method() => {|E128164:"https://api.contoso.test/v5"|}; + + void Use() + { + string Local() => {|E128164:"https://api.contoso.test/v6"|}; + var x = {|E128164:"HTTPS://API.CONTOSO.TEST/v7"|}; + } + } + + class ClientSettings + { + string Url { get; } = {|E128164:"https://api.contoso.test/v8"|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTextIsNotAnAbsoluteUrlWithAHost() + { + return VerifyAsync(""" + class C + { + void M() + { + var a = "http://"; + var b = "https://"; + var c = "ftp://files.contoso.test"; + var d = "not a url"; + var e = "http://api.example.com/path"; + var f = "https://EXAMPLE.org"; + var g = "https://sub.w3.org/ns"; + var h = "mailto:user@example.com"; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundBranchCoverageTests.cs new file mode 100644 index 00000000..f89f85fa --- /dev/null +++ b/tests/E128.Analyzers.Tests/HttpBodyReadWithoutSizeBoundBranchCoverageTests.cs @@ -0,0 +1,261 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HttpBodyReadWithoutSizeBoundBranchCoverageTests +{ + private const string Length = "response.Content.Headers.ContentLength"; + + private const string Read = "_ = await response.Content.ReadAsStringAsync();"; + + private const string ReportedRead = "_ = await {|E128227:response.Content.ReadAsStringAsync()|};"; + + private static Task VerifyAsync(string members) + { + var source = $$""" + using System; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + class C + { + HttpResponseMessage field = new HttpResponseMessage(); + + {{members}} + } + """; + + return AnalyzerTestRunner.VerifyAsync(source); + } + + private static string Method(string name, string body) + { + return $$""" + async Task {{name}}(HttpResponseMessage response, bool flag, int count) + { + {{body}} + } + """; + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAGuardThatStopsTheFlowHoldsForANullLength() + { + var methods = string.Join( + "\n\n", + Method("OrNull", $" if ({Length} == null || {Length} > 100) {{ throw new InvalidOperationException(); }}\n {Read}"), + Method("NotLessOrEqual", $" if (!({Length} <= 100)) {{ return; }}\n {Read}"), + Method("NotAnd", $" if (!({Length} != null && {Length} < 100)) {{ return; }}\n {Read}"), + Method("IsNull", $" if ({Length} is null) {{ return; }}\n {Read}"), + Method("IsNullOr", $" if ({Length} is null or > 100) {{ return; }}\n {Read}"), + Method("IsNotRange", $" if ({Length} is not (> 0 and < 100)) {{ return; }}\n {Read}"), + Method("NullOnTheLeft", $" foreach (var item in new[] {{ 1 }})\n {{\n if (null == {Length}) {{ continue; }}\n {Read}\n }}"), + Method("BothNull", $" if (({Length} == null) && ({Length} == null)) {{ return; }}\n {Read}"), + Method("InsideBlock", $" {{\n if ({Length} is null or > 100) {{ return; }}\n }}\n {Read}"), + Method("ReadInThen", $" if ({Length} is not null && {Length} < 100)\n {{\n {Read}\n }}"), + Method("ReadInThenRelational", $" if ({Length} is > 0 and < 100)\n {{\n {Read}\n }}")); + + return VerifyAsync(methods); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardCannotProveTheLengthWasKnown() + { + var methods = string.Join( + "\n\n", + Method("Greater", $" if ({Length} > 100) {{ return; }}\n {ReportedRead}"), + Method("OrUnknown", $" if ({Length} > 100 || flag) {{ return; }}\n {ReportedRead}"), + Method("AndUnknown", $" if ({Length} == null && flag) {{ return; }}\n {ReportedRead}"), + Method("NotOrUnknown", $" if (!(flag || {Length} > 1)) {{ return; }}\n {ReportedRead}"), + Method("DeclarationPattern", $" if ({Length} is long known) {{ return; }}\n {ReportedRead}"), + Method("ConstantPattern", $" if ({Length} is 5) {{ return; }}\n {ReportedRead}"), + Method("NotNull", $" if ({Length} != null) {{ return; }}\n {ReportedRead}"), + Method("ReadWhenNull", $" if ({Length} == null)\n {{\n {ReportedRead}\n }}"), + Method("NoTermination", $" if ({Length} == null) {{ count++; }}\n {ReportedRead}"), + Method("NegatedUnknown", $" if (!({Length}.HasValue && flag)) {{ return; }}\n {ReportedRead}")); + + return VerifyAsync(methods); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardSitsInABranchTheReadCanSkip() + { + var guard = $"if ({Length} is null or > 100) {{{{ throw new InvalidOperationException(); }}}}"; + var methods = string.Join( + "\n\n", + Method("InIf", $" if (flag) {{ {guard} }}\n {ReportedRead}"), + Method("InElse", $" if (flag) {{ count++; }} else {{ {guard} }}\n {ReportedRead}"), + Method("InCatch", $" try {{ count++; }} catch (InvalidOperationException) {{ {guard} }}\n {ReportedRead}"), + Method("InFinally", $" try {{ count++; }} finally {{ {guard} }}\n {ReportedRead}"), + Method("InFor", $" for (var i = 0; i < 1; i++) {{ {guard} }}\n {ReportedRead}"), + Method("InForEach", $" foreach (var i in new[] {{ 1 }}) {{ {guard} }}\n {ReportedRead}"), + Method("InWhile", $" while (flag) {{ {guard} }}\n {ReportedRead}"), + Method("InDo", $" do {{ {guard} }} while (flag);\n {ReportedRead}"), + Method("InUnbracedWhile", $" while (flag) {{ {guard} }}\n {ReportedRead}"), + Method("InLambda", $" Action inner = () => {{ {guard} }};\n {ReportedRead}"), + Method("InLocalFunction", $" void Inner() {{ {guard} }}\n {ReportedRead}"), + Method("AfterTheRead", $" {ReportedRead}\n {guard}")); + + return VerifyAsync(methods); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLengthLivesInALocalOfTheSameChain() + { + var methods = string.Join( + "\n\n", + Method("Plain", $" var length = {Length};\n if (length is null or > 100) {{ return; }}\n {Read}"), + Method("Parenthesized", $" var length = ({Length});\n if (length is null or > 100) {{ return; }}\n {Read}")); + var reports = string.Join( + "\n\n", + Method("OtherChain", $" var other = field.Content.Headers.ContentLength;\n if (other is null or > 100) {{ return; }}\n {ReportedRead}"), + Method("NotALength", $" var small = count;\n if (small > 100) {{ return; }}\n {ReportedRead}"), + Method("NotAMember", $" var text = response.ToString();\n if (text is null) {{ return; }}\n {ReportedRead}")); + + return VerifyAsync(methods + "\n\n" + reports); + } + + [Fact] + [Trait("Category", "CI")] + public Task Resolves_TheContentChainThroughThisPostfixParenthesesAndConditionalAccess() + { + var silent = string.Join( + "\n\n", + """ + async Task ThisRoot() + { + if (this.field.Content.Headers.ContentLength is null or > 100) { return; } + _ = await this.field.Content.ReadAsStringAsync(); + } + """, + """ + async Task ParenthesizedRoot(HttpResponseMessage response) + { + if ((response).Content.Headers.ContentLength is null or > 100) { return; } + _ = await (response).Content.ReadAsStringAsync(); + } + """, + """ + async Task PostfixRoot(HttpResponseMessage response) + { + if (response!.Content.Headers.ContentLength is null or > 100) { return; } + _ = await response!.Content.ReadAsStringAsync(); + } + """, + """ + async Task ConditionalInParentheses(HttpResponseMessage response) + { + if ((response?.Content).Headers.ContentLength is null or > 100) { return; } + _ = await (response?.Content).ReadAsStringAsync(); + } + """); + var reports = string.Join( + "\n\n", + """ + async Task ThisAgainstPlain() + { + if (this.field.Content.Headers.ContentLength is null or > 100) { return; } + _ = await {|E128227:field.Content.ReadAsStringAsync()|}; + } + """, + """ + HttpResponseMessage Get() => field; + + async Task CallRoot() + { + if (Get().Content.Headers.ContentLength is null or > 100) { return; } + _ = await {|E128227:Get().Content.ReadAsStringAsync()|}; + } + """); + + return VerifyAsync(silent + "\n\n" + reports); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ReadsThatLiveOutsideAMethodBodyOrInALambda() + { + return VerifyAsync(""" + Task expressionBodied(HttpContent content) => {|E128227:content.ReadAsStringAsync()|}; + + Task fieldRead = {|E128227:new StreamContent(System.IO.Stream.Null).ReadAsStringAsync()|}; + + async Task LambdaBodies(HttpResponseMessage response) + { + Func> a = () => {|E128227:response.Content.ReadAsStringAsync()|}; + Func> b = async () => + { + if (response.Content.Headers.ContentLength is null or > 100) { throw new InvalidOperationException(); } + return await response.Content.ReadAsStringAsync(); + }; + await a(); + await b(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Handles_CappedBufferLoadsByRootDominanceAndOverload() + { + var methods = string.Join( + "\n\n", + Method("IntCap", $" await response.Content.LoadIntoBufferAsync(100);\n {Read}"), + Method("TokenCap", $" await response.Content.LoadIntoBufferAsync(100, CancellationToken.None);\n {Read}"), + Method("OtherRoot", $" await field.Content.LoadIntoBufferAsync(100);\n {ReportedRead}"), + Method("NoCap", $" await response.Content.LoadIntoBufferAsync();\n {ReportedRead}"), + Method("InBranch", $" if (flag) {{ await response.Content.LoadIntoBufferAsync(100); }}\n {ReportedRead}"), + Method("TokenOnly", $" await response.Content.LoadIntoBufferAsync(CancellationToken.None);\n {ReportedRead}"), + Method("AfterTheRead", $" {ReportedRead}\n await response.Content.LoadIntoBufferAsync(100);")); + + return VerifyAsync(methods); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheContentIsKnownToBeInMemoryOrNotHttpContent() + { + return VerifyAsync(""" + async Task InMemory(byte[] bytes) + { + _ = await new ByteArrayContent(bytes).ReadAsStringAsync(); + _ = await new ReadOnlyMemoryContent(bytes).ReadAsByteArrayAsync(); + _ = await new StringContent("text").ReadAsStringAsync(); + _ = await System.Net.Http.Json.JsonContent.Create(1).ReadAsStringAsync(); + } + + async Task Other(Own own) + { + _ = await own.ReadAsStringAsync(); + _ = await own.Other(); + } + } + + class Own + { + public Task ReadAsStringAsync() => Task.FromResult(""); + + public Task Other() => Task.FromResult(""); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AContentChainThatIsNotANamedReceiver() + { + return VerifyAsync(""" + async Task Chains(HttpClient client) + { + _ = await {|E128227:(await client.GetAsync("x")).Content.ReadAsStringAsync()|}; + _ = await client.GetAsync("y"); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageTests.cs new file mode 100644 index 00000000..6b2e22a3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/HttpClientCertificateBypassBranchCoverageTests.cs @@ -0,0 +1,180 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HttpClientCertificateBypassBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_DelegatesThatAReferencedMethodLocalOrFieldHolds() + { + return VerifyAsync(""" + using System.Net.Http; + using System.Net.Security; + using System.Security.Cryptography.X509Certificates; + + class C + { + static readonly RemoteCertificateValidationCallback FieldCallback = (_, _, _, _) => true; + + static bool AcceptAll(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) => true; + + static bool AcceptWithBlock(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) + { + return true; + } + + static bool Inspect(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) + { + var ok = errors == SslPolicyErrors.None; + return ok; + } + + void M(SslClientAuthenticationOptions options) + { + RemoteCertificateValidationCallback local = (_, _, _, _) => true; + RemoteCertificateValidationCallback second = local; + + {|E128156:options.RemoteCertificateValidationCallback = local|}; + {|E128156:options.RemoteCertificateValidationCallback = FieldCallback|}; + {|E128156:options.RemoteCertificateValidationCallback = AcceptAll|}; + {|E128156:options.RemoteCertificateValidationCallback = AcceptWithBlock|}; + options.RemoteCertificateValidationCallback = second; + options.RemoteCertificateValidationCallback = Inspect; + + bool LocalFunction(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) => true; + bool LocalBlock(object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) + { + return true; + } + + {|E128156:options.RemoteCertificateValidationCallback = LocalFunction|}; + {|E128156:options.RemoteCertificateValidationCallback = LocalBlock|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallbackIsMissingUnknownOrNotDecidable() + { + return VerifyAsync(""" + using System; + using System.Net.Http; + using System.Net.Security; + using System.Security.Cryptography.X509Certificates; + + class C + { + RemoteCertificateValidationCallback? field; + + void Use(RemoteCertificateValidationCallback callback) { } + + void M(SslClientAuthenticationOptions options, RemoteCertificateValidationCallback parameter, bool flag) + { + options.RemoteCertificateValidationCallback = null; + options.RemoteCertificateValidationCallback = parameter; + options.RemoteCertificateValidationCallback = field; + options.RemoteCertificateValidationCallback = (_, _, _, errors) => + { + if (errors == SslPolicyErrors.None) + { + return true; + } + + return false; + }; + options.RemoteCertificateValidationCallback = (_, _, _, errors) => { var x = 1; return true; }; + options.RemoteCertificateValidationCallback = (_, _, _, errors) => errors == SslPolicyErrors.None; + options.RemoteCertificateValidationCallback = (_, _, _, errors) => errors == SslPolicyErrors.None && true; + options.RemoteCertificateValidationCallback = flag ? parameter : parameter; + Use((_, _, _, _) => true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAssignedPropertyBelongsToAnotherType() + { + return VerifyAsync(""" + using System; + + class Other + { + public Func? ServerCertificateCustomValidationCallback { get; set; } + + public Func? RemoteCertificateValidationCallback { get; set; } + + public Func? Something { get; set; } + } + + class C + { + void M(Other other) + { + other.ServerCertificateCustomValidationCallback = _ => true; + other.RemoteCertificateValidationCallback = _ => true; + other.Something = _ => true; + Func[] array = new Func[1]; + array[0] = _ => true; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TheDangerousValidatorAndOrExpressionsThroughAHandlerProperty() + { + return VerifyAsync(""" + using System.Net.Http; + using System.Net.Security; + class C + { + void M(HttpClientHandler handler, bool flag) + { + {|E128156:handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator|}; + {|E128156:handler.ServerCertificateCustomValidationCallback = (_, _, _, errors) => flag || true|}; + {|E128156:handler.ServerCertificateCustomValidationCallback = (_, _, _, errors) => (true || flag)|}; + {|E128156:handler.ServerCertificateCustomValidationCallback = ((_, _, _, _) => true)|}; + handler.ServerCertificateCustomValidationCallback = (_, _, _, errors) => flag || errors == SslPolicyErrors.None; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_SslStreamCreatedWithAnAcceptAllCallbackAndSilentOtherwise() + { + return VerifyAsync(""" + using System.IO; + using System.Net.Security; + class C + { + static bool AcceptAll(object sender, System.Security.Cryptography.X509Certificates.X509Certificate? c, System.Security.Cryptography.X509Certificates.X509Chain? ch, SslPolicyErrors e) => true; + + void M(Stream stream, RemoteCertificateValidationCallback parameter) + { + var a = {|E128156:new SslStream(stream, false, (_, _, _, _) => true)|}; + SslStream b = {|E128156:new(stream, false, AcceptAll)|}; + var c = new SslStream(stream); + var d = new SslStream(stream, false); + var e = new SslStream(stream, false, parameter); + var f = new SslStream(stream, false, (_, _, _, errors) => errors == SslPolicyErrors.None); + var g = new MemoryStream(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HttpClientInfiniteTimeoutBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HttpClientInfiniteTimeoutBranchCoverageTests.cs new file mode 100644 index 00000000..72c3413e --- /dev/null +++ b/tests/E128.Analyzers.Tests/HttpClientInfiniteTimeoutBranchCoverageTests.cs @@ -0,0 +1,83 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HttpClientInfiniteTimeoutBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Net.Http;\nusing System.Threading;\nclass Other { public TimeSpan Timeout { get; set; } }\n" + + "class C\n{\n TimeSpan _field;\n void M(HttpClient client, Other other, int milliseconds)\n {\n" + body + "\n }\n}\n"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("-1L")] + [InlineData("-1.0")] + [InlineData("-1")] + public Task Reports_ForEveryConstantFormOfMinusOneMillisecond(string literal) + { + return VerifyAsync($$""" + {|E128181:client.Timeout = TimeSpan.FromMilliseconds({{literal}})|}; + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("TimeSpan.FromMilliseconds(-1.5)")] + [InlineData("TimeSpan.FromMilliseconds(-2L)")] + [InlineData("TimeSpan.FromMilliseconds(30000)")] + [InlineData("TimeSpan.FromMilliseconds(milliseconds)")] + [InlineData("TimeSpan.FromSeconds(-1)")] + [InlineData("TimeSpan.Zero")] + [InlineData("_field")] + [InlineData("Timeout.InfiniteTimeSpan - TimeSpan.Zero")] + public Task Silent_ForFiniteOrComputedTimeouts(string value) + { + return VerifyAsync($$""" + client.Timeout = {{value}}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForATimeoutPropertyOnAnotherTypeAndForNonProperties() + { + return VerifyAsync(""" + other.Timeout = Timeout.InfiniteTimeSpan; + _field = Timeout.InfiniteTimeSpan; + var local = TimeSpan.Zero; + local = Timeout.InfiniteTimeSpan; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnotherHttpClientProperty() + { + return VerifyAsync(""" + client.MaxResponseContentBufferSize = 10; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInfiniteTimeSpanNamedFieldOnAnotherType() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Net.Http; + static class Limits { public static readonly TimeSpan InfiniteTimeSpan = TimeSpan.FromMilliseconds(-1); } + class C + { + void M(HttpClient client) + { + client.Timeout = Limits.InfiniteTimeSpan; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchBranchCoverageTests.cs new file mode 100644 index 00000000..d71c1647 --- /dev/null +++ b/tests/E128.Analyzers.Tests/HttpClientMissingOceCatchBranchCoverageTests.cs @@ -0,0 +1,181 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class HttpClientMissingOceCatchBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n" + + "sealed class Client : HttpClient { }\n" + + "class C\n{\n private readonly HttpClient _client = new();\n" + members + "}\n"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("PostAsync(\"u\", null)")] + [InlineData("PutAsync(\"u\", null)")] + [InlineData("DeleteAsync(\"u\")")] + [InlineData("SendAsync(new HttpRequestMessage())")] + public Task Reports_ForEachRequestMethodWithABroadCatch(string call) + { + return VerifyAsync($$""" + async Task M() + { + try + { + await _client.{{call}}; + } + {|E128051:catch (Exception)|} + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForACallOnAnHttpClientSubclass() + { + return VerifyAsync(""" + async Task M(Client client) + { + try + { + await client.GetAsync("u"); + } + {|E128051:catch (Exception)|} + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForMethodsThatAreNotRequestMethods() + { + return VerifyAsync(""" + async Task M() + { + try + { + await _client.GetStringAsync("u"); + } + catch (Exception) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForALocalFunctionNamedLikeARequestMethod() + { + return VerifyAsync(""" + async Task M() + { + try + { + await GetAsync(); + } + catch (Exception) + { + } + + static Task GetAsync() => Task.CompletedTask; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRequestIsOutsideTheTryBlock() + { + return VerifyAsync(""" + async Task M() + { + await _client.GetAsync("u"); + try + { + await Task.Delay(1); + } + catch (Exception) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenANarrowerCatchHandlesTheRequest() + { + return VerifyAsync(""" + async Task M() + { + try + { + await _client.GetAsync("u"); + } + catch (HttpRequestException) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenADerivedCancellationCatchPrecedesTheBroadCatch() + { + return VerifyAsync(""" + async Task M() + { + try + { + await _client.GetAsync("u"); + } + catch (TaskCanceledException) + { + } + catch (Exception) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnrelatedCatchPrecedesTheBroadCatch() + { + return VerifyAsync(""" + async Task M() + { + try + { + await _client.GetAsync("u"); + } + catch (HttpRequestException) + { + } + {|E128051:catch (Exception)|} + { + } + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ImmutableArrayDefaultBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ImmutableArrayDefaultBranchCoverageTests.cs new file mode 100644 index 00000000..ee24e209 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ImmutableArrayDefaultBranchCoverageTests.cs @@ -0,0 +1,92 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ImmutableArrayDefaultBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenATupleDeconstructionAssignsTheField() + { + return VerifyAsync(""" + private ImmutableArray _first; + private ImmutableArray _second; + private ImmutableArray _third; + + void Set(ImmutableArray a, ImmutableArray b, ImmutableArray c) + { + (_first, (_second, _third)) = (a, (b, c)); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAThisQualifiedAssignmentSetsTheField() + { + return VerifyAsync(""" + private ImmutableArray _items; + + void Set(ImmutableArray value) + { + this._items = value; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenARefOrOutArgumentPassesTheField() + { + return VerifyAsync(""" + private ImmutableArray _viaRef; + private ImmutableArray _viaOut; + + void Fill() + { + Replace(ref _viaRef); + Create(out _viaOut); + } + + static void Replace(ref ImmutableArray target) { target = ImmutableArray.Empty; } + + static void Create(out ImmutableArray target) { target = ImmutableArray.Empty; } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyOtherTargetsAreAssignedOrPassed() + { + return VerifyAsync(""" + private ImmutableArray {|E128163:_items|}; + private int _count; + + void Work(List list, int[] numbers) + { + list[0] = 1; + numbers[0] = 2; + _count = _items.Length; + int local = 0; + Touch(ref local); + Use(_items); + } + + static void Touch(ref int value) { } + + static void Use(ImmutableArray value) { } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..41ef627e --- /dev/null +++ b/tests/E128.Analyzers.Tests/ImplicitStateMachineAnalyzerBranchCoverageTests.cs @@ -0,0 +1,469 @@ +using System; +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ImplicitStateMachineAnalyzerBranchCoverageTests +{ + private const string FourFlagsBody = """ + { + private bool _a; + private bool _b; + private bool _c; + private bool _d; + private bool _once; + private int _count; + + public void SetA(bool value) { _a = value; } + public void SetB(bool value) { _b = value; } + public void SetC(bool value) { _c = value; } + public void SetD(bool value) { _d = value; } + public void Arm() { _once = true; } + + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + private static Task VerifyReadAsync(string condition, bool fires, string extraMembers = "") + { + var name = fires ? "{|E128218:Machine|}" : "Machine"; + return VerifyAsync( + "sealed class " + name + "\n" + FourFlagsBody + extraMembers + " public void Run() { " + condition + " }\n}\n"); + } + + private static Task VerifyForwardingAsync( + Func getter, + Func setter, + bool fires) + { + var name = fires ? "{|E128218:Machine|}" : "Machine"; + var code = "sealed class " + name + "\n{\n" + + " private bool _a;\n private bool _b;\n private bool _c;\n" + + Property("A", getter, setter, "_a", "_b") + + Property("B", getter, setter, "_b", "_c") + + Property("C", getter, setter, "_c", "_a") + + " public void X() { A = true; B = false; C = true; }\n" + + " public void Y() { A = false; B = true; C = false; }\n}\n"; + return VerifyAsync(code); + } + + private static string Property( + string name, + Func getter, + Func setter, + string field, + string other) + { + return " public bool " + name + " { " + getter(field, other) + " " + setter(field, other) + " }\n"; + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForCompoundAssignmentsOfThreeFlags() + { + return VerifyAsync(""" + sealed class {|E128218:Machine|} + { + private bool _a; + private bool _b; + private bool _c; + + public void Merge(bool x) + { + _a |= x; + _b &= x; + _c |= x; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForWritesThatTargetNoCandidateField() + { + return VerifyAsync(""" + sealed class Machine + { + private bool _a; + private bool _b; + private bool _c; + private int _count; + private readonly bool[] _items = new bool[2]; + + public void Run(Machine other, bool x) + { + var local = false; + local = true; + _count = 1; + _items[0] = true; + (_a, _b) = (true, false); + other._a = true; + other._b = false; + other._c = x; + _ = local; + } + } + + static class Registry + { + internal static bool Shared; + } + + record Settings + { + public bool Flag { get; set; } + } + + sealed class Writer + { + public void Run(Settings settings) + { + Registry.Shared = true; + settings.Flag = true; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnUnclusteredFlagIsOnlySetOneWay() + { + return VerifyAsync(""" + sealed class {|E128218:Machine|} + { + private bool _a; + private bool _b; + private bool _c; + private bool _once; + + public void Start() + { + _once = true; + _a = true; + _b = false; + _c = false; + } + + public void Stop() + { + _a = false; + _b = true; + _c = true; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AtTheEarliestOfTwoCoWriteBodies() + { + return VerifyAsync(""" + sealed class {|E128218:Machine|} + { + private bool _a; + private bool _b; + private bool _c; + + public void First() + { + _a = true; + _b = false; + } + + public void Second() + { + _a = false; + _b = true; + _c = true; + } + + public void Third() + { + _c = false; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForNotEqualsTrueNegation() + { + return VerifyReadAsync("if (_a && _b != true) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForTrueNotEqualsFlagNegation() + { + return VerifyReadAsync("if (_a && true != _b) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForFalseEqualsFlagNegation() + { + return VerifyReadAsync("if (_a && false == _b) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForNotTruePatternNegation() + { + return VerifyReadAsync("if (_a && _b is not true) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForTernaryCondition() + { + return VerifyReadAsync("var x = _a && !_b ? 1 : 2; _ = x;", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForForLoopCondition() + { + return VerifyReadAsync("for (var i = 0; _a && !_b; i++) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenNonFlagMembersJoinTheCondition() + { + return VerifyReadAsync("if (!_a && _b && _count > 0) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AtTheEarliestOfTwoCoReads() + { + return VerifyReadAsync("if (_a && !_b) { } if (_c && !_d) { }", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForEqualsTrueAndNotEqualsFalseComparisons() + { + return VerifyReadAsync("if (_a && _b == true && _c != false) { }", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNotFalsePatternAndPlainConstantPattern() + { + return VerifyReadAsync("if (_a && _b is not false && _c is true) { }", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNegatedFlagIsOutsideTheCluster() + { + return VerifyReadAsync("if (_a && _b && !_once) { }", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenOnlyOneClusterFlagIsRead() + { + return VerifyReadAsync("if (_a && !_once) { }", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AfterEmptyForAndForeachLoops() + { + return VerifyReadAsync( + "for (; ; ) { break; } foreach (var item in new int[0]) { _ = item; } do { } while (_a && !_b);", + true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForConditionsOnAnotherInstance() + { + return VerifyReadAsync( + string.Empty, + false, + " public void Peek(Machine other) { if (other._a && !other._b) { } }\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForConditionsInTypesThatAreNotAnalyzed() + { + return VerifyAsync(""" + static class Gate + { + private static bool s_a; + private static bool s_b; + + public static void Run(bool x) + { + if (x && !s_a && s_b) + { + } + + s_a = x; + s_b = !x; + } + } + + sealed class Plain + { + private int _n; + + public void Run(bool x) + { + if (x && !x) + { + _n++; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForInterlockedAndVolatileCallsThatDoNotWriteAFlag() + { + return VerifyAsync(""" + using System.Threading; + + sealed class Machine + { + private bool _a; + private bool _b; + private bool _c; + private int _count; + + public void Run(Machine other) + { + var local = false; + Interlocked.Exchange(ref local, true); + Interlocked.Exchange(ref other._a, true); + Interlocked.Exchange(ref _count, 1); + Interlocked.Increment(ref _count); + Volatile.Write(ref other._b, false); + Volatile.Read(ref _c); + Volatile.Write(ref _count, 3); + } + } + + static class Counter + { + private static int s_value; + + public static void Run() + { + Interlocked.Exchange(ref s_value, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForBlockBodiedForwardingAccessors() + { + return VerifyForwardingAsync(static (f, _) => $"get {{ return {f}; }}", static (f, _) => $"set {{ {f} = value; }}", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForForwardingAccessorsThatUseThis() + { + return VerifyForwardingAsync(static (f, _) => $"get => this.{f};", static (f, _) => $"set => this.{f} = value;", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForMixedBlockAndArrowForwardingAccessors() + { + return VerifyForwardingAsync(static (f, _) => $"get => {f};", static (f, _) => $"set {{ {f} = value; }}", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForBlockGetterWithArrowSetter() + { + return VerifyForwardingAsync(static (f, _) => $"get {{ return {f}; }}", static (f, _) => $"set => {f} = value;", true); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGetterBodyHasTwoStatements() + { + return VerifyForwardingAsync(static (f, _) => $"get {{ var x = {f}; return x; }}", static (f, _) => $"set {{ {f} = value; }}", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSetterBodyHasTwoStatements() + { + return VerifyForwardingAsync(static (f, _) => $"get => {f};", static (f, _) => $"set {{ {f} = value; _ = value; }}", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSetterStoresAnotherValue() + { + return VerifyForwardingAsync(static (f, _) => $"get => {f};", static (f, _) => $"set {{ {f} = !value; }}", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSetterIsACompoundAssignment() + { + return VerifyForwardingAsync(static (f, _) => $"get => {f};", static (f, _) => $"set => {f} |= value;", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGetterReturnsAnExpression() + { + return VerifyForwardingAsync(static (f, _) => $"get => !{f};", static (f, _) => $"set => {f} = value;", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGetterAndSetterNameDifferentFields() + { + return VerifyForwardingAsync(static (f, _) => $"get => {f};", static (_, o) => $"set => {o} = value;", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePropertyHasOnlyASetter() + { + return VerifyForwardingAsync(static (_, _) => string.Empty, static (f, _) => $"set => {f} = value;", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGetterForwardsToAProperty() + { + return VerifyAsync(""" + sealed class Machine + { + private static bool s_shared; + public bool A { get => B; set => B = value; } + public bool B { get; set; } + public bool C { get; set; } + public bool S { get => s_shared; set => s_shared = value; } + + public void X() { A = true; S = true; } + public void Y() { A = false; S = false; } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InModifierHelperBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/InModifierHelperBranchCoverageTests.cs new file mode 100644 index 00000000..d0831862 --- /dev/null +++ b/tests/E128.Analyzers.Tests/InModifierHelperBranchCoverageTests.cs @@ -0,0 +1,66 @@ +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InModifierHelperBranchCoverageTests +{ + private static SyntaxTokenListProbe Modifiers(string declaration) + { + var member = SyntaxFactory.ParseMemberDeclaration(declaration)!; + return new SyntaxTokenListProbe(member.Modifiers); + } + + private readonly record struct SyntaxTokenListProbe(Microsoft.CodeAnalysis.SyntaxTokenList List); + + private static ParameterSyntax Parameter(string text) + { + return SyntaxFactory.ParseParameterList("(" + text + ")").Parameters[0]; + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("public int F;", SyntaxKind.StaticKeyword, "public static")] + [InlineData("private readonly int F;", SyntaxKind.StaticKeyword, "private static readonly")] + [InlineData("private int F;", SyntaxKind.ReadOnlyKeyword, "private readonly")] + [InlineData("static int F;", SyntaxKind.PublicKeyword, "public static")] + [InlineData("int F;", SyntaxKind.StaticKeyword, "static")] + [InlineData("private static int F;", SyntaxKind.StaticKeyword, "private static")] + [InlineData("private int F;", SyntaxKind.ConstKeyword, "private const")] + [InlineData("const int F = 1;", SyntaxKind.StaticKeyword, "static const")] + public void AddModifier_PlacesTheTokenInLanguageReferenceOrder(string declaration, SyntaxKind kind, string expected) + { + var result = InModifierHelper.AddModifier(Modifiers(declaration).List, kind); + Assert.Equal(expected, string.Join(' ', result.Select(static token => token.Text))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("in int value", true)] + [InlineData("ref int value", false)] + [InlineData("int value", false)] + [InlineData("this in int value", true)] + public void HasInModifier_FindsTheInKeyword(string text, bool expected) + { + Assert.Equal(expected, InModifierHelper.HasInModifier(Parameter(text))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("in int value", "int value")] + [InlineData("this in int value", "this int value")] + public void RemoveInModifier_DropsOnlyTheInKeyword(string text, string expected) + { + Assert.Equal(expected, InModifierHelper.RemoveInModifier(Parameter(text)).ToString()); + } + + [Fact] + [Trait("Category", "CI")] + public void RemoveInModifier_KeepsTheLeadingTriviaOfTheTypeAfterTheLastModifier() + { + var parameter = SyntaxFactory.ParseParameterList("(\n in int value)").Parameters[0]; + Assert.Equal(" int value", InModifierHelper.RemoveInModifier(parameter).ToFullString()); + } +} diff --git a/tests/E128.Analyzers.Tests/IndexOfAnyToSearchValuesCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/IndexOfAnyToSearchValuesCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..b4cbd99e --- /dev/null +++ b/tests/E128.Analyzers.Tests/IndexOfAnyToSearchValuesCodeFixBranchCoverageTests.cs @@ -0,0 +1,113 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class IndexOfAnyToSearchValuesCodeFixBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_HandlesAnExplicitCharArray() + { + return VerifyFixAsync( + """ + class C + { + void M(string path) + { + var i = {|E128102:path.IndexOfAny(new char[] { '/', '\\' })|}; + } + } + """, + """ + using System; + + class C + { + private static readonly System.Buffers.SearchValues _pathChars = System.Buffers.SearchValues.Create("/\\"); + + void M(string path) + { + var i = path.AsSpan().IndexOfAny(_pathChars); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTypeAlreadyHasAMemberWithTheFieldName() + { + return VerifyNoFixAsync( + """ + class C + { + private static readonly int _pathChars = 0; + + void M(string path) + { + var i = {|E128102:path.IndexOfAny(new[] { '/', '\\' })|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnElementIsNotACharLiteral() + { + return VerifyNoFixAsync( + """ + class C + { + void M(string path, char separator) + { + var i = {|E128102:path.IndexOfAny(new[] { separator, '\\' })|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheArrayIsEmpty() + { + return VerifyNoFixAsync( + """ + class C + { + void M(string path) + { + var i = {|E128102:path.IndexOfAny(new char[] { })|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAStartIndexIsPassed() + { + return VerifyNoFixAsync( + """ + class C + { + void M(string path) + { + var i = {|E128102:path.IndexOfAny(new[] { '/', '\\' }, 1)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/IndexedForLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/IndexedForLoopBranchCoverageTests.cs new file mode 100644 index 00000000..f14bdaba --- /dev/null +++ b/tests/E128.Analyzers.Tests/IndexedForLoopBranchCoverageTests.cs @@ -0,0 +1,62 @@ +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class IndexedForLoopBranchCoverageTests +{ + private static ForStatementSyntax Loop(string text) + { + var tree = CSharpSyntaxTree.ParseText( + "class C { void M() { " + text + " } }", + cancellationToken: TestContext.Current.CancellationToken); + return tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes().OfType().First(); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (var i = 0; i < items.Length; i++) { }", "i", "items")] + [InlineData("for (int j = 0; j < this.items.Length; j++) { }", "j", "this.items")] + [InlineData("for (var i = 0; i < Get().Length; i++) { }", "i", "Get()")] + public void TryMatch_ReadsTheIndexVariableAndTheLengthOwner(string text, string variable, string owner) + { + var loop = Loop(text); + + Assert.True(IndexedForLoop.TryMatch(loop, out var name, out var boundOwner, out var body)); + Assert.Equal(variable, name); + Assert.Equal(owner, boundOwner?.ToString()); + Assert.Same(loop.Statement, body); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (; ; ) { }")] + [InlineData("for (var i = 0, j = 0; i < items.Length; i++) { }")] + [InlineData("for (var i = 1; i < items.Length; i++) { }")] + [InlineData("for (var i = start; i < items.Length; i++) { }")] + [InlineData("for (int i; i < items.Length; i++) { }")] + [InlineData("for (var i = 0; ; i++) { }")] + [InlineData("for (var i = 0; i <= items.Length; i++) { }")] + [InlineData("for (var i = 0; i < items.Count; i++) { }")] + [InlineData("for (var i = 0; i < items.Length * 2; i++) { }")] + [InlineData("for (var i = 0; 0 < items.Length; i++) { }")] + [InlineData("for (var i = 0; i < items.Length; ) { }")] + [InlineData("for (var i = 0; i < items.Length; i++, j++) { }")] + [InlineData("for (var i = 0; i < items.Length; ++i) { }")] + [InlineData("for (var i = 0; i < items.Length; i--) { }")] + [InlineData("for (var i = 0; i < items.Length; i += 1) { }")] + [InlineData("for (var i = 0; i < items.Length; items.Index++) { }")] + [InlineData("for (var i = 0; j < items.Length; i++) { }")] + [InlineData("for (var i = 0; i < items.Length; j++) { }")] + [InlineData("for (i = 0; i < items.Length; i++) { }")] + public void TryMatch_RejectsLoopsThatAreNotAZeroBasedLengthScan(string text) + { + var loop = Loop(text); + + Assert.False(IndexedForLoop.TryMatch(loop, out var name, out var boundOwner, out _)); + Assert.Empty(name); + Assert.Null(boundOwner); + } +} diff --git a/tests/E128.Analyzers.Tests/InitializerAssignmentsBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/InitializerAssignmentsBranchCoverageTests.cs new file mode 100644 index 00000000..7440286b --- /dev/null +++ b/tests/E128.Analyzers.Tests/InitializerAssignmentsBranchCoverageTests.cs @@ -0,0 +1,40 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InitializerAssignmentsBranchCoverageTests +{ + private static BaseObjectCreationExpressionSyntax Create(string text) + { + return (BaseObjectCreationExpressionSyntax)SyntaxFactory.ParseExpression(text); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("new Widget { Name = \"a\" }", "Name", true)] + [InlineData("new Widget { Other = 1, Name = \"a\" }", "Name", true)] + [InlineData("new Widget { Other = 1 }", "Name", false)] + [InlineData("new Widget { [0] = 1 }", "Name", false)] + [InlineData("new Widget { 1, 2 }", "Name", false)] + [InlineData("new Widget()", "Name", false)] + [InlineData("new Widget { }", "Name", false)] + [InlineData("new() { Name = \"a\" }", "Name", true)] + [InlineData("new Widget { name = \"a\" }", "Name", false)] + public void Assigns_FindsTheNamedPropertyInTheInitializer(string text, string property, bool expected) + { + Assert.Equal(expected, InitializerAssignments.Assigns(Create(text), property)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Name", "Name")] + [InlineData("a[0]", null)] + [InlineData("(a)", null)] + [InlineData("a()", null)] + public void GetAssignedName_ReadsTheSimpleNameOnTheLeft(string text, string? expected) + { + Assert.Equal(expected, InitializerAssignments.GetAssignedName(SyntaxFactory.ParseExpression(text))); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageTests.cs new file mode 100644 index 00000000..5ba6dd8a --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextBranchCoverageTests.cs @@ -0,0 +1,182 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NextBytesIntoASensitiveBufferThroughSliceCalls() + { + return VerifyAsync(""" + using System; + class C + { + byte[] GetBuffer() => new byte[8]; + + void M(Random random, byte[] keyBuffer, byte[] plain) + { + {|E128075:random.NextBytes(keyBuffer.AsSpan(0, 8))|}; + {|E128075:random.NextBytes(keyBuffer.AsSpan())|}; + {|E128075:random.NextBytes(keyBuffer)|}; + Span keySpan = keyBuffer; + {|E128075:random.NextBytes(keySpan.Slice(0, 4))|}; + random.NextBytes(plain.AsSpan()); + random.NextBytes(GetBuffer()); + random.NextBytes(stackalloc byte[8]); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_SensitiveDestinationsReachedThroughValueExpressions() + { + return VerifyAsync(""" + using System; + class C + { + static object Box(int value) => value; + + static T Echo(T value) => value; + + void M(Random random, int count) + { + var tokenBytes = BitConverter.GetBytes({|E128075:random.Next()|}); + var otp = Math.Abs({|E128075:random.Next()|}); + var pinText = {|E128075:random.Next()|}.ToString(); + var nonce = $"{ {|E128075:random.Next()|} }"; + var salt = (long){|E128075:random.Next()|} + 1; + var iv = -{|E128075:random.Next()|}; + var secret = count > 0 ? {|E128075:random.Next()|} : 0; + int? key = null; + key ??= {|E128075:random.Next()|}; + var tokenEcho = Echo({|E128075:random.Next()|}); + var tokenStamp = DateTime.FromBinary({|E128075:random.Next()|}); + var plain = Math.Abs(random.Next()); + var tokenObject = Box(random.Next()); + var tokenSpan = TimeSpan.FromTicks(random.Next()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AssignmentsToSensitiveParametersAndIgnoresOtherTargets() + { + return VerifyAsync(""" + using System; + class C + { + int[] values = new int[4]; + + void Fill(Random random, ref int token, out int pin, int[] numbers) + { + token = {|E128075:random.Next()|}; + pin = {|E128075:random.Next()|}; + numbers[0] = random.Next(); + values[random.Next(4)] = 1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CreationsInAFileThatUsesAspNetCoreCryptography() + { + return VerifyAsync(""" + using System; + + namespace Microsoft.AspNetCore.Cryptography.KeyDerivation + { + public static class KeyDerivation + { + public static int Derive() => 1; + } + } + + class C + { + int M() + { + var d = Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation.Derive(); + return d + {|E128075:new Random()|}.Next(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_CreationsInAFileThatUsesAnAttributeWrittenWithoutItsSuffix() + { + return VerifyAsync(""" + using System; + + namespace System.Security.Cryptography + { + [AttributeUsage(AttributeTargets.Class)] + public sealed class MarkerAttribute : Attribute + { + } + + public sealed class AttributeSuffixOnly : Attribute + { + } + } + + [System.Security.Cryptography.Marker] + class C + { + int M() + { + return {|E128075:new Random()|}.Next(); + } + } + + class D + { + int M() + { + return {|E128075:new Random()|}.Next(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFileNeverNamesACryptographyTypeAndNothingIsSensitive() + { + return VerifyAsync(""" + using System; + + namespace Own.Cryptography + { + public static class Helper + { + public static int Value() => 1; + } + } + + class C + { + int M() + { + var d = Own.Cryptography.Helper.Value(); + return d + new Random().Next(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..f3f8f3ec --- /dev/null +++ b/tests/E128.Analyzers.Tests/InsecureRandomInCryptoContextCodeFixBranchCoverageTests.cs @@ -0,0 +1,58 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InsecureRandomInCryptoContextCodeFixBranchCoverageTests +{ + private static string Source(string expression, string usings) + { + return $$""" + {{usings}} + + class C + { + int M() + { + var token = {{expression}}; + return 0; + } + } + """; + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("{|E128075:Random.Shared|}.Next((byte)1, (byte)7)", "RandomNumberGenerator.GetInt32((byte)1, (byte)7)")] + [InlineData("{|E128075:Random.Shared|}.Next((sbyte)1, (sbyte)7)", "RandomNumberGenerator.GetInt32((sbyte)1, (sbyte)7)")] + [InlineData("{|E128075:Random.Shared|}.Next((short)1, (short)7)", "RandomNumberGenerator.GetInt32((short)1, (short)7)")] + [InlineData("{|E128075:Random.Shared|}.Next((ushort)1, (ushort)7)", "RandomNumberGenerator.GetInt32((ushort)1, (ushort)7)")] + [InlineData("{|E128075:Random.Shared|}.Next('a', 'z')", "RandomNumberGenerator.GetInt32('a', 'z')")] + [InlineData("{|E128075:Random.Shared|}.Next()", "RandomNumberGenerator.GetInt32(int.MaxValue)")] + public Task RandomSharedNext_FixedToGetInt32_ForSmallIntegerConstants(string original, string replacement) + { + return CodeFixTestRunner.RunAsync( + Source(original, "using System;"), + Source(replacement, "using System;\nusing System.Security.Cryptography;")); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDiagnosticIsNotARandomSharedNextCall() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + class C + { + void M(Random random) + { + var token = {|E128075:Random.Shared|}; + var secret = {|E128075:Random.Shared|}.NextDouble(); + var nonce = ({|E128075:Random.Shared|}).Next(5); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/InterfaceMembersBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/InterfaceMembersBranchCoverageTests.cs new file mode 100644 index 00000000..bf7001cf --- /dev/null +++ b/tests/E128.Analyzers.Tests/InterfaceMembersBranchCoverageTests.cs @@ -0,0 +1,176 @@ +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class InterfaceMembersBranchCoverageTests +{ + private const string Source = """ + using System; + using System.Collections.Generic; + + interface IWork + { + void Run(); + void Run(int count); + int Size { get; } + } + + class Implicit : IWork + { + public void Run() { } + public void Run(int count) { } + public int Size => 1; + public void Other() { } + public void Run(string text) { } + } + + class Explicit : IWork + { + void IWork.Run() { } + void IWork.Run(int count) { } + int IWork.Size => 1; + } + + class Plain + { + public void Run() { } + } + + class Base : IWork + { + public virtual void Run() { } + public void Run(int count) { } + public int Size => 1; + } + + class Hider : Base + { + public new void Run() { } + } + + struct Value : IWork + { + public void Run() { } + public void Run(int count) { } + public int Size => 1; + } + + delegate void Handler(); + + class Generic : IWork + { + public void Run() { } + public void Run(int count) { } + public int Size => 1; + public void Add(T item) { } + } + + class Closed : Generic + { + } + """; + + private static (Compilation Compilation, INamedTypeSymbol Type) Get(string typeName) + { + var tree = CSharpSyntaxTree.ParseText(Source, cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "InterfaceProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return (compilation, compilation.GetTypeByMetadataName(typeName)!); + } + + private static IMethodSymbol Method(INamedTypeSymbol type, string name, int parameterCount, SpecialType? parameterType = null) + { + return type.GetMembers(name).OfType().Single( + m => m.Parameters.Length == parameterCount + && (parameterType is null || (m.Parameters.Length > 0 && m.Parameters[0].Type.SpecialType == parameterType))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsTrueForImplicitImplementations() + { + var (_, type) = Get("Implicit"); + Assert.True(InterfaceMembers.Implements(Method(type, "Run", 0))); + Assert.True(InterfaceMembers.Implements(Method(type, "Run", 1, SpecialType.System_Int32))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsFalseForMethodsThatImplementNothing() + { + var (_, type) = Get("Implicit"); + Assert.False(InterfaceMembers.Implements(Method(type, "Other", 0))); + Assert.False(InterfaceMembers.Implements(Method(type, "Run", 1, SpecialType.System_String))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsTrueForExplicitImplementations() + { + var (_, type) = Get("Explicit"); + var methods = type.GetMembers().OfType().Where(static m => m.MethodKind is MethodKind.ExplicitInterfaceImplementation); + Assert.All(methods, static method => Assert.True(InterfaceMembers.Implements(method))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsFalseForAClassWithoutInterfaces() + { + var (_, type) = Get("Plain"); + Assert.False(InterfaceMembers.Implements(Method(type, "Run", 0))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsFalseForInterfaceAndDelegateMembers() + { + var (_, iface) = Get("IWork"); + var (_, handler) = Get("Handler"); + Assert.False(InterfaceMembers.Implements(Method(iface, "Run", 0))); + Assert.False(InterfaceMembers.Implements(handler.GetMembers("Invoke").OfType().Single())); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsFalseForAMethodThatHidesTheImplementation() + { + var (_, hider) = Get("Hider"); + var (_, baseType) = Get("Base"); + Assert.False(InterfaceMembers.Implements(Method(hider, "Run", 0))); + Assert.True(InterfaceMembers.Implements(Method(baseType, "Run", 0))); + } + + [Fact] + [Trait("Category", "CI")] + public void Implements_IsTrueForStructsAndConstructedGenericTypes() + { + var (_, value) = Get("Value"); + var (_, closed) = Get("Closed"); + var constructed = closed.BaseType!; + Assert.True(InterfaceMembers.Implements(Method(value, "Run", 0))); + Assert.True(InterfaceMembers.Implements(Method(constructed, "Run", 0))); + Assert.False(InterfaceMembers.Implements(Method(constructed, "Add", 1))); + } + + [Fact] + [Trait("Category", "CI")] + public void ImplementsMember_ReportsMethodsThatMapToAnInterfaceMember() + { + var (_, type) = Get("Implicit"); + Assert.True(InterfaceMembers.ImplementsMember(Method(type, "Run", 0))); + Assert.False(InterfaceMembers.ImplementsMember(Method(type, "Other", 0))); + } + + [Fact] + [Trait("Category", "CI")] + public void ImplementsMember_IsFalseForClassesWithoutInterfaces() + { + var (_, type) = Get("Plain"); + Assert.False(InterfaceMembers.ImplementsMember(Method(type, "Run", 0))); + } +} diff --git a/tests/E128.Analyzers.Tests/JsonDocumentLifetimeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/JsonDocumentLifetimeBranchCoverageTests.cs new file mode 100644 index 00000000..82896a31 --- /dev/null +++ b/tests/E128.Analyzers.Tests/JsonDocumentLifetimeBranchCoverageTests.cs @@ -0,0 +1,227 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers how the JsonDocument rule finds the parse call and follows the root element. +/// +public sealed class JsonDocumentLifetimeBranchCoverageTests +{ + private static Task VerifyAsync(string source) + { + return AnalyzerTestRunner.VerifyAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenParseIsCalledThroughAStaticImport() + { + return VerifyAsync(""" + using System.Text.Json; + using static System.Text.Json.JsonDocument; + class C + { + void M() + { + var doc = {|E128041:Parse("{}")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenParseIsAssignedToAnExistingLocal() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + void M() + { + JsonDocument doc; + doc = {|E128041:JsonDocument.Parse("{}")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenParseIsTheResourceExpressionOfAUsingStatement() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + void M() + { + using ({|E128041:JsonDocument.Parse("{}")|}) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheUsingStatementReturnsTheRootElement() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + JsonElement M() + { + using (var doc = {|E128041:JsonDocument.Parse("{}")|}) + { + return doc.RootElement; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAPropertyOfTheRootElementIsReturned() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + JsonValueKind M() + { + using var doc = {|E128041:JsonDocument.Parse("{}")|}; + return doc.RootElement.ValueKind; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheClonedChildOfTheRootElementIsReturned() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + JsonElement M() + { + using var doc = JsonDocument.Parse("{}"); + return doc.RootElement.GetProperty("a").Clone(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRootElementIsPassedAsAnArgument() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + static string Describe(JsonElement element) => element.GetRawText(); + + string M() + { + using var doc = JsonDocument.Parse("{}"); + return Describe(doc.RootElement); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRootElementIsConsumedByACall() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + string M() + { + using var doc = JsonDocument.Parse("{}"); + return doc.RootElement.GetRawText(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnEarlyReturnHasNoValue() + { + return VerifyAsync(""" + using System.Text.Json; + class C + { + void M(bool skip) + { + using var doc = JsonDocument.Parse("{}"); + if (skip) + { + return; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheUsingDeclarationSitsInAFieldInitializerLambda() + { + return VerifyAsync(""" + using System; + using System.Text.Json; + class C + { + private static readonly Func Reader = text => + { + using var doc = JsonDocument.Parse(text); + return doc.RootElement; + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenParseBelongsToAnotherType() + { + return VerifyAsync(""" + using System.Text.Json.Nodes; + class C + { + void M() + { + var node = JsonNode.Parse("{}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInvokedExpressionIsNotAName() + { + return VerifyAsync(""" + using System; + class C + { + void M(Func[] parsers) + { + var value = parsers[0]("1"); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LargeStructByValueBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LargeStructByValueBranchCoverageTests.cs new file mode 100644 index 00000000..583fc0d2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LargeStructByValueBranchCoverageTests.cs @@ -0,0 +1,539 @@ +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LargeStructByValueBranchCoverageTests +{ + private static readonly AnalyzerTestOptions UnsafeOptions = new() { AllowUnsafe = true }; + + private static DiagnosticResult Expected(string structName, int size) + { + return new DiagnosticResult("E128217", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("value", structName, size); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("bool", 1)] + [InlineData("byte", 1)] + [InlineData("sbyte", 1)] + [InlineData("char", 2)] + [InlineData("short", 2)] + [InlineData("ushort", 2)] + [InlineData("int", 4)] + [InlineData("uint", 4)] + [InlineData("float", 4)] + [InlineData("long", 8)] + [InlineData("ulong", 8)] + [InlineData("double", 8)] + [InlineData("decimal", 16)] + [InlineData("nint", 8)] + [InlineData("nuint", 8)] + [InlineData("string", 8)] + [InlineData("object", 8)] + [InlineData("int[]", 8)] + [InlineData("int*", 8)] + [InlineData("delegate*", 8)] + [InlineData("int?", 8)] + [InlineData("ByteEnum", 1)] + [InlineData("LongEnum", 8)] + [InlineData("System.Collections.Generic.List", 8)] + public Task FieldType_AddsItsSizeToTheReportedTotal(string fieldType, int fieldSize) + { + var code = $$""" + enum ByteEnum : byte { A } + enum LongEnum : long { A } + + unsafe struct S + { + public long A; + public long B; + public long C; + public {{fieldType}} D; + } + + unsafe class C + { + void M({|#0:S value|}) + { + } + } + """; + + return AnalyzerTestRunner.VerifyAsync( + code, + Expected("S", 24 + fieldSize), + UnsafeOptions); + } + + [Fact] + [Trait("Category", "CI")] + public Task LargeFixedBuffer_Fires() + { + return AnalyzerTestRunner.VerifyAsync( + """ + unsafe struct Large + { + public fixed long Buffer[4]; + } + + unsafe class C + { + void M({|E128217:Large value|}) + { + } + } + """, + options: UnsafeOptions); + } + + [Fact] + [Trait("Category", "CI")] + public Task TypeParameterFields_CountAsPointers() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Quad + { + public T A; + public T B; + public T C; + public T D; + } + + class C + { + void M({|E128217:Quad value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NestedStructFields_AreMeasuredRecursively() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Inner + { + public long A; + public long B; + } + + struct Outer + { + public Inner First; + public Inner Second; + } + + class C + { + void M({|E128217:Outer value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task InlineArrayStruct_IsMeasuredByElementCount() + { + const string code = """ + using System.Runtime.CompilerServices; + + [System.Obsolete] + [InlineArray(4)] + struct Buffer + { + private static int count; + private long element; + } + + class C + { + void M({|#0:Buffer value|}) + { + } + } + """; + + return AnalyzerTestRunner.VerifyAsync( + code, + Expected("Buffer", 32), + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task StructWithAnUnrelatedAttribute_StillFires() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + [Serializable] + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Big value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task SequentialLayoutStruct_Fires() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Runtime.InteropServices; + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + struct Packed + { + public long A; + public long B; + public long C; + public long D; + } + + [StructLayout(LayoutKind.Sequential)] + struct Plain + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Packed first|}, {|E128217:Plain second|}) + { + } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task LookAlikeStructLayoutAttribute_DoesNotMarkTheStructExplicit() + { + return AnalyzerTestRunner.VerifyAsync( + """ + namespace Other + { + [System.AttributeUsage(System.AttributeTargets.Struct)] + public sealed class StructLayoutAttribute : System.Attribute + { + public StructLayoutAttribute(int kind) + { + } + } + } + + [Other.StructLayout(2)] + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Big value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ShortStructLayoutArgument_IsNotTreatedAsExplicit() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Runtime.InteropServices; + + [StructLayout((short)2)] + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M({|E128217:Big value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task OutParameter_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M(out Big value) + { + value = default; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ExtensionThisParameter_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + static class Extensions + { + public static long Sum(this Big value) + { + return value.A; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ParamsArray_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M(params Big[] values) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ConstructorParameter_Fires() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + public C({|E128217:Big value|}) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task DelegateLambdaAndLocalFunctionParameters_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + delegate void Handler(Big value); + + class C + { + void M() + { + Action untyped = value => { }; + Action typed = (Big value) => { }; + void Local(Big value) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ImplicitInterfaceImplementation_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + struct Big + { + public long A; + public long B; + public long C; + public long D; + } + + interface IHandler + { + void Handle(Big value); + } + + class C : IHandler + { + public void Handle(Big value) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task StructsInVectorNamespaces_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + namespace System.Numerics + { + public struct Wide + { + public long A; + public long B; + public long C; + public long D; + } + } + + namespace System.Runtime.Intrinsics + { + public struct Wider + { + public long A; + public long B; + public long C; + public long D; + } + } + + class C + { + void M(System.Numerics.Wide first, System.Runtime.Intrinsics.Wider second) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task EnumAndRefStructParameters_Silent() + { + return AnalyzerTestRunner.VerifyAsync( + """ + enum Mode : long + { + A + } + + ref struct Cursor + { + public long A; + public long B; + public long C; + public long D; + } + + class C + { + void M(Mode mode, (long, long, long, long) tuple, System.DateTime moment) + { + } + + void N(Cursor cursor) + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task StructChainDeeperThanTheLimit_Fires() + { + const int Levels = 20; + var code = new StringBuilder(); + + for (var level = 0; level < Levels; level++) + { + var next = level < Levels - 1 ? "S" + (level + 1).ToString(CultureInfo.InvariantCulture) : "byte"; + _ = code.Append(CultureInfo.InvariantCulture, $"struct S{level} {{ public {next} Next; }}\n"); + } + + _ = code.Append("class C { void M({|E128217:S0 value|}) { } }\n"); + + return AnalyzerTestRunner.VerifyAsync(code.ToString()); + } +} diff --git a/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyBranchCoverageTests.cs new file mode 100644 index 00000000..39166ac4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LazyFieldThreadSafetyBranchCoverageTests.cs @@ -0,0 +1,119 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the field and constructor shapes the Lazy thread safety rule reads. +/// +public sealed class LazyFieldThreadSafetyBranchCoverageTests +{ + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Threading;\n" + source, + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheModeArgumentComesBeforeTheFactoryByName() + { + return VerifyAsync(""" + class C + { + private static readonly Lazy {|E128194:Value = new Lazy(mode: LazyThreadSafetyMode.None, valueFactory: () => 1)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForEachVariableOfAMultiFieldDeclaration() + { + return VerifyAsync(""" + class C + { + private static readonly Lazy Plain, {|E128194:Unsafe = new Lazy(() => 1, LazyThreadSafetyMode.None)|}, Safe = new Lazy(() => 2); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheThreadSafetyFlagIsNotAConstant() + { + return VerifyAsync(""" + class C + { + private static bool flag = true; + + private static readonly Lazy Value = new Lazy(() => 1, flag); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInitializerHasNoArgumentList() + { + return VerifyAsync(""" + class C + { + private static readonly Lazy Value = new Lazy { }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreatedTypeDerivesFromLazy() + { + return VerifyAsync(""" + class DerivedLazy : Lazy + { + public DerivedLazy(LazyThreadSafetyMode mode) + : base(() => 1, mode) + { + } + } + + class C + { + private static readonly Lazy Value = new DerivedLazy(LazyThreadSafetyMode.None); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFieldTypeIsNotLazy() + { + return VerifyAsync(""" + class C + { + private static readonly object Boxed = new Lazy(() => 1, LazyThreadSafetyMode.None); + private static readonly dynamic Late = new Lazy(() => 1, LazyThreadSafetyMode.None); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFieldHasNoInitializerOrACreationThatDoesNotBind() + { + return VerifyAsync( + """ + class C + { + private static Lazy Empty; + + private static readonly Lazy Broken = new Lazy(missing, LazyThreadSafetyMode.None); + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/LinearLookupInLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LinearLookupInLoopBranchCoverageTests.cs new file mode 100644 index 00000000..cfbaa510 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LinearLookupInLoopBranchCoverageTests.cs @@ -0,0 +1,307 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LinearLookupInLoopBranchCoverageTests +{ + private static DiagnosticResult Expected(int markupIndex, string method, string receiver) + { + return new DiagnosticResult("E128066", DiagnosticSeverity.Warning) + .WithLocation(markupIndex) + .WithArguments(method, receiver); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_ForWhereFollowedByCount_AndNamesTheReceiverExpression() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + var count = {|#0:lookup.Where(x => x == item).Count()|}; + } + } + } + """, + Expected(0, "Count", "lookup.Where(x => x == item)")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCountThatIsNotAWhereCountPattern() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + var plain = lookup.Count(); + var filtered = lookup.Count(x => x == item); + var selected = lookup.Select(x => x + item).Count(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_AndNamesTheReceiverByItsMemberOrItsExpression() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + private readonly List _lookup = new(); + + List GetLookup() => _lookup; + + void M(List items) + { + foreach (var item in items) + { + _ = {|#0:this._lookup.Contains(item)|}; + _ = {|#1:GetLookup().Contains(item)|}; + } + } + } + """, + Expected(0, "Contains", "_lookup"), + Expected(1, "Contains", "GetLookup()")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAMemberAccess() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + bool Contains(int value) => value > 0; + + void M(List items) + { + foreach (var item in items) + { + _ = Contains(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLambdaIsNotALinqArgument() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Collections.Generic; + class C + { + static void Run(Func test) + { + } + + void M(List lookup) + { + Func assigned = y => lookup.Contains(y); + Run(y => lookup.Contains(y)); + Action> action = Run; + action(y => lookup.Contains(y)); + new List().Sort((a, b) => lookup.Contains(a) ? 0 : 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenALambdaOnADelegateRunsInsideALoop() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Collections.Generic; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + Func check = () => {|E128066:lookup.Contains(item)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ConstantBoundForLoop_DependsOnWhichSideHoldsTheLiteral() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + bool Check(int i) => i > 0; + + void M(List lookup, int n) + { + for (var i = 0; 10 > i; i++) + { + _ = lookup.Contains(i); + } + + for (var i = 0; Check(i); i++) + { + _ = {|E128066:lookup.Contains(i)|}; + } + + for (var i = 0; i < n; i++) + { + _ = {|E128066:lookup.Contains(i)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAForeachSitsInsideAConstantBoundLoop() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(List items, List lookup) + { + for (var round = 0; round < 3; round++) + { + foreach (var item in items) + { + _ = {|E128066:lookup.Contains(item)|}; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMethodIsAFieldHoldingADelegate() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System; + using System.Collections.Generic; + class Holder + { + public Func Remove = _ => true; + } + + class C + { + void M(List items, Holder holder) + { + foreach (var item in items) + { + _ = holder.Remove(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenOverloadResolutionFailsButCandidatesExist() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + _ = {|E128066:lookup.Contains(item, item, item)|}; + } + } + } + """, + options: new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheQueryableIsAClass() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List ids, EnumerableQuery query) + { + foreach (var id in ids) + { + var found = query.Any(x => x == id); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForFrozenAndImmutableLookups() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Collections.Frozen; + using System.Collections.Generic; + using System.Collections.Immutable; + class C + { + void M( + List ids, + FrozenSet frozen, + ImmutableHashSet immutable, + IReadOnlySet readOnlySet) + { + foreach (var id in ids) + { + _ = frozen.Contains(id) || immutable.Contains(id) || readOnlySet.Contains(id); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..836264aa --- /dev/null +++ b/tests/E128.Analyzers.Tests/LinearLookupInLoopCodeFixBranchCoverageTests.cs @@ -0,0 +1,119 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LinearLookupInLoopCodeFixBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_HoistsTheSetAboveAWhileLoop() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + var i = 0; + while (i < items.Count) + { + if ({|E128066:lookup.Contains(items[i])|}) { } + i++; + } + } + } + """, + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + var i = 0; + var lookupSet = lookup.ToHashSet(); + while (i < items.Count) + { + if (lookupSet.Contains(items[i])) { } + i++; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_HoistsTheSetAboveTheLoopWhenALambdaDoesTheLookup() + { + return VerifyFixAsync( + """ + using System; + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + Func check = () => {|E128066:lookup.Contains(item)|}; + } + } + } + """, + """ + using System; + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + var lookupSet = lookup.ToHashSet(); + foreach (var item in items) + { + Func check = () => lookupSet.Contains(item); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForMethodsOtherThanContainsAndAny() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, List lookup) + { + foreach (var item in items) + { + _ = {|E128066:lookup.Remove(item)|}; + _ = {|E128066:lookup.Find(x => x == item)|}; + _ = {|E128066:lookup.Where(x => x == item).Count()|}; + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LoggerArgumentGuardBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LoggerArgumentGuardBranchCoverageTests.cs new file mode 100644 index 00000000..d1ff99f5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoggerArgumentGuardBranchCoverageTests.cs @@ -0,0 +1,384 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoggerArgumentGuardBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithLogging = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Logging.Abstractions", "10.0.13")]); + + private static AnalyzerTestOptions Options => new() { References = Net100WithLogging }; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code, options: Options); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("LogTrace")] + [InlineData("LogDebug")] + [InlineData("LogInformation")] + [InlineData("LogWarning")] + [InlineData("LogError")] + [InlineData("LogCritical")] + public Task Reports_ForEveryNamedLogLevel(string method) + { + return VerifyAsync($$""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + {|E128122:logger.{{method}}($"count {count}")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMethodIsNotALevelMethod() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + logger.Log(LogLevel.Information, $"count {count}"); + _ = logger.BeginScope($"count {count}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLevelMethodDoesNotComeFromLoggerExtensions() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + + static class OwnExtensions + { + public static void LogInformation(this ILogger logger, string message) + { + } + } + + class C + { + void M(ILogger logger, int count) + { + logger.LogInformation($"count {count}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInterpolatedMessageIsConstant() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger) + { + logger.LogInformation($"fixed text"); + logger.LogInformation("a" + "b"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenArgumentsAreNotMessageBuilders() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + logger.LogInformation("count {Count}", count > 3); + logger.LogInformation("count {Count}", count - 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAHelperMethodHoldsTheGuard() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + static bool ExpressionHelper(ILogger logger) => logger.IsEnabled(LogLevel.Information); + + static bool BlockHelper(ILogger logger) + { + return logger.IsEnabled(LogLevel.Warning); + } + + void M(ILogger logger, int count) + { + if (ExpressionHelper(logger)) + { + logger.LogInformation($"count {count}"); + } + + if (BlockHelper(logger)) + { + logger.LogWarning($"count {count}"); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAPropertyAccessorHoldsTheGuard() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + private readonly ILogger _logger; + + C(ILogger logger) + { + _logger = logger; + } + + private bool BlockEnabled + { + get + { + return _logger.IsEnabled(LogLevel.Information); + } + } + + private bool ArrowEnabled + { + get => _logger.IsEnabled(LogLevel.Warning); + } + + void M(int count) + { + if (BlockEnabled) + { + _logger.LogInformation($"count {count}"); + } + + if (ArrowEnabled) + { + _logger.LogWarning($"count {count}"); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAPropertyWithoutAccessorBodyIsTheCondition() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + private bool Enabled { get; set; } + + void M(ILogger logger, int count) + { + if (Enabled) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAFieldHoldsTheCondition() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + private bool _enabled; + + void M(ILogger logger, int count) + { + if (_enabled) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardIsNegatedInsideTheThenBranch() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + if (!logger.IsEnabled(LogLevel.Information)) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLevelIsNamedWithAStaticImport() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + using static Microsoft.Extensions.Logging.LogLevel; + class C + { + void M(ILogger logger, int count) + { + if (logger.IsEnabled(Information)) + { + logger.LogInformation($"count {count}"); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardLevelIsNotANamedLevel() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + static LogLevel Pick() => LogLevel.Information; + + void M(ILogger logger, ILogger other, LogLevel level, int count) + { + if (logger.IsEnabled(level)) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + + if (logger.IsEnabled(Pick())) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + + if (other.IsEnabled(LogLevel.Information)) + { + {|E128122:logger.LogInformation($"count {count}")|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAParenthesizedNegatedGuardReturnsEarly() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + if (!(logger.IsEnabled(LogLevel.Information))) return; + + logger.LogInformation($"count {count}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenEarlierStatementsAreNotAnEarlyReturnGuard() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, ILogger other, int count, bool flag) + { + if (flag) + { + return; + } + + if (!flag) + { + return; + } + + if (!logger.IsEnabled(LogLevel.Information)) + { + count++; + } + + if (!logger.IsEnabled(LogLevel.Information)) + { + count++; + return; + } + + if (!other.IsEnabled(LogLevel.Information)) + { + return; + } + + if (!logger.IsEnabled(LogLevel.Warning)) + { + return; + } + + {|E128122:logger.LogInformation($"count {count}")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCallIsInsideALambdaInAFieldInitializer() + { + return VerifyAsync(""" + using System; + using Microsoft.Extensions.Logging; + class C + { + private readonly ILogger _logger = null!; + + private Action Callback => count => {|E128122:_logger.LogInformation($"count {count}")|}; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/LoggerArgumentGuardCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LoggerArgumentGuardCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..f6fe3a9e --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoggerArgumentGuardCodeFixBranchCoverageTests.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoggerArgumentGuardCodeFixBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithLogging = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Logging.Abstractions", "10.0.13")]); + + [Theory] + [Trait("Category", "CI")] + [InlineData("Trace")] + [InlineData("Debug")] + [InlineData("Warning")] + [InlineData("Error")] + [InlineData("Critical")] + public Task Fix_GuardsWithTheLevelOfTheLogMethod(string level) + { + var source = $$""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + {|E128122:logger.Log{{level}}($"count {count}")|}; + } + } + """; + var fixedCode = $$""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, int count) + { + if (logger.IsEnabled(global::Microsoft.Extensions.Logging.LogLevel.{{level}})) + { + logger.Log{{level}}($"count {count}"); + } + } + } + """; + + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + references: Net100WithLogging); + } +} diff --git a/tests/E128.Analyzers.Tests/LoopContextBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LoopContextBranchCoverageTests.cs new file mode 100644 index 00000000..6f8093a7 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoopContextBranchCoverageTests.cs @@ -0,0 +1,362 @@ +using System; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoopContextBranchCoverageTests +{ + private const string Prelude = """ + #nullable enable + using System; + using System.Threading; + using System.Threading.Tasks; + + class Other + { + public static void Sleep(int ms) { } + public static Task Delay(int ms) { return Task.CompletedTask; } + } + + class C + { + int[] values = new int[4]; + int[] items = new int[4]; + (int, int)[] pairs = new (int, int)[4]; + string? name; + void Use(int value) { } + + """; + + private static (SyntaxNode Root, SemanticModel Model) Parse(string members) + { + var tree = CSharpSyntaxTree.ParseText( + Prelude + members + "\n}\n", + cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "LoopContextProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return (tree.GetRoot(TestContext.Current.CancellationToken), compilation.GetSemanticModel(tree)); + } + + private static T Find(SyntaxNode root, string text) + where T : SyntaxNode + { + return root.DescendantNodes().OfType().First(n => string.Equals(n.ToString(), text, StringComparison.Ordinal)); + } + + private static bool ContainsWait(string bodyStatements) + { + var (root, model) = Parse("void M() { while (true) { " + bodyStatements + " } }"); + var body = root.DescendantNodes().OfType().Single().Statement; + return LoopContext.ContainsWaitCall(body, model, TestContext.Current.CancellationToken); + } + + private static bool References(string members, string nodeText) + { + var (root, model) = Parse(members); + var node = Find(root, nodeText); + var body = LoopContext.FindEnclosingLoopBody(node); + Assert.NotNull(body); + return LoopContext.ReferencesLoopVariable(node, body, model, TestContext.Current.CancellationToken); + } + + [Fact] + [Trait("Category", "CI")] + public void ContainsWaitCall_IsTrueForTaskDelay() + { + Assert.True(ContainsWait("Task.Delay(10);")); + } + + [Fact] + [Trait("Category", "CI")] + public void ContainsWaitCall_IsTrueForThreadSleep() + { + Assert.True(ContainsWait("Thread.Sleep(10);")); + } + + [Fact] + [Trait("Category", "CI")] + public void ContainsWaitCall_IsFalseForSameNamedMethodsOnOtherTypes() + { + Assert.False(ContainsWait("Other.Sleep(10); Other.Delay(10);")); + } + + [Fact] + [Trait("Category", "CI")] + public void ContainsWaitCall_IsFalseForOtherMethodsOnTaskAndThread() + { + Assert.False(ContainsWait("Task.Yield(); Thread.Yield(); Use(1);")); + } + + [Fact] + [Trait("Category", "CI")] + public void ContainsWaitCall_SkipsCallsThatDoNotBind() + { + Assert.False(ContainsWait("Missing(1); this.Missing(2);")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueWhenTheNodeCallsAMethod() + { + Assert.True(References("void M() { while (true) { Use(values[Compute()]); } } int Compute() { return 1; }", "values[Compute()]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseWhenNothingVaries() + { + Assert.False(References("void M() { while (true) { Use(values[0]); } }", "values[0]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForTheForeachVariable() + { + Assert.True(References("void M() { foreach (var item in items) { Use(values[item]); } }", "values[item]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseWhenTheForeachVariableIsNotRead() + { + Assert.False(References("void M() { foreach (var item in items) { Use(values[0]); } }", "values[0]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForADeconstructedForeachVariable() + { + Assert.True(References("void M() { foreach (var (a, b) in pairs) { Use(values[a]); } }", "values[a]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseForAForeachDeconstructionThatIsNotRead() + { + Assert.False(References("void M() { foreach (var (a, b) in pairs) { Use(values[0]); } }", "values[0]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForTheForCounter() + { + Assert.True(References("void M() { for (var i = 0; i < 3; i++) { Use(values[i]); } }", "values[i]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseForAForLoopWithoutADeclaration() + { + Assert.False(References("void M() { for (; ; ) { Use(values[0]); } }", "values[0]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForALocalDeclaredInTheBody() + { + Assert.True(References("void M() { while (true) { var local = 1; Use(values[local]); } }", "values[local]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForAVariableAssignedInTheBody() + { + Assert.True(References("void M() { var j = 0; while (true) { j = 2; Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseWhenTheBodyAssignsAnElement() + { + Assert.False(References("void M() { while (true) { values[0] = 1; Use(values[1]); } }", "values[1]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForAPrefixIncrementInTheBody() + { + Assert.True(References("void M() { var j = 0; while (true) { ++j; Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForAPrefixDecrementInTheBody() + { + Assert.True(References("void M() { var j = 0; while (true) { --j; Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForAPostfixIncrementInTheBody() + { + Assert.True(References("void M() { var j = 0; while (true) { j++; Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsTrueForAPostfixDecrementInTheBody() + { + Assert.True(References("void M() { var j = 0; while (true) { j--; Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseForUnaryOperatorsThatDoNotWrite() + { + Assert.False(References("void M() { var j = 0; while (true) { Use(-j); Use(values[j]); } }", "values[j]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseForTheNullForgivingOperator() + { + Assert.False(References("void M() { while (true) { Use(name!.Length); Use(values[name.Length]); } }", "values[name.Length]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_IsFalseForIncrementsOfMembers() + { + Assert.False(References("void M() { while (true) { values[0]++; ++values[1]; Use(values[2]); } }", "values[2]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_SkipsAssignmentsToUnknownNames() + { + Assert.False(References("void M() { while (true) { unknown = 1; Use(values[0]); } }", "values[0]")); + } + + [Fact] + [Trait("Category", "CI")] + public void ReferencesLoopVariable_SkipsUnknownNamesInTheNode() + { + Assert.False(References("void M() { foreach (var item in items) { Use(values[missing]); } }", "values[missing]")); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (var i = 0; i < 10; i++) { Use(1); }", true)] + [InlineData("for (var i = 0; i <= 10; i++) { Use(1); }", true)] + [InlineData("for (var i = 10; 10 >= i; i--) { Use(1); }", true)] + [InlineData("for (var i = 0; i < items.Length; i++) { Use(1); }", false)] + [InlineData("for (var i = 0; i != 10; i++) { Use(1); }", false)] + [InlineData("for (var i = 0; i < 10 && i < 20; i++) { Use(1); }", false)] + [InlineData("for (; ; ) { Use(1); }", false)] + [InlineData("while (true) { Use(1); }", false)] + [InlineData("foreach (var item in items) { Use(1); }", false)] + [InlineData("for (var i = 0; i < 10; i++) { Action a = () => Use(1); }", false)] + public void HasConstantBound_ReadsTheNearestForCondition(string statement, bool expected) + { + var (root, _) = Parse("void M() { " + statement + " }"); + var node = Find(root, "Use(1)"); + Assert.Equal(expected, LoopContext.HasConstantBound(node)); + } + + [Fact] + [Trait("Category", "CI")] + public void FindEnclosingLoop_ReturnsTheLoopStatementForABodyNode() + { + var (root, _) = Parse("void M() { while (true) { Use(1); } }"); + var loop = LoopContext.FindEnclosingLoop(Find(root, "Use(1)")); + _ = Assert.IsType(loop); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (var i = Use(1); i < 3; i++) { }")] + [InlineData("for (var i = 0; i < Use(1); i++) { }")] + [InlineData("for (var i = 0; i < 3; i += Use(1)) { }")] + [InlineData("foreach (var item in Make(Use(1))) { }")] + [InlineData("while (Use(1) > 0) { }")] + [InlineData("do { } while (Use(1) > 0);")] + public void FindEnclosingLoopBody_IsNullForHeaderNodes(string statement) + { + var (root, _) = Parse("void M() { " + statement + " } int Use(int v) { return v; } int[] Make(int v) { return items; }"); + Assert.Null(LoopContext.FindEnclosingLoopBody(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void FindEnclosingLoopBody_FallsBackToTheOuterLoopForAHeaderNode() + { + var (root, _) = Parse( + "void M() { while (true) { for (var i = Use(1); i < 3; i++) { } } } int Use(int v) { return v; }"); + var body = LoopContext.FindEnclosingLoopBody(Find(root, "Use(1)")); + var outer = root.DescendantNodes().OfType().Single(); + Assert.Same(outer.Statement, body); + } + + [Fact] + [Trait("Category", "CI")] + public void FindEnclosingLoopBody_IsNullInsideALambda() + { + var (root, _) = Parse("void M() { while (true) { Action a = () => Use(1); } }"); + Assert.Null(LoopContext.FindEnclosingLoopBody(Find(root, "Use(1)"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (var i = 0; i < Use(1); i++) { }", true)] + [InlineData("for (var i = 0; i < 3; i += Use(1)) { }", true)] + [InlineData("while (Use(1) > 0) { }", true)] + [InlineData("do { } while (Use(1) > 0);", true)] + [InlineData("for (var i = Use(1); i < 3; i++) { }", false)] + [InlineData("foreach (var item in Make(Use(1))) { }", false)] + [InlineData("while (true) { Use(1); }", true)] + [InlineData("Use(1);", false)] + public void IsInsideLoopBody_CountsConditionsAndIncrementors(string statement, bool expected) + { + var (root, _) = Parse("void M() { " + statement + " } int Use(int v) { return v; } int[] Make(int v) { return items; }"); + Assert.Equal(expected, LoopContext.IsInsideLoopBody(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsInsideLoopBody_IsTrueInsideALambdaInTheLoop() + { + var (root, _) = Parse("void M() { while (true) { Action a = () => Use(1); } }"); + Assert.True(LoopContext.IsInsideLoopBody(Find(root, "Use(1)"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("for (var i = Use(1); i < 3; i++) { }", true)] + [InlineData("foreach (var item in Make(Use(1))) { }", true)] + [InlineData("while (true) { Use(1); }", true)] + [InlineData("Use(1);", false)] + public void IsWithinAnyLoop_IncludesLoopHeaders(string statement, bool expected) + { + var (root, _) = Parse("void M() { " + statement + " } int Use(int v) { return v; } int[] Make(int v) { return items; }"); + Assert.Equal(expected, LoopContext.IsWithinAnyLoop(Find(root, "Use(1)"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("public C() { Use(1); }")] + [InlineData("~C() { Use(1); }")] + [InlineData("public static C operator +(C a, C b) { Use(1); return a; }")] + [InlineData("public static implicit operator int(C a) { Use(1); return 0; }")] + [InlineData("int P { get { Use(1); return 0; } }")] + [InlineData("void M() { Use(1); }")] + [InlineData("void M() { while (true) { void Local() { Use(1); } } }")] + public void IsWithinAnyLoop_StopsAtDeclarationBoundaries(string members) + { + var (root, _) = Parse(members + " "); + Assert.False(LoopContext.IsWithinAnyLoop(Find(root, "Use(1)"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsWithinAnyLoop_SeesALoopAroundALambda() + { + var (root, _) = Parse("void M() { while (true) { Action a = () => Use(1); } }"); + Assert.True(LoopContext.IsWithinAnyLoop(Find(root, "Use(1)"))); + } +} diff --git a/tests/E128.Analyzers.Tests/LoopCountBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LoopCountBranchCoverageTests.cs new file mode 100644 index 00000000..f3c43c11 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LoopCountBranchCoverageTests.cs @@ -0,0 +1,236 @@ +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LoopCountBranchCoverageTests +{ + private const string Prelude = """ + using System; + using System.Collections.Generic; + + class WithStaticCount + { + public static int Count => 1; + public IEnumerator GetEnumerator() { return null!; } + } + + class WithLongCount + { + public long Count => 1; + public IEnumerator GetEnumerator() { return null!; } + } + + class WithPrivateCount + { + int Count => 1; + public IEnumerator GetEnumerator() { return null!; } + } + + class WithInternalCount + { + internal int Count => 1; + public IEnumerator GetEnumerator() { return null!; } + } + + class WithLength + { + public int Length => 1; + public IEnumerator GetEnumerator() { return null!; } + } + + class Derived : WithLength + { + } + + class C + { + int[] array = new int[2]; + List list = new List(); + string text = ""; + IEnumerable sequence = new int[2]; + ICollection collection = new List(); + WithStaticCount staticCount = new WithStaticCount(); + WithLongCount longCount = new WithLongCount(); + WithPrivateCount privateCount = new WithPrivateCount(); + WithInternalCount internalCount = new WithInternalCount(); + Derived derived = new Derived(); + C next = null!; + List Make() { return list; } + void Use(int value) { } + + """; + + private static (SyntaxNode Root, SemanticModel Model) Parse(string members) + { + var tree = CSharpSyntaxTree.ParseText( + Prelude + members + "\n}\n", + cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "LoopCountProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return (tree.GetRoot(TestContext.Current.CancellationToken), compilation.GetSemanticModel(tree)); + } + + private static string? CountOf(string loop) + { + var (root, model) = Parse("void M(int n) { " + loop + " }"); + var statement = root.DescendantNodes().OfType() + .First(static s => s is ForStatementSyntax or CommonForEachStatementSyntax or WhileStatementSyntax); + return LoopCount.TryGetCount(statement, model, TestContext.Current.CancellationToken); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("foreach (var x in array) { }", "array.Length")] + [InlineData("foreach (var x in list) { }", "list.Count")] + [InlineData("foreach (var x in text) { }", "text.Length")] + [InlineData("foreach (var x in collection) { }", "collection.Count")] + [InlineData("foreach (var x in derived) { }", "derived.Length")] + [InlineData("foreach (var x in next.list) { }", "next.list.Count")] + [InlineData("foreach (var x in internalCount) { }", "internalCount.Count")] + [InlineData("foreach (var (a, b) in new (int, int)[0]) { }", null)] + [InlineData("foreach (var x in sequence) { }", null)] + [InlineData("foreach (var x in Make()) { }", null)] + [InlineData("foreach (var x in staticCount) { }", null)] + [InlineData("foreach (var x in longCount) { }", null)] + [InlineData("foreach (var x in privateCount) { }", null)] + [InlineData("foreach (var x in missing) { }", null)] + [InlineData("for (var i = 0; i < list.Count; i++) { }", "list.Count")] + [InlineData("for (var i = 0; i < array.Length; i++) { }", "array.Length")] + [InlineData("for (var i = 0; i < next.list.Count; i++) { }", "next.list.Count")] + [InlineData("for (var i = 0; i < n; i++) { }", null)] + [InlineData("for (var i = 0; i < Make().Count; i++) { }", null)] + [InlineData("for (var i = 0; i < list.Capacity; i++) { }", null)] + [InlineData("for (var i = 0; i <= list.Count; i++) { }", null)] + [InlineData("for (; ; ) { }", null)] + [InlineData("while (true) { }", null)] + public void TryGetCount_ReadsTheLoopSource(string loop, string? expected) + { + Assert.Equal(expected, CountOf(loop)); + } + + private static (StatementSyntax? Result, StatementSyntax? Next) FillLoop(string statements, string methodName = "Add") + { + var (root, model) = Parse("void M() { " + statements + " }"); + var declaration = root.DescendantNodes().OfType().First(); + var receiver = model.GetDeclaredSymbol(declaration.Declaration.Variables[0], TestContext.Current.CancellationToken)!; + var result = LoopCount.TryGetNextFillLoop( + declaration, + receiver, + [methodName, "Insert"], + model, + TestContext.Current.CancellationToken); + var block = (BlockSyntax)declaration.Parent!; + var index = block.Statements.IndexOf(declaration); + return (result, index + 1 < block.Statements.Count ? block.Statements[index + 1] : null); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_ReturnsTheLoopThatCallsTheMethod() + { + var (result, next) = FillLoop("var target = new List(); for (var i = 0; i < 3; i++) { target.Add(i); }"); + Assert.Same(next, result); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_AcceptsAnyListedMethodName() + { + var (result, next) = FillLoop("var target = new List(); foreach (var i in list) { target.Insert(0, i); }"); + Assert.Same(next, result); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_IsNullWhenTheLoopMayStopEarly() + { + var (result, _) = FillLoop("var target = new List(); foreach (var i in list) { target.Add(i); break; }"); + Assert.Null(result); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_IsNullWhenTheLoopCallsAnotherMethod() + { + var (result, _) = FillLoop("var target = new List(); foreach (var i in list) { target.Clear(); }"); + Assert.Null(result); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_IsNullForTheLastStatementInTheBlock() + { + var (result, next) = FillLoop("var target = new List();"); + Assert.Null(next); + Assert.Null(result); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_IsNullWhenTheDeclarationIsNotInABlock() + { + var (root, model) = Parse("void M(int k) { switch (k) { case 1: var target = new List(); foreach (var i in list) { target.Add(i); } break; } }"); + var declaration = root.DescendantNodes().OfType().First(); + var receiver = model.GetDeclaredSymbol(declaration.Declaration.Variables[0], TestContext.Current.CancellationToken)!; + + var result = LoopCount.TryGetNextFillLoop(declaration, receiver, ["Add"], model, TestContext.Current.CancellationToken); + + Assert.Null(result); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("target.Add(1);", true)] + [InlineData("other.Add(1);", false)] + [InlineData("this.list.Add(1);", false)] + [InlineData("target.Clear();", false)] + [InlineData("Action a = () => target.Add(1);", false)] + [InlineData("void Local() { target.Add(1); }", false)] + [InlineData("Use(target.Count);", false)] + [InlineData("Make().Add(1);", false)] + [InlineData("missing.Add(1);", false)] + public void ContainsCall_FindsOnlyDirectCallsOnTheReceiver(string body, bool expected) + { + var (root, model) = Parse("void M() { var target = new List(); var other = new List(); while (true) { " + body + " } }"); + var declaration = root.DescendantNodes().OfType().First(); + var receiver = model.GetDeclaredSymbol(declaration.Declaration.Variables[0], TestContext.Current.CancellationToken)!; + var loop = root.DescendantNodes().OfType().Single(); + + Assert.Equal(expected, LoopCount.ContainsCall(loop, receiver, "Add", model, TestContext.Current.CancellationToken)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("while (true) { break; }", true)] + [InlineData("while (true) { if (n > 0) { break; } }", true)] + [InlineData("while (true) { for (;;) { break; } }", false)] + [InlineData("while (true) { foreach (var x in list) { break; } }", false)] + [InlineData("while (true) { while (n > 0) { break; } }", false)] + [InlineData("while (true) { do { break; } while (n > 0); }", false)] + [InlineData("while (true) { switch (n) { case 1: break; } }", false)] + [InlineData("while (true) { switch (n) { case 1: break; } break; }", true)] + [InlineData("while (true) { Use(n); }", false)] + public void HasDirectBreak_IgnoresBreaksOfNestedConstructs(string loop, bool expected) + { + var (root, _) = Parse("void M(int n) { " + loop + " }"); + var statement = root.DescendantNodes().OfType().First(); + Assert.Equal(expected, LoopCount.HasDirectBreak(statement)); + } + + [Fact] + [Trait("Category", "CI")] + public void TryGetNextFillLoop_HandlesAnEmptyMethodNameList() + { + var (root, model) = Parse("void M() { var target = new List(); foreach (var i in list) { target.Add(i); } }"); + var declaration = root.DescendantNodes().OfType().First(); + var receiver = model.GetDeclaredSymbol(declaration.Declaration.Variables[0], TestContext.Current.CancellationToken)!; + + Assert.Null(LoopCount.TryGetNextFillLoop(declaration, receiver, [], model, TestContext.Current.CancellationToken)); + } +} diff --git a/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..ad12aa7d --- /dev/null +++ b/tests/E128.Analyzers.Tests/LowValueTestAnalyzerBranchCoverageTests.cs @@ -0,0 +1,128 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LowValueTestAnalyzerBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("xunit.v3.core", "3.2.2"), + new PackageIdentity("xunit.v3.assert", "3.2.2") + ]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { References = Net100WithXunit }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAMethodThatIsNotATest() + { + return VerifyAsync(""" + using Xunit; + + public sealed class Subject + { + public void Helper() + { + var left = 1; + var right = 2; + Assert.Equal(3, left + right); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TwoExpressionBodiedTestsThatShareTheSameCall() + { + return VerifyAsync(""" + using Xunit; + + public static class Calculator + { + public static int Add(int left, int right) => left + right; + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_ProducePositiveValue|}() => Assert.NotEqual(0, Calculator.Add(1, 2)); + + [Fact] + public void {|E128107:Should_ProduceNonZeroValue|}() => Assert.NotEqual(0, Calculator.Add(1, 2)); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTestsThatShareOnlyAnInterfaceCall() + { + return VerifyAsync(""" + using Xunit; + + public interface IReader + { + int Read(int value); + } + + public sealed class Reader : IReader + { + public int Read(int value) => value; + } + + public sealed class Subject + { + [Fact] + public void Should_ReadTheFirstValue() + { + IReader reader = new Reader(); + var value = reader.Read(1); + Assert.NotEqual(0, value); + } + + [Fact] + public void Should_ReadTheSameValueAgain() + { + IReader reader = new Reader(); + var value = reader.Read(1); + Assert.NotEqual(0, value); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAShortTestThatReadsAProductionProperty() + { + return VerifyAsync(""" + using Xunit; + + public static class Pool + { + public static int Shared => 3; + } + + public sealed class Subject + { + [Fact] + public void Should_ExposeTheSharedValue() + { + var left = 1; + var right = 2; + Assert.Equal(left + right, Pool.Shared); + } + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/LowValueTestCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/LowValueTestCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..e9887fa9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/LowValueTestCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,102 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class LowValueTestCodeFixProviderBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([ + new PackageIdentity("xunit.v3.core", "3.2.2"), + new PackageIdentity("xunit.v3.assert", "3.2.2") + ]); + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + references: Net100WithXunit, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck, + options: new CodeFixTestOptions { FixAllIterations = 1 }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RemovesTheOnlyMemberOfTheTestClass() + { + return VerifyFixAsync( + """ + using Xunit; + + public static class Calculator + { + public static int Echo(int value) => value; + } + + public sealed class Subject + { + [Fact] + public void {|E128107:Should_SumTwoValues|}() + { + Assert.Equal(1, Calculator.Echo(1)); + } + } + """, + """ + using Xunit; + + public static class Calculator + { + public static int Echo(int value) => value; + } + + public sealed class Subject + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsACommentOnTheClosingBrace() + { + return VerifyFixAsync( + """ + using Xunit; + + public static class Calculator + { + public static int Echo(int value) => value; + } + + public sealed class Subject + { + public static int Zero() => 0; + + [Fact] + public void {|E128107:Should_SumTwoValues|}() + { + Assert.Equal(1, Calculator.Echo(1)); + } + // End of the subject. + } + """, + """ + using Xunit; + + public static class Calculator + { + public static int Echo(int value) => value; + } + + public sealed class Subject + { + public static int Zero() => 0; + // End of the subject. + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ManualBitCountBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ManualBitCountBranchCoverageTests.cs new file mode 100644 index 00000000..b50078fd --- /dev/null +++ b/tests/E128.Analyzers.Tests/ManualBitCountBranchCoverageTests.cs @@ -0,0 +1,190 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ManualBitCountBranchCoverageTests +{ + private static Task VerifyAsync( + string valueType, + string countType, + string condition, + string first, + string second, + bool reports) + { + var loop = $$""" + while ({{condition}}) + { + {{first}} + {{second}} + } + """; + var marked = reports ? "{|E128134:" + loop.TrimStart() + "|}" : loop.TrimStart(); + var code = $$""" + class C + { + int Count({{valueType}} value, {{valueType}} other, int shift) + { + {{countType}} count = 0; + {{marked}} + return (int)count; + } + } + """; + + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("int", "int")] + [InlineData("uint", "long")] + [InlineData("long", "long")] + [InlineData("int", "long")] + public Task Reports_ForSupportedValueAndCountTypes(string valueType, string countType) + { + return VerifyAsync(valueType, countType, "value != 0", "count += value & 1;", "value >>= 1;", true); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("short", "int")] + [InlineData("byte", "int")] + [InlineData("int", "double")] + public Task Silent_ForUnsupportedValueOrCountTypes(string valueType, string countType) + { + return VerifyAsync(valueType, countType, "value != 0", "count += value & 1;", "value >>= 1;", false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheZeroIsOnTheLeft() + { + return VerifyAsync("int", "int", "0 != value", "count += value & 1;", "value >>= 1;", true); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("value != 1")] + [InlineData("value != 0L")] + [InlineData("value != other")] + [InlineData("1 != value")] + [InlineData("0 != 0")] + [InlineData("value > 0")] + public Task Silent_WhenTheConditionIsNotAComparisonWithZero(string condition) + { + return VerifyAsync("int", "int", condition, "count += value & 1;", "value >>= 1;", false); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("count = value & 1;")] + [InlineData("count += value & 2;")] + [InlineData("count += other & 1;")] + [InlineData("count += (value & 1);")] + [InlineData("count += value | 1;")] + [InlineData("count += value;")] + [InlineData("count -= value & 1;")] + [InlineData("if (value > 1) { count++; }")] + public Task Silent_WhenTheFirstStatementIsNotTheLowBitAddition(string first) + { + return VerifyAsync("int", "int", "value != 0", first, "value >>= 1;", false); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("value >>= 2;")] + [InlineData("value >>= shift;")] + [InlineData("value <<= 1;")] + [InlineData("other >>= 1;")] + [InlineData("value = value >> 1;")] + [InlineData("value++;")] + public Task Silent_WhenTheSecondStatementIsNotAShiftByOne(string second) + { + return VerifyAsync("int", "int", "value != 0", "count += value & 1;", second, false); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueAndCountAreNotLocalsOrParameters() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + private int _value; + + private int _count; + + int FromField(int seed) + { + int count = 0; + while (_value != 0) + { + count += _value & 1; + _value >>= 1; + } + + return count + seed; + } + + int CountField(int value) + { + while (value != 0) + { + _count += value & 1; + value >>= 1; + } + + return value; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopIsAnEmbeddedStatement() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Count(int value, bool flag) + { + int count = 0; + if (flag) + while (value != 0) + { + count += value & 1; + value >>= 1; + } + + return count; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopBodyIsNotABlock() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + int Count(int value) + { + int count = 0; + while (value != 0) + count += value & 1; + + return count; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..4bc522b2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MissingTraitCategoryAnalyzerBranchCoverageTests.cs @@ -0,0 +1,129 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MissingTraitCategoryAnalyzerBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithXunit = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("xunit.v3.core", "3.2.2")]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { References = Net100WithXunit }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTraitNameIsNotCategory() + { + return VerifyAsync(""" + using Xunit; + public sealed class MyTests + { + [{|E128073:Fact|}] + [Trait("Priority", "High")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTraitNameHasDifferentCase() + { + return VerifyAsync(""" + using Xunit; + public sealed class MyTests + { + [{|E128073:Fact|}] + [Trait("category", "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnAttributeNamedTraitIsNotTheXunitTrait() + { + return VerifyAsync(""" + using System; + using Xunit; + + namespace Other + { + sealed class TraitAttribute : Attribute + { + public TraitAttribute(string name, string value) { } + } + } + + public sealed class MyTests + { + [{|E128073:Fact|}] + [Other.Trait("Category", "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAConstantNamesTheCategory() + { + return VerifyAsync(""" + using Xunit; + public sealed class MyTests + { + private const string Key = "Category"; + + [Fact] + [Trait(Key, "CI")] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheClassHasSeveralAttributesIncludingTheCategory() + { + return VerifyAsync(""" + using System; + using Xunit; + + [Obsolete] + [Trait("Priority", "High")] + [TraitAttribute("Category", "CI")] + public sealed class MyTests + { + [Fact] + public void Works() { } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAUserDefinedFactAttribute() + { + return VerifyAsync(""" + using System; + namespace Other + { + sealed class FactAttribute : Attribute { } + } + + public sealed class MyTests + { + [Other.Fact] + public void Works() { } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MonthTimeSpanBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/MonthTimeSpanBranchCoverageTests.cs new file mode 100644 index 00000000..3ecc4f55 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MonthTimeSpanBranchCoverageTests.cs @@ -0,0 +1,188 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers operand order, constant types, and call shapes of the month span rule. +/// +public sealed class MonthTimeSpanBranchCoverageTests +{ + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheSpanIsTheLeftOperandOfAnAddition() + { + return VerifyAsync( + """ + using System; + class C + { + static DateTime M(DateTime date, DateTimeOffset offset) + { + var first = {|E128197:TimeSpan.FromDays(30)|} + date; + var second = {|E128197:TimeSpan.FromDays(31)|} + offset; + return first; + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNeitherOperandIsADate() + { + return VerifyAsync(""" + using System; + class C + { + static TimeSpan M(TimeSpan span) + { + span += TimeSpan.FromDays(30); + return TimeSpan.FromDays(30) + TimeSpan.FromDays(30); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenASubtractionHasTheSpanOnTheLeft() + { + return VerifyAsync( + """ + using System; + class C + { + static object M(DateTime date) + { + return TimeSpan.FromDays(30) - date; + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("27")] + [InlineData("32")] + [InlineData("27L")] + [InlineData("32L")] + [InlineData("27f")] + [InlineData("32f")] + [InlineData("27.0")] + [InlineData("32.0")] + [InlineData("30.5")] + public Task Silent_WhenTheDayCountIsOutsideTheMonthRange(string days) + { + return VerifyAsync($$""" + using System; + class C + { + static DateTime M(DateTime date) + { + return date.Add(TimeSpan.FromDays({{days}})); + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("28")] + [InlineData("31")] + [InlineData("28L")] + [InlineData("31L")] + [InlineData("28f")] + [InlineData("31f")] + [InlineData("28.0")] + [InlineData("31.0")] + public Task Reports_WhenTheDayCountIsAtAnEdgeOfTheMonthRange(string days) + { + return VerifyAsync($$""" + using System; + class C + { + static DateTime M(DateTime date) + { + return date.Add({|E128197:TimeSpan.FromDays({{days}})|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFromDaysHasMoreThanOneArgument() + { + return VerifyAsync(""" + using System; + class C + { + static DateTime M(DateTime date) + { + return date.Add(TimeSpan.FromDays(30, 1)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSpanComesFromAnotherFactory() + { + return VerifyAsync(""" + using System; + class C + { + static DateTime M(DateTime date) + { + return date.Add(TimeSpan.FromHours(720)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFromDaysIsCalledThroughAUsingStatic() + { + return VerifyAsync(""" + using System; + using static System.TimeSpan; + class C + { + static DateTime M(DateTime date) + { + return date.Add(FromDays(30)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFromDaysDoesNotBind() + { + return VerifyAsync( + """ + using System; + class C + { + static DateTime M(DateTime date) + { + return date.Add(TimeSpan.FromDays(missing)); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..dcd30257 --- /dev/null +++ b/tests/E128.Analyzers.Tests/MutableCollectionExposureAnalyzerBranchCoverageTests.cs @@ -0,0 +1,107 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MutableCollectionExposureAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInterfaceImplementationThatMustReturnTheMutableType() + { + return VerifyAsync(""" + using System.Collections.Generic; + + interface ISource + { + List Items(); + } + + class Source : ISource + { + public List Items() => new(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNonGenericAndUnmappedGenericTypes() + { + return VerifyAsync(""" + using System.Collections.Generic; + + class Source + { + public int Value() => 1; + public int Count => 1; + public string Name => "x"; + public IEnumerable Items() => new int[0]; + public IEnumerable Values => new int[0]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAccessorsAndOverridesThatAreNotApiCandidates() + { + return VerifyAsync(""" + using System.Collections.Generic; + + abstract class Base + { + public abstract List Items(); + public abstract List Values { get; set; } + } + + class Source : Base + { + public override List Items() => new(); + public override List Values { get; set; } = new(); + private List PrivateItems() => new(); + protected List ProtectedItems() => new(); + private List PrivateValues => new(); + protected List ProtectedValues => new(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForInternalMembersAndInitOnlyProperties() + { + return VerifyAsync(""" + using System.Collections.Generic; + + class Source + { + internal List {|E128052:Items|}() => new(); + internal Dictionary {|E128052:Counts|} { get; init; } = new(); + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Builder")] + [InlineData("State")] + [InlineData("Stats")] + [InlineData("Accumulator")] + [InlineData("Options")] + public Task Silent_ForTypesWhoseNamesDescribeMutableState(string suffix) + { + return VerifyAsync(""" + using System.Collections.Generic; + class Some + """ + suffix + """ + { public List Items() => new(); public List Values { get; } = new(); } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..620822ef --- /dev/null +++ b/tests/E128.Analyzers.Tests/MutableStaticReadonlyArrayCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,126 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class MutableStaticReadonlyArrayCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ConvertsAnImplicitByteArrayOfByteCasts() + { + return VerifyFixAsync( + """ + class C + { + private static readonly {|E128061:byte[] Magic = new[] { (byte)1, (byte)2 }|}; + } + """, + """ + using System; + + class C + { + private static ReadOnlySpan Magic => [(byte)1, (byte)2]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AcceptsNamedByteConstants() + { + return VerifyFixAsync( + """ + class C + { + private const byte Tag = 7; + private static readonly {|E128061:byte[] Header = [Tag, 255]|}; + } + """, + """ + using System; + + class C + { + private const byte Tag = 7; + private static ReadOnlySpan Header => [Tag, 255]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_FallsBackToImmutableArrayForASpreadElement() + { + return VerifyFixAsync( + """ + class C + { + private static readonly System.Collections.Generic.List Prefix = new(); + private static readonly {|E128061:byte[] Full = [.. Prefix, 2]|}; + } + """, + """ + using System.Collections.Immutable; + + class C + { + private static readonly System.Collections.Generic.List Prefix = new(); + private static readonly ImmutableArray Full = [.. Prefix, 2]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_FallsBackToImmutableArrayForAConstantsFollowedByACall() + { + return VerifyFixAsync( + """ + class C + { + private static readonly {|E128061:byte[] Values = [1, 2, ReadOne()]|}; + + private static byte ReadOne() => 1; + } + """, + """ + using System.Collections.Immutable; + + class C + { + private static readonly ImmutableArray Values = [1, 2, ReadOne()]; + + private static byte ReadOne() => 1; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ConvertsAnImplicitArrayOfStrings() + { + return VerifyFixAsync( + """ + class C + { + private static readonly {|E128061:string[] Names = new[] { "a", "b" }|}; + } + """, + """ + using System.Collections.Immutable; + + class C + { + private static readonly ImmutableArray Names = ["a", "b"]; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/NamespacesBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/NamespacesBranchCoverageTests.cs new file mode 100644 index 00000000..eb9c7181 --- /dev/null +++ b/tests/E128.Analyzers.Tests/NamespacesBranchCoverageTests.cs @@ -0,0 +1,44 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class NamespacesBranchCoverageTests +{ + private static INamespaceSymbol Namespace(string dotted) + { + var tree = CSharpSyntaxTree.ParseText( + "namespace " + dotted + " { class Probe { } }", + cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "NamespaceProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return compilation.GetTypeByMetadataName(dotted + ".Probe")!.ContainingNamespace; + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("System.Net.Http", "System.Net.Http", true)] + [InlineData("System", "System", true)] + [InlineData("System.Net", "System", false)] + [InlineData("System.Net", "Net", false)] + [InlineData("System.Net", "A.System.Net", false)] + [InlineData("System.Net", "System.Net.Http", false)] + [InlineData("System.Net", ".Net", false)] + [InlineData("System.Net", "System.Nex", false)] + [InlineData("System.Net", "Systen.Net", false)] + [InlineData("System.Net", "", false)] + public void Equals_ComparesTheWholeChain(string actual, string dotted, bool expected) + { + Assert.Equal(expected, Namespaces.Equals(Namespace(actual), dotted)); + } + + [Fact] + [Trait("Category", "CI")] + public void Equals_IsFalseForANullNamespace() + { + Assert.False(Namespaces.Equals(null, "System")); + } +} diff --git a/tests/E128.Analyzers.Tests/NamingStyleCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/NamingStyleCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..df887e81 --- /dev/null +++ b/tests/E128.Analyzers.Tests/NamingStyleCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using E128.Analyzers.Style; +using Microsoft.CodeAnalysis; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class NamingStyleCodeFixProviderBranchCoverageTests +{ + private static Diagnostic CreateDiagnostic(params (string Key, string? Value)[] properties) + { + var builder = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal); + foreach (var (key, value) in properties) + { + builder[key] = value; + } + + return Diagnostic.Create( + new DiagnosticDescriptor("IDE1006", "Test", "Test", "Style", DiagnosticSeverity.Warning, true), + Location.None, + builder.ToImmutable()); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("max_retry_count", "", "", "_", "CamelCase", "max_Retry_Count")] + [InlineData("max_retry_count", "", "", "_", "PascalCase", "Max_Retry_Count")] + [InlineData("max_retry_count", "", "", "_", "FirstUpper", "Max_retry_count")] + [InlineData("maxRetryCount", "", "", "", "FirstUpper", "MaxRetryCount")] + [InlineData("maxRetryCount", "", "", "", "AllUpper", "MAXRETRYCOUNT")] + [InlineData("MaxRetryCount", "", "", "_", "AllLower", "max_retry_count")] + [InlineData("MaxRetryCount", "", "", "", "AllLowerCase", "maxretrycount")] + [InlineData("MaxRetryCount", "", "", "-", "AllUpperCase", "MAX-RETRY-COUNT")] + [InlineData("max_retry", "", "", "_", "Unknown", "Max_Retry")] + public void BuildCompliantName_AppliesEachCapitalizationScheme( + string symbolName, + string prefix, + string suffix, + string separator, + string scheme, + string expected) + { + Assert.Equal(expected, NamingStyleCodeFixProvider.BuildCompliantName(symbolName, prefix, suffix, separator, scheme)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("fooAsync", "", "Async", "PascalCase", "FooAsync")] + [InlineData("foo", "", "Async", "PascalCase", "FooAsync")] + [InlineData("_", "_", "", "PascalCase", "_")] + [InlineData("_", "_", "", "CamelCase", "_")] + [InlineData("s_value", "_", "", "CamelCase", "_value")] + [InlineData("m_value", "_", "", "CamelCase", "_value")] + [InlineData("TValue", "", "", "PascalCase", "Value")] + [InlineData("_Value", "s_", "", "CamelCase", "s_value")] + public void BuildCompliantName_StripsAffixesBeforeRebuilding( + string symbolName, + string prefix, + string suffix, + string scheme, + string expected) + { + Assert.Equal(expected, NamingStyleCodeFixProvider.BuildCompliantName(symbolName, prefix, suffix, string.Empty, scheme)); + } + + [Fact] + [Trait("Category", "CI")] + public void SplitByCaseTransition_ReturnsNoWordsForAnEmptyName() + { + Assert.Empty(NamingStyleCodeFixProvider.SplitByCaseTransition(string.Empty)); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_ReturnsNullWithoutAnyName() + { + Assert.Null(NamingStyleCodeFixProvider.ComputeCompliantName(CreateDiagnostic(("Prefix", "_")))); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_ReturnsNullForAnEmptySymbolName() + { + Assert.Null(NamingStyleCodeFixProvider.ComputeCompliantName(CreateDiagnostic(("SymbolName", string.Empty)))); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_UsesPascalCaseWhenNoStyleIsGiven() + { + var diagnostic = CreateDiagnostic(("SymbolName", "myField")); + Assert.Equal("MyField", NamingStyleCodeFixProvider.ComputeCompliantName(diagnostic)); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_PrefersTheFallbackSymbolName() + { + var diagnostic = CreateDiagnostic(("SymbolName", "ignored"), ("Prefix", "_"), ("CapitalizationScheme", "CamelCase")); + Assert.Equal("_actual", NamingStyleCodeFixProvider.ComputeCompliantName(diagnostic, "Actual")); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_IgnoresAnEmptySuggestedName() + { + var diagnostic = CreateDiagnostic(("SuggestedName", string.Empty), ("SymbolName", "myField"), ("Suffix", "Value")); + Assert.Equal("MyFieldValue", NamingStyleCodeFixProvider.ComputeCompliantName(diagnostic)); + } + + [Fact] + [Trait("Category", "CI")] + public void ComputeCompliantName_ReadsEveryStyleProperty() + { + var properties = new List<(string Key, string? Value)> + { + ("SymbolName", "maxRetry"), + ("Prefix", "k_"), + ("Suffix", "_v"), + ("WordSeparator", "_"), + ("CapitalizationScheme", "AllUpperCase") + }; + + var diagnostic = CreateDiagnostic([.. properties]); + Assert.Equal("k_MAX_RETRY_v", NamingStyleCodeFixProvider.ComputeCompliantName(diagnostic)); + } +} diff --git a/tests/E128.Analyzers.Tests/NonPublicBclReflectionAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/NonPublicBclReflectionAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..c042d083 --- /dev/null +++ b/tests/E128.Analyzers.Tests/NonPublicBclReflectionAnalyzerBranchCoverageTests.cs @@ -0,0 +1,88 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class NonPublicBclReflectionAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "using System; using System.Reflection;\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForPropertyAndConstructorLookups() + { + return VerifyAsync(""" + class C + { + void M() + { + var a = {|E128137:typeof(string).GetProperty("Length", BindingFlags.NonPublic | BindingFlags.Instance)|}; + var b = {|E128137:typeof(string).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAStaticImportOfTheNonPublicFlag() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Reflection; + using static System.Reflection.BindingFlags; + + class C + { + void M() + { + var method = {|E128137:typeof(string).GetMethod("Empty", NonPublic | Static)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenANonPublicNameDoesNotResolveToBindingFlags() + { + return VerifyAsync(""" + class C + { + const BindingFlags NonPublic = BindingFlags.Public; + + void M() + { + var method = typeof(string).GetMethod("Empty", NonPublic | BindingFlags.Static); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForOtherMethodsOnTypeAndOtherReceivers() + { + return VerifyAsync(""" + class Other + { + public object GetMethod(string name, BindingFlags flags) => null; + } + + class C + { + void M(Other other, Type type) + { + var a = other.GetMethod("M", BindingFlags.NonPublic); + var b = type.GetMethod("M", BindingFlags.NonPublic); + var c = typeof(string).GetMethods(BindingFlags.Public); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..f0982a22 --- /dev/null +++ b/tests/E128.Analyzers.Tests/NullByRefAnalyzerBranchCoverageTests.cs @@ -0,0 +1,144 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class NullByRefAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code, options: new AnalyzerTestOptions { AllowUnsafe = true }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAsRefOfANullLiteral() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int value = ref {|E128127:Unsafe.AsRef(null)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAsRefOfADefaultPointer() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int value = ref {|E128127:Unsafe.AsRef(default(void*))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAsRefOfAZeroPointerCastWithEachLiteralType() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M() + { + ref int a = ref {|E128127:Unsafe.AsRef((void*)0u)|}; + ref int b = ref {|E128127:Unsafe.AsRef((void*)0L)|}; + ref int c = ref {|E128127:Unsafe.AsRef((void*)0UL)|}; + ref int d = ref {|E128127:Unsafe.AsRef((void*)null)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForNullRefCalledThroughUsingStatic() + { + return VerifyAsync(""" + using static System.Runtime.CompilerServices.Unsafe; + class C + { + void M() + { + ref int value = ref {|E128127:NullRef()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAsRefOfAPointerThatIsNotNull() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + unsafe class C + { + void M(void* pointer, int value) + { + ref int a = ref Unsafe.AsRef((void*)1); + ref int b = ref Unsafe.AsRef(pointer); + ref int c = ref Unsafe.AsRef(in value); + ref int d = ref Unsafe.AsRef((void*)pointer); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForSameNamedMethodsOnOtherTypes() + { + return VerifyAsync(""" + static class Unsafe + { + public static unsafe ref T AsRef(void* source) where T : unmanaged { return ref *(T*)source; } + public static ref T NullRef() { throw new System.InvalidOperationException(); } + } + + unsafe class C + { + void M() + { + ref int a = ref Unsafe.AsRef(null); + ref int b = ref Unsafe.NullRef(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNullRefIsReturnedAsTheNotFoundSentinel() + { + return VerifyAsync(""" + using System.Runtime.CompilerServices; + class C + { + ref int Find(bool found, ref int value) + { + if (!found) + { + return ref Unsafe.NullRef(); + } + + return ref value; + } + + ref int Missing() => ref Unsafe.NullRef(); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/OceWhenTokenFilterBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/OceWhenTokenFilterBranchCoverageTests.cs new file mode 100644 index 00000000..f4af7b23 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OceWhenTokenFilterBranchCoverageTests.cs @@ -0,0 +1,72 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OceWhenTokenFilterBranchCoverageTests +{ + private static Task VerifyAsync(string catchClauses) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\n" + + "struct FakeToken { public bool IsCancellationRequested => false; }\n" + + "class C\n{\n void M(CancellationToken token, FakeToken fake, bool flag)\n {\n try { }\n" + + catchClauses + "\n }\n}\n"); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("TaskCanceledException")] + [InlineData("System.OperationCanceledException")] + public Task Reports_ForTheCancellationExceptionTypes(string type) + { + return VerifyAsync($$""" + {|E128100:catch ({{type}}) when (!token.IsCancellationRequested)|} + { + throw; + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("(!token.IsCancellationRequested)")] + [InlineData("((!(token.IsCancellationRequested)))")] + public Task Reports_ThroughParentheses(string filter) + { + return VerifyAsync($$""" + {|E128100:catch (OperationCanceledException) when ({{filter}})|} + { + throw; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForACatchWithoutADeclarationOrFilter() + { + return VerifyAsync(""" + catch when (!token.IsCancellationRequested) + { + } + catch (OperationCanceledException) + { + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("catch (InvalidOperationException) when (!token.IsCancellationRequested) { }")] + [InlineData("catch (OperationCanceledException) when (token.IsCancellationRequested) { }")] + [InlineData("catch (OperationCanceledException) when (!fake.IsCancellationRequested) { }")] + [InlineData("catch (OperationCanceledException) when (!token.CanBeCanceled) { }")] + [InlineData("catch (OperationCanceledException) when (!flag) { }")] + [InlineData("catch (OperationCanceledException) when (flag) { }")] + public Task Silent_ForFiltersThatAreNotTheNegatedTokenState(string clause) + { + return VerifyAsync(clause); + } +} diff --git a/tests/E128.Analyzers.Tests/OptionsBindInitBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/OptionsBindInitBranchCoverageTests.cs new file mode 100644 index 00000000..841787e3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OptionsBindInitBranchCoverageTests.cs @@ -0,0 +1,147 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the Bind call shapes and options types that the init-only rule reads. +/// +public sealed class OptionsBindInitBranchCoverageTests +{ + private const string Stubs = """ + namespace Microsoft.Extensions.Configuration + { + public interface IConfiguration + { + IConfigurationSection GetSection(string key); + } + + public interface IConfigurationSection : IConfiguration + { + } + } + + namespace Microsoft.Extensions.Options + { + public class OptionsBuilder where T : class + { + public OptionsBuilder Bind(Microsoft.Extensions.Configuration.IConfigurationSection section) => this; + } + } + + """; + + private static Task VerifyAsync(string source) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EachInitAccessorOfTheBoundType() + { + return VerifyAsync(""" + public class Options + { + public string First { get; {|E128033:init|}; } + + public int Second { get; {|E128033:init|}; } + + public int Third { get; set; } + } + + class Setup + { + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + new Microsoft.Extensions.Options.OptionsBuilder() + .Bind(config.GetSection("Options")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePositionalRecordSynthesizesTheInitAccessor() + { + return VerifyAsync(""" + public record Options(string Name); + + class Setup + { + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + new Microsoft.Extensions.Options.OptionsBuilder() + .Bind(config.GetSection("Options")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheBoundTypeComesFromMetadata() + { + return VerifyAsync(""" + class Setup + { + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + new Microsoft.Extensions.Options.OptionsBuilder() + .Bind(config.GetSection("Handler")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenBindBelongsToAnotherType() + { + return VerifyAsync(""" + public class Options + { + public string Name { get; init; } = string.Empty; + } + + class Binder + { + public Binder Bind(Microsoft.Extensions.Configuration.IConfigurationSection section) => this; + } + + class Setup + { + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + new Binder().Bind(config.GetSection("Options")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenBindIsCalledWithoutAReceiver() + { + return VerifyAsync(""" + public class Options + { + public string Name { get; init; } = string.Empty; + } + + class Setup + { + void Bind(Microsoft.Extensions.Configuration.IConfigurationSection section) + { + } + + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + Bind(config.GetSection("Options")); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/OptionsBindInitCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/OptionsBindInitCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..e53b648d --- /dev/null +++ b/tests/E128.Analyzers.Tests/OptionsBindInitCodeFixBranchCoverageTests.cs @@ -0,0 +1,104 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Applies the init-to-set rewrite. The analyzer reports from a compilation start action, so +/// the verifier skips the local diagnostic check. +/// +public sealed class OptionsBindInitCodeFixBranchCoverageTests +{ + private const string Stubs = """ + namespace Microsoft.Extensions.Configuration + { + public interface IConfiguration + { + IConfigurationSection GetSection(string key); + } + + public interface IConfigurationSection : IConfiguration + { + } + } + + namespace Microsoft.Extensions.Options + { + public class OptionsBuilder where T : class + { + public OptionsBuilder Bind(Microsoft.Extensions.Configuration.IConfigurationSection section) => this; + } + } + + """; + + private const string Setup = """ + + class Setup + { + void Configure(Microsoft.Extensions.Configuration.IConfiguration config) + { + new Microsoft.Extensions.Options.OptionsBuilder() + .Bind(config.GetSection("Mixed")); + } + } + """; + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesInitWithSet_ForAnAutoProperty() + { + return CodeFixTestRunner.RunAsync( + Stubs + """ + public class MixedOptions + { + public string Mutable { get; set; } = string.Empty; + + public string Immutable { get; {|E128033:init|}; } + } + """ + Setup, + Stubs + """ + public class MixedOptions + { + public string Mutable { get; set; } = string.Empty; + + public string Immutable { get; set; } + } + """ + Setup, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesInitWithSet_AndKeepsTheBodyAndModifiers() + { + return CodeFixTestRunner.RunAsync( + Stubs + """ + public class MixedOptions + { + private string _name = string.Empty; + + public string Name + { + get => _name; + protected {|E128033:init|} { _name = value; } + } + } + """ + Setup, + Stubs + """ + public class MixedOptions + { + private string _name = string.Empty; + + public string Name + { + get => _name; + protected set { _name = value; } + } + } + """ + Setup, + behaviors: CodeFixTestBehaviors.SkipLocalDiagnosticCheck); + } +} diff --git a/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..e3efb56f --- /dev/null +++ b/tests/E128.Analyzers.Tests/OptionsValidationMissingAnalyzerBranchCoverageTests.cs @@ -0,0 +1,349 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OptionsValidationMissingAnalyzerBranchCoverageTests +{ + // A compact copy of the framework surface that the rule resolves by metadata name. + private const string Stubs = """ + using System; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Options; + + namespace Microsoft.Extensions.Configuration + { + public interface IConfiguration + { + } + } + + namespace Microsoft.Extensions.Options + { + public sealed class OptionsBuilder + where TOptions : class + { + public OptionsBuilder Validate(Func validate) + { + return this; + } + + public OptionsBuilder Tweak(object value) + { + return this; + } + } + + public interface IValidateOptions + where TOptions : class + { + } + } + + namespace Microsoft.Extensions.DependencyInjection + { + using System; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.Options; + + public interface IServiceCollection + { + } + + public static class ServiceCollectionServiceExtensions + { + public static IServiceCollection AddSingleton(this IServiceCollection services) + where TService : class + where TImplementation : class, TService + { + return services; + } + + public static IServiceCollection AddSingleton(this IServiceCollection services) + where TService : class + { + return services; + } + } + + public static class OptionsServiceCollectionExtensions + { + public static OptionsBuilder AddOptions(this IServiceCollection services) + where TOptions : class + { + return new OptionsBuilder(); + } + + public static OptionsBuilder AddOptions(this IServiceCollection services, string name) + where TOptions : class + { + return new OptionsBuilder(); + } + + public static IServiceCollection Configure(this IServiceCollection services, Action configureOptions) + where TOptions : class + { + return services; + } + + public static IServiceCollection PostConfigure(this IServiceCollection services, Action configureOptions) + where TOptions : class + { + return services; + } + + public static OptionsBuilder AddOptions(this IServiceCollection services, string name, int extra) + where TOptions : class + { + return new OptionsBuilder(); + } + } + + public static class OptionsConfigurationServiceCollectionExtensions + { + public static IServiceCollection Configure(this IServiceCollection services, IConfiguration configuration) + where TOptions : class + { + return services; + } + } + + public static class OptionsBuilderConfigurationExtensions + { + public static OptionsBuilder Bind(this OptionsBuilder builder, IConfiguration configuration) + where TOptions : class + { + return builder; + } + } + + public static class OptionsBuilderExtensions + { + public static OptionsBuilder ValidateOnStart(this OptionsBuilder builder) + where TOptions : class + { + return builder; + } + } + } + + class MyOptions + { + public string Name { get; set; } = ""; + } + + class OtherOptions + { + public string Name { get; set; } = ""; + } + + class MyValidator : IValidateOptions + { + } + + interface ISomething + { + } + + class Something : ISomething + { + } + + class OtherSomething : ISomething + { + } + + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheOptionsPackageTypesAreMissing() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Builder + { + public Builder AddOptions() { return this; } + public Builder Bind(object configuration) { return this; } + } + + class Startup + { + void Configure(Builder builder, object configuration) + { + builder.AddOptions().Bind(configuration); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALateBoundCallFollowsTheRegistration() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services, IConfiguration configuration) + { + {|E128179:services.AddOptions()|}.Bind(configuration).Tweak((dynamic)configuration); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForTheUnreducedStaticRegistrationCall() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services, IConfiguration configuration) + { + {|E128179:OptionsServiceCollectionExtensions.AddOptions(services)|}.Bind(configuration); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherMemberInTheFileRegistersTheValidator() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration); + } + + void Validators(IServiceCollection services) + { + Helper(); + services.AddSingleton(); + services.AddSingleton, OtherSomething>(); + services.AddSingleton, MyValidator>(); + } + + void Helper() + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFileValidatorTargetsAnotherOptionsType() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services, IConfiguration configuration) + { + {|E128179:services.Configure(configuration)|}; + } + + void Validators(IServiceCollection services, Startup other) + { + other.Helper(); + services.AddSingleton>(); + services.AddSingleton, OtherSomething>(); + } + + void Helper() + { + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAValidationCallFollowsABindCallOnTheBuilder() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services, IConfiguration configuration) + { + services.AddOptions().Bind(configuration).ValidateOnStart(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForACallToALocalMethodNamedLikeTheRegistration() + { + return VerifyAsync(""" + class Startup + { + void Configure(IServiceCollection services) + { + } + + void Run(IServiceCollection services) + { + Configure(services); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForALateBoundRegistrationCall() + { + return VerifyAsync(""" + class Startup + { + void Run(IServiceCollection services, IConfiguration configuration) + { + dynamic late = services; + late.AddOptions().Bind(configuration); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnAddOptionsOverloadWithMoreParameters() + { + return VerifyAsync(""" + class Startup + { + void Run(IServiceCollection services, IConfiguration configuration) + { + services.AddOptions("named", 1).Bind(configuration); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAPostConfigureCallFollowsTheRegistration() + { + return VerifyAsync(""" + class Startup + { + void Run(IServiceCollection services, IConfiguration configuration) + { + {|E128179:services.Configure(configuration)|}.PostConfigure(options => { }); + } + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/OrderByFirstBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/OrderByFirstBranchCoverageTests.cs new file mode 100644 index 00000000..3fe76793 --- /dev/null +++ b/tests/E128.Analyzers.Tests/OrderByFirstBranchCoverageTests.cs @@ -0,0 +1,145 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class OrderByFirstBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenFirstTakesAPredicate() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + class C + { + int M(List items) + { + return items.OrderBy(x => x).First(x => x > 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenOrderByTakesAComparerOrIsFollowedByThenBy() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + class C + { + int M(List items) + { + var first = items.OrderBy(x => x, Comparer.Default).First(); + var second = items.OrderBy(x => x).ThenBy(x => x).First(); + return first + second; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFirstCallFollowsAHelperOrAMethodGroup() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + class C + { + static IEnumerable Sorted(List items) => items; + + int M(List items) + { + return Sorted(items).First(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSourceIsAQueryable() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Linq; + class C + { + int M(IQueryable items) + { + return items.OrderBy(x => x).First(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnotherNamespaceDefinesTheEnumerableMethods() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + namespace MyLinq + { + public static class Enumerable + { + public static List OrderBy(this List source, System.Func key) => source; + + public static T First(this List source) => source[0]; + } + } + + namespace Other.Linq + { + public static class Enumerable + { + public static List OrderByDescending(this List source, System.Func key) => source; + + public static T FirstOrDefault(this List source) => source[0]; + } + } + + namespace App + { + using MyLinq; + using Other.Linq; + + class C + { + int M(List items) + { + return items.OrderBy(x => x).First() + items.OrderByDescending(x => x).FirstOrDefault(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenOnlyTheFirstCallComesFromAnotherType() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + + static class Extras + { + public static T First(this IOrderedEnumerable source) => default!; + } + + class C + { + int M(List items) + { + return Extras.First(items.OrderBy(x => x)) + items.OrderBy(x => x).First(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ParallelCollectionIndexBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ParallelCollectionIndexBranchCoverageTests.cs new file mode 100644 index 00000000..c468aca3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ParallelCollectionIndexBranchCoverageTests.cs @@ -0,0 +1,216 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ParallelCollectionIndexBranchCoverageTests +{ + private static Task VerifyAsync(string body, string members = "") + { + var code = "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n" + + "using static System.Linq.Enumerable;\n\n" + + "public static class Subject\n{\n" + + members + + " public static void Verify(List columns, List> rows, int[,] grid, int k)\n {\n" + + body + + " }\n}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task MultiArgumentIndexer_Silent() + { + return VerifyAsync(""" + for (var i = 0; i < columns.Count; i++) + { + _ = grid[i, 0]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NonIdentifierIndex_Silent() + { + return VerifyAsync(""" + for (var i = 0; i < columns.Count; i++) + { + _ = rows[i + 1]; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task IndexThatNoLoopOrLambdaDeclares_Silent() + { + return VerifyAsync(""" + _ = rows[k]; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task TwoAccessesInOneLambda_BothReported() + { + return VerifyAsync(""" + var cells = Enumerable.Range(0, columns.Count) + .Select(i => {|E128106:rows[i]|}.Count + {|E128106:rows[i]|}.Count) + .ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task RangeThatStartsAboveZero_Silent() + { + return VerifyAsync(""" + var cells = Enumerable.Range(1, columns.Count).Select(i => rows[i]).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task RangeWithConstantOrCapacityCount_Silent() + { + return VerifyAsync(""" + var fixedCells = Enumerable.Range(0, 5).Select(i => rows[i]).ToList(); + var sized = Enumerable.Range(0, columns.Capacity).Select(i => rows[i]).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task RepeatInsteadOfRange_Silent() + { + return VerifyAsync(""" + var cells = Enumerable.Repeat(0, columns.Count).Select((x, i) => rows[i]).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task LambdaOutsideAnyInvocation_Silent() + { + return VerifyAsync(""" + Func> pick = i => rows[i]; + _ = pick(0); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task RangeCalledThroughADelegateVariableOrArrayElement_Silent() + { + return VerifyAsync(""" + Func> range = Enumerable.Range; + var viaVariable = range(0, columns.Count).Select(i => rows[i]).ToList(); + var ranges = new[] { range }; + var viaElement = ranges[0](0, columns.Count).Select(i => rows[i]).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ParenthesizedLambdaParameter_Reported() + { + return VerifyAsync(""" + var cells = Enumerable.Range(0, columns.Count).Select((i) => {|E128106:rows[i]|}).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task RangeCalledThroughUsingStatic_Reported() + { + return VerifyAsync(""" + var cells = Range(0, columns.Count).Select(i => {|E128106:rows[i]|}).ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task AnonymousMethodParameter_Silent() + { + return VerifyAsync(""" + var cells = Enumerable.Range(0, columns.Count) + .Select(delegate (int i) { return rows[i]; }) + .ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NestedLambdaOverTheOuterIndex_Reported() + { + return VerifyAsync(""" + var cells = Enumerable.Range(0, columns.Count) + .Select(i => columns.Select(x => {|E128106:rows[i]|}).ToList()) + .ToList(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task LengthGuardWithTheIndexOnTheLeft_Silent() + { + return VerifyAsync(""" + for (var i = 0; i < columns.Count; i++) + { + if (i < rows.Count) + { + _ = rows[i]; + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ComparisonsThatAreNotLengthGuards_StillReported() + { + return VerifyAsync(""" + for (var i = 0; i < columns.Count; i++) + { + if (k > i && i < columns.Count && rows.Count > 0 && GetRows().Count > i && new List().Capacity > i) + { + _ = {|E128106:rows[i]|}; + } + } + + """, """ + public static List GetRows() => new(); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task ForLoopWithoutCondition_Silent() + { + return VerifyAsync(""" + for (var i = 0; ; i++) + { + _ = rows[i]; + break; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ParallelForEachAsyncCapBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ParallelForEachAsyncCapBranchCoverageTests.cs new file mode 100644 index 00000000..8986c128 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ParallelForEachAsyncCapBranchCoverageTests.cs @@ -0,0 +1,111 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ParallelForEachAsyncCapBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + var code = "using System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\n\n" + + "class MyOptions : ParallelOptions\n{\n}\n\n" + + "class C\n{\n Task M(List items, CancellationToken token, ParallelOptions options)\n {\n" + + body + + " }\n}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheOptionsAreNamedAndUncapped() + { + return VerifyAsync(""" + return {|E128187:Parallel.ForEachAsync(items, parallelOptions: new ParallelOptions(), body: (item, ct) => default)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNamedOptionsAreCapped() + { + return VerifyAsync(""" + return Parallel.ForEachAsync( + source: items, + parallelOptions: new ParallelOptions { MaxDegreeOfParallelism = 4 }, + body: (item, ct) => default); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNamedOptionsComeFromAVariable() + { + return VerifyAsync(""" + return Parallel.ForEachAsync(items, parallelOptions: options, body: (item, ct) => default); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenOnlyOtherArgumentsAreNamed() + { + return VerifyAsync(""" + return {|E128187:Parallel.ForEachAsync(source: items, body: (item, ct) => default)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheTokenOverloadTakesNoOptions() + { + return VerifyAsync(""" + return {|E128187:Parallel.ForEachAsync(items, token, (item, ct) => default)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenADerivedOptionsTypeIsCreated() + { + return VerifyAsync(""" + return Parallel.ForEachAsync(items, new MyOptions(), (item, ct) => default); + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheDefaultExpressionOrLiteralIsPassed() + { + return VerifyAsync(""" + _ = {|E128187:Parallel.ForEachAsync(items, default(ParallelOptions), (item, ct) => default)|}; + return {|E128187:Parallel.ForEachAsync(items, parallelOptions: default, body: (item, ct) => default)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenForEachAsyncIsCalledWithoutAReceiver() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + using System.Threading.Tasks; + using static System.Threading.Tasks.Parallel; + + class C + { + Task M(List items) + { + return ForEachAsync(items, (item, ct) => default); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PathCombineSegmentBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PathCombineSegmentBranchCoverageTests.cs new file mode 100644 index 00000000..3a29f74d --- /dev/null +++ b/tests/E128.Analyzers.Tests/PathCombineSegmentBranchCoverageTests.cs @@ -0,0 +1,84 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PathCombineSegmentBranchCoverageTests +{ + [Theory] + [Trait("Category", "CI")] + [InlineData("", false)] + [InlineData("/x", true)] + [InlineData("\\x", true)] + [InlineData("C:x", true)] + [InlineData("z:", true)] + [InlineData("1:x", false)] + [InlineData(":x", false)] + [InlineData("x", false)] + [InlineData("ab", false)] + public void IsRooted_RecognizesSeparatorAndDriveRoots(string segment, bool expected) + { + Assert.Equal(expected, PathCombineSegmentAnalyzer.IsRooted(segment)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("a", false)] + [InlineData("..", false)] + [InlineData("../a", true)] + [InlineData("..\\a", true)] + [InlineData("a/../b", false)] + [InlineData("a/../../b", true)] + [InlineData("./a", false)] + [InlineData("a//b", false)] + [InlineData("/a/b", false)] + public void EscapesBase_CountsDepthAcrossSegments(string segment, bool expected) + { + Assert.Equal(expected, PathCombineSegmentAnalyzer.EscapesBase(segment)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNonConstantAndNullSegments() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + string M(string name) => Path.Combine("base", name) + Path.Combine("base", null!); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EachRiskySegmentAfterTheBase() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.IO; + class C + { + const string Root = "/etc"; + + string M() => Path.Combine("/base", "safe", {|E128161:Root|}, {|E128161:"../up"|}); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForCombineOnAnotherPathType() + { + return AnalyzerTestRunner.VerifyAsync(""" + class Path + { + public static string Combine(string a, string b) => a + b; + } + class C + { + string M() => Path.Combine("base", "/etc"); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetBranchCoverageTests.cs new file mode 100644 index 00000000..6fef8b7d --- /dev/null +++ b/tests/E128.Analyzers.Tests/PfxImportEphemeralKeySetBranchCoverageTests.cs @@ -0,0 +1,89 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PfxImportEphemeralKeySetBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_FileConstructorsWithoutTheEphemeralBit() + { + return VerifyAsync(""" + using System.Security.Cryptography.X509Certificates; + class C + { + void M(string path, string password, X509KeyStorageFlags unknown) + { + X509Certificate2 b = {|E128191:new(path, password, X509KeyStorageFlags.Exportable)|}; + var c = {|E128191:new X509Certificate2(path, password, X509KeyStorageFlags.Exportable)|}; + var d = {|E128191:new X509Certificate2(keyStorageFlags: X509KeyStorageFlags.PersistKeySet, password: password, fileName: path)|}; + var e = new X509Certificate2(path, password, X509KeyStorageFlags.EphemeralKeySet); + var f = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet); + var g = new X509Certificate2(path, password, unknown); + var h = {|E128191:new X509Certificate2(path, "pw", (X509KeyStorageFlags)0)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheConstructorHasNoFileNameOrNoFlags() + { + return VerifyAsync(""" + using System.Security.Cryptography.X509Certificates; + class Other + { + public Other(string fileName) { } + } + + class C + { + void M(byte[] data, string path, string password) + { + var a = new X509Certificate2(data); + var b = new X509Certificate2(data, password); + var d = new Other(path); + var e = new System.Text.StringBuilder(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_EveryPkcs12LoaderWithoutTheEphemeralBit() + { + return VerifyAsync(""" + using System.Security.Cryptography.X509Certificates; + class C + { + void M(byte[] data, string path, string password, X509KeyStorageFlags unknown) + { + var a = {|E128191:X509CertificateLoader.LoadPkcs12(data, password)|}; + var b = {|E128191:X509CertificateLoader.LoadPkcs12FromFile(path, password)|}; + var c = {|E128191:X509CertificateLoader.LoadPkcs12Collection(data, password)|}; + var d = {|E128191:X509CertificateLoader.LoadPkcs12CollectionFromFile(path, password)|}; + var e = {|E128191:X509CertificateLoader.LoadPkcs12(data, password, X509KeyStorageFlags.Exportable)|}; + var f = X509CertificateLoader.LoadPkcs12(data, password, X509KeyStorageFlags.EphemeralKeySet); + var g = X509CertificateLoader.LoadPkcs12(data, password, unknown); + var h = X509CertificateLoader.LoadCertificate(data); + var i = X509CertificateLoader.LoadCertificateFromFile(path); + var j = new Own().LoadPkcs12(data, password); + } + } + + class Own + { + public object LoadPkcs12(byte[] data, string password) => data; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PollingLoopNoTokenBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PollingLoopNoTokenBranchCoverageTests.cs new file mode 100644 index 00000000..68ce1350 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PollingLoopNoTokenBranchCoverageTests.cs @@ -0,0 +1,128 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PollingLoopNoTokenBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fires_ForDelayInAForeachOrDoLoop() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + class C + { + async Task M(int[] items, Func done) + { + foreach (var item in items) + { + await {|E128211:Task.Delay(item)|}; + } + + do + { + await {|E128211:Task.Delay(TimeSpan.FromSeconds(1))|}; + } + while (!done()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_ForDelayCalledThroughUsingStatic() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + using static System.Threading.Tasks.Task; + class C + { + async Task M(Func done) + { + while (!done()) + { + await {|E128211:Delay(100)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopConditionObservesTheToken() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading; + using System.Threading.Tasks; + class C + { + static bool Check(CancellationToken token) => token.IsCancellationRequested; + + async Task M(CancellationToken token) + { + for (; !token.IsCancellationRequested;) + { + await Task.Delay(100); + } + + while (!Check(token)) + { + await Task.Delay(100); + } + + do + { + await Task.Delay(100); + } + while (!token.IsCancellationRequested); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenTheLoopConditionMentionsNoToken() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Threading.Tasks; + class C + { + async Task M(int attempts) + { + for (var i = 0; i < attempts; i++) + { + await {|E128211:Task.Delay(100)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForDelayCalledOnAnotherReceiverExpression() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + class C + { + void M(Func> factory, int[] items) + { + foreach (var item in items) + { + _ = factory()(item); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PoolRentCapacityGuardBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PoolRentCapacityGuardBranchCoverageTests.cs new file mode 100644 index 00000000..202c07e2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PoolRentCapacityGuardBranchCoverageTests.cs @@ -0,0 +1,281 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers which Rent calls the capacity rule inspects and which guards it accepts. +/// +public sealed class PoolRentCapacityGuardBranchCoverageTests +{ + private const string Pools = """ + using System; + using System.Buffers; + class BytePool + { + public byte[] Rent(int size) => new byte[size]; + } + + class lowerpool + { + public byte[] Rent(int size) => new byte[size]; + } + + class Allocator + { + public byte[] Rent(int size) => new byte[size]; + } + + class WidePool + { + public byte[] Rent(long size) => new byte[size]; + public byte[] Rent(int size, int extra = 0) => new byte[size]; + } + + static class Math2 + { + public static int Min(int a, int b) => a < b ? a : b; + } + + """; + + private static Task VerifyAsync(string body, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + Pools + "class C\n{\n" + body + "\n}\n", + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAMemoryPoolRentOfAVariableSize() + { + return VerifyAsync(""" + void M(int size) + { + using var owner = MemoryPool.Shared.{|E128070:Rent(size)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForATypeWhoseNameEndsInPool() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var buffer = pool.{|E128070:Rent(size)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForATypeWhoseNameContainsLowercasePool() + { + return VerifyAsync(""" + void M(lowerpool pool, int size) + { + var buffer = pool.{|E128070:Rent(size)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForANegativeConstantSize() + { + return VerifyAsync(""" + void M(BytePool pool) + { + var buffer = pool.{|E128070:Rent(-1)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheArgumentIsAnotherCall() + { + return VerifyAsync(""" + static int Size() => 10; + + void M(BytePool pool) + { + var buffer = pool.{|E128070:Rent(Size())|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCapComesFromAMinLookAlike() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var buffer = pool.{|E128070:Rent(Math2.Min(size, 10))|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsALocalFromMathMin() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var capped = Math.Min(size, 1024); + var buffer = pool.Rent(capped); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLocalComesFromAnotherCall() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var wider = Math.Max(size, 1024); + var buffer = pool.{|E128070:Rent(wider)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLocalComesFromAMinLookAlike() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var capped = Math2.Min(size, 1024); + var buffer = pool.{|E128070:Rent(capped)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLocalComesFromAPlainValue() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + var copy = size; + var buffer = pool.{|E128070:Rent(copy)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLocalHasNoInitializer() + { + return VerifyAsync(""" + void M(BytePool pool, int size) + { + int later; + later = size; + var buffer = pool.{|E128070:Rent(later)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheArgumentIsAField() + { + return VerifyAsync(""" + private int _size; + + void M(BytePool pool) + { + var buffer = pool.{|E128070:Rent(_size)|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTypeIsNotAPool() + { + return VerifyAsync(""" + void M(Allocator allocator, int size) + { + var buffer = allocator.Rent(size); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRentTakesALongSize() + { + return VerifyAsync(""" + void M(WidePool pool, long size) + { + var buffer = pool.Rent(size); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRentOverloadHasASecondParameter() + { + return VerifyAsync(""" + void M(WidePool pool, int size) + { + var buffer = pool.Rent(size); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAMemberCall() + { + return VerifyAsync(""" + byte[] Rent(int size) => new byte[size]; + + void M(int size) + { + var buffer = Rent(size); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMethodIsNotNamedRent() + { + return VerifyAsync(""" + void M(BytePool pool) + { + var text = pool.ToString(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallDoesNotBind() + { + return VerifyAsync( + """ + void M(BytePool pool) + { + var buffer = pool.Rent(missing); + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/PooledBufferZeroingBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PooledBufferZeroingBranchCoverageTests.cs new file mode 100644 index 00000000..30d8df8b --- /dev/null +++ b/tests/E128.Analyzers.Tests/PooledBufferZeroingBranchCoverageTests.cs @@ -0,0 +1,127 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PooledBufferZeroingBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAWholeIntArrayIsZeroedThroughAsBytes() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + using System.Runtime.InteropServices; + using System.Security.Cryptography; + class C + { + void M() + { + var buffer = ArrayPool.Shared.Rent(8); + try { } + finally + { + CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(buffer.AsSpan())); + ArrayPool.Shared.Return(buffer); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherBufferIsZeroed() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Buffers; + using System.Security.Cryptography; + class C + { + void M(byte[] other) + { + var buffer = ArrayPool.Shared.Rent(8); + try { } + finally + { + CryptographicOperations.ZeroMemory(other); + {|E128110:ArrayPool.Shared.Return(buffer)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAFunctionNamedZeroMemoryIsNotCryptographicOperations() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Buffers; + class C + { + static void ZeroMemory(byte[] buffer) { } + void M() + { + var buffer = ArrayPool.Shared.Rent(8); + try { } + finally + { + ZeroMemory(buffer); + {|E128110:ArrayPool.Shared.Return(buffer)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheBufferIsUsedAfterTheEnclosingBlock() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + class C + { + void M(bool flag) + { + var buffer = ArrayPool.Shared.Rent(8); + if (flag) + { + {|E128110:ArrayPool.Shared.Return(buffer)|}; + } + Console.WriteLine({|E128111:buffer|}.Length); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForUseAfterANewBufferReplacesTheReturnedBuffer() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Buffers; + using System.Security.Cryptography; + class C + { + void M() + { + var buffer = ArrayPool.Shared.Rent(8); + try { } + finally + { + CryptographicOperations.ZeroMemory(buffer); + ArrayPool.Shared.Return(buffer); + } + buffer = new byte[8]; + Console.WriteLine(buffer.Length); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/PrimaryConstructorBackingFieldCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/PrimaryConstructorBackingFieldCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..1691c7d1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/PrimaryConstructorBackingFieldCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,82 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class PrimaryConstructorBackingFieldCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReplacesAThisQualifiedFieldAccess() + { + return VerifyFixAsync( + """ + class C(int value) + { + private readonly int {|E128017:_value|} = value; + int Get() => this._value; + } + """, + """ + class C(int value) + { + int Get() => value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsOtherVariablesInTheSameFieldDeclaration() + { + return VerifyFixAsync( + """ + class C(int value) + { + private readonly int {|E128017:_value|} = value, _other = 2; + int Get() => _value + _other; + } + """, + """ + class C(int value) + { + private readonly int _other = 2; + int Get() => value + _other; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_LeavesASameNamedLocalAlone() + { + return VerifyFixAsync( + """ + class C(int value) + { + private readonly int {|E128017:_value|} = value; + int Get() + { + int _value = 2; + return _value + this._value; + } + } + """, + """ + class C(int value) + { + int Get() + { + int _value = 2; + return _value + value; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessOutputValidatorBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ProcessOutputValidatorBranchCoverageTests.cs new file mode 100644 index 00000000..257faecd --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessOutputValidatorBranchCoverageTests.cs @@ -0,0 +1,176 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessOutputValidatorBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Diagnostics;\nusing System.IO;\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReadHappensBeforeTheWait() + { + return VerifyAsync(""" + string M(Process process, string outputFile) + { + var text = File.ReadAllText(outputFile); + process.WaitForExit(); + return text; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePathHasNoSimpleRoot() + { + return VerifyAsync(""" + static string Path() => "out.txt"; + + string M(Process process) + { + process.WaitForExit(); + var a = File.ReadAllText("out.txt"); + var b = File.ReadAllText(Path()); + return a + b; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAFileInfoExistsCheckPrecedesTheRead() + { + return VerifyAsync(""" + string? M(Process process, FileInfo output) + { + process.WaitForExit(); + if (!output.Exists) + { + return null; + } + + return File.ReadAllText(output.FullName); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheExistsCheckFollowsTheRead() + { + return VerifyAsync(""" + string M(Process process, string outputFile) + { + process.WaitForExit(); + var text = {|E128101:File.ReadAllText(outputFile)|}; + return File.Exists(outputFile) ? text : string.Empty; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheExistsCheckGuardsAnotherPath() + { + return VerifyAsync(""" + string M(Process process, string outputFile, string other) + { + process.WaitForExit(); + if (!File.Exists(other)) + { + return string.Empty; + } + + return {|E128101:File.ReadAllText(outputFile)|}; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAQualifiedFileReadAfterAWaitOnADerivedProcess() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Diagnostics; + + class Child : Process + { + string M(string outputFile) + { + WaitForExit(); + return {|E128101:System.IO.File.ReadAllText(outputFile)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsNotOnAProcess() + { + return VerifyAsync(""" + sealed class Worker + { + public void WaitForExit() { } + } + + string M(Worker worker, string outputFile) + { + worker.WaitForExit(); + return File.ReadAllText(outputFile); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsAnotherProcessMethodOrAnInvokedDelegate() + { + return VerifyAsync(""" + string M(Process process, Func factory, string outputFile) + { + process.Start(); + factory()(); + return File.ReadAllText(outputFile); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForReadsThatAreNotOnFile() + { + return VerifyAsync(""" + string M(Process process, StreamReader reader, string outputFile) + { + process.WaitForExit(); + return reader.ReadToEnd() + Path.GetFileName(outputFile); + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAMethodWithoutAProcessWait() + { + return VerifyAsync(""" + string M(string outputFile) => File.ReadAllText(outputFile); + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..3eeb5e25 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessOutputValidatorCodeFixBranchCoverageTests.cs @@ -0,0 +1,104 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessOutputValidatorCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesFileExistsForAMemberThatIsNotFullName() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Diagnostics; + using System.IO; + class Options { public string Output { get; set; } = ""; } + class C + { + string M(Process process, Options options) + { + process.WaitForExit(); + return {|E128101:File.ReadAllText(options.Output)|}; + } + } + """, + """ + using System; + using System.Diagnostics; + using System.IO; + class Options { public string Output { get; set; } = ""; } + class C + { + string M(Process process, Options options) + { + process.WaitForExit(); + if (!File.Exists(options.Output)) throw new InvalidOperationException($"Expected output file not created: {options.Output}"); + return File.ReadAllText(options.Output); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_InsertsTheGuardAfterTheLastWaitBeforeTheRead() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Diagnostics; + using System.IO; + class C + { + string M(Process first, Process second, string outputFile) + { + first.WaitForExit(); + second.WaitForExit(); + var note = "x"; + return note + {|E128101:File.ReadAllText(outputFile)|}; + } + } + """, + """ + using System; + using System.Diagnostics; + using System.IO; + class C + { + string M(Process first, Process second, string outputFile) + { + first.WaitForExit(); + second.WaitForExit(); + if (!File.Exists(outputFile)) throw new InvalidOperationException($"Expected output file not created: {outputFile}"); + var note = "x"; + return note + File.ReadAllText(outputFile); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheWaitSitsInAnOuterBlock() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Diagnostics; + using System.IO; + class C + { + string M(Process process, string outputFile, bool flag) + { + process.WaitForExit(); + if (flag) + { + return {|E128101:File.ReadAllText(outputFile)|}; + } + + return string.Empty; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentBranchCoverageTests.cs new file mode 100644 index 00000000..8d58d1a0 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentBranchCoverageTests.cs @@ -0,0 +1,93 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessStartInfoArgumentBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TargetTypedCreationAndStatementAssignments() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + void M(string value) + { + ProcessStartInfo a = new() { {|E128091:Arguments = value|} }; + var b = new ProcessStartInfo("tool"); + {|E128091:b.Arguments = value|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheValueIsEmptyOrArgumentListIsUsed() + { + return VerifyAsync(""" + using System.Diagnostics; + class C + { + const string None = ""; + + void M(string value) + { + var a = new ProcessStartInfo { Arguments = "" }; + var b = new ProcessStartInfo { Arguments = string.Empty }; + var c = new ProcessStartInfo { Arguments = None }; + var d = new ProcessStartInfo { Arguments = value, ArgumentList = { "x" } }; + var e = new ProcessStartInfo(); + var f = new ProcessStartInfo { FileName = "tool" }; + a.Arguments = ""; + var g = new System.Text.StringBuilder(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsNotAProcessStartInfoOrNotAMemberAccess() + { + return VerifyAsync(""" + using System.Diagnostics; + + namespace Other + { + public sealed class ProcessStartInfo + { + public string Arguments { get; set; } = ""; + } + } + + class Holder + { + public string Arguments { get; set; } = ""; + + public string Name { get; set; } = ""; + } + + class C + { + void M(string value, Holder holder, Other.ProcessStartInfo other) + { + holder.Arguments = value; + holder.Name = value; + other.Arguments = value; + var created = new Other.ProcessStartInfo { Arguments = value }; + var array = new string[1]; + array[0] = value; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..a7351020 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ProcessStartInfoArgumentCodeFixBranchCoverageTests.cs @@ -0,0 +1,161 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ProcessStartInfoArgumentCodeFixBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task LiteralArguments_SplitIntoOneTokenPerWord() + { + return VerifyFixAsync( + """ + using System.Diagnostics; + class C + { + void M() + { + var startInfo = new ProcessStartInfo + { + {|E128091:Arguments = "-a --long \"two words\" tail"|} + }; + } + } + """, + """ + using System.Diagnostics; + class C + { + void M() + { + var startInfo = new ProcessStartInfo + { + ArgumentList = + { + "-a", + "--long", + "two words", + "tail" + } + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task InterpolatedArguments_KeepAHoleGluedToItsTextAsOneToken() + { + return VerifyFixAsync( + """ + using System.Diagnostics; + class C + { + void M(string name, string other) + { + var startInfo = new ProcessStartInfo + { + {|E128091:Arguments = $"--name={name} {other} {name}{other}"|} + }; + } + } + """, + """ + using System.Diagnostics; + class C + { + void M(string name, string other) + { + var startInfo = new ProcessStartInfo + { + ArgumentList = + { + $"--name={name}", + other, + $"{name}{other}" + } + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheQuotesAreUnbalancedOrTheTextIsOnlyWhitespace() + { + return VerifyNoFixAsync( + """ + using System.Diagnostics; + class C + { + void M(string name) + { + var a = new ProcessStartInfo + { + {|E128091:Arguments = $"--name=\"{name}"|} + }; + var b = new ProcessStartInfo + { + {|E128091:Arguments = " "|} + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAHoleHasAFormatOrAlignmentClause() + { + return VerifyNoFixAsync( + """ + using System.Diagnostics; + class C + { + void M(int count) + { + var a = new ProcessStartInfo + { + {|E128091:Arguments = $"-n {count:x}"|} + }; + var b = new ProcessStartInfo + { + {|E128091:Arguments = $"-n {count,5}"|} + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheArgumentsAreAssignedOutsideAnObjectInitializer() + { + return VerifyNoFixAsync( + """ + using System.Diagnostics; + class C + { + void M(string name) + { + var startInfo = new ProcessStartInfo("tool"); + {|E128091:startInfo.Arguments = $"-x {name}"|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationBranchCoverageTests.cs new file mode 100644 index 00000000..35153ea1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/QuerySelectorAllMaterializationBranchCoverageTests.cs @@ -0,0 +1,135 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class QuerySelectorAllMaterializationBranchCoverageTests +{ + private const string Stub = """ + using System.Collections.Generic; + using System.Linq; + using AngleSharp.Dom; + namespace AngleSharp.Dom + { + public interface IElement { } + public interface IDocument + { + IEnumerable QuerySelectorAll(string selector); + } + public abstract class Page + { + protected IEnumerable QuerySelectorAll(string selector) => new List(); + } + } + """; + + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync(Stub + "\nclass C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALinqChainEndsInToList() + { + return VerifyAsync(""" + void M(IDocument doc) + { + foreach (var element in doc.QuerySelectorAll("p").Where(e => e != null).ToList()) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheQueryRunsInsideALambdaOfTheInitializer() + { + return VerifyAsync(""" + void M(IDocument doc) + { + var items = new[] { 1 }.SelectMany(_ => doc.QuerySelectorAll("p")); + foreach (var element in items) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopVariableHasNoInitializer() + { + return VerifyAsync(""" + void M(IDocument doc) + { + IEnumerable items; + items = doc.QuerySelectorAll("p"); + foreach (var element in items) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopSourceIsNotALocal() + { + return VerifyAsync(""" + IEnumerable field = new List(); + + void M(IEnumerable parameter) + { + foreach (var element in parameter) + { + } + + foreach (var element in field) + { + } + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnUnqualifiedQueryOnAnAngleSharpType() + { + return AnalyzerTestRunner.VerifyAsync( + Stub + """ + + class Child : Page + { + void M() + { + foreach (var element in {|E128076:QuerySelectorAll("p")|}) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnInitializerThatQueriesBeforeAnotherCall() + { + return VerifyAsync(""" + void M(IDocument doc) + { + var items = {|E128076:doc.QuerySelectorAll("p")|}.Where(e => e != null); + foreach (var element in items) + { + } + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamBranchCoverageTests.cs new file mode 100644 index 00000000..de9a3843 --- /dev/null +++ b/tests/E128.Analyzers.Tests/ReadOnlyMemoryStreamBranchCoverageTests.cs @@ -0,0 +1,267 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class ReadOnlyMemoryStreamBranchCoverageTests +{ + private const string Usings = """ + using System; + using System.IO; + using System.IO.Compression; + using System.Net.Http; + using System.Security.Cryptography; + using System.Text; + using System.Text.Json; + using System.Xml; + using System.Xml.Linq; + using System.Xml.XPath; + + """; + + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync(Usings + members); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamIsAssignedAfterItsDeclaration() + { + return VerifyAsync(""" + class C + { + void M(byte[] data) + { + MemoryStream stream; + stream = new MemoryStream(data); + _ = stream.Length; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamIsStoredInAFieldOrAProperty() + { + return VerifyAsync(""" + class C + { + private static readonly MemoryStream Shared = new MemoryStream(new byte[4]); + + private MemoryStream _stream = new MemoryStream(new byte[4]); + + public MemoryStream Stream { get; set; } = new MemoryStream(new byte[4]); + + void M(byte[] data) + { + _stream = new MemoryStream(data); + this.Stream = new MemoryStream(data); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCreationIsNotAssignedToAnything() + { + return VerifyAsync(""" + class C + { + void M(byte[] data) + { + using var reader = new StreamReader(new MemoryStream(data)); + new MemoryStream(data).Dispose(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamHasNoArgumentsOrIsAnotherType() + { + return VerifyAsync(""" + class C + { + void M() + { + using var empty = new MemoryStream(); + MemoryStream implicitEmpty = new(); + using var reader = new StringReader("text"); + _ = empty.Length + implicitEmpty.Length + reader.Peek(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherTypeReturnsTheBytes() + { + return VerifyAsync(""" + class Source + { + public static byte[] GetBytes(string text) + { + return new byte[4]; + } + } + + class C + { + void M(string text) + { + using var stream = {|E128224:new MemoryStream(Source.GetBytes(text))|}; + _ = stream.Length; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenPositionIsIncrementedOrDecremented() + { + return VerifyAsync(""" + class C + { + void M(byte[] data) + { + using var prefix = new MemoryStream(data); + ++prefix.Position; + + using var postfix = new MemoryStream(data); + postfix.Position--; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALengthIsPassedAsAnArgument() + { + return VerifyAsync(""" + class C + { + static void Use(long length) + { + } + + void M(byte[] data) + { + using var stream = {|E128224:new MemoryStream(data)|}; + Use(stream.Length); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheStreamIsCopiedIntoAnotherVariable() + { + return VerifyAsync(""" + class C + { + void M(byte[] data) + { + using var stream = new MemoryStream(data); + var alias = stream; + _ = alias.Length; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenReadOnlyConsumersTakeTheStream() + { + return VerifyAsync(""" + class C + { + void M(byte[] data) + { + using var forBinary = {|E128224:new MemoryStream(data)|}; + using var binary = new BinaryReader(forBinary); + + using var forContent = {|E128224:new MemoryStream(data)|}; + using var content = new StreamContent(forContent); + + using var forXPath = {|E128224:new MemoryStream(data)|}; + var xpath = new XPathDocument(forXPath); + + using var forXml = {|E128224:new MemoryStream(data)|}; + var document = XDocument.Load(forXml); + + using var forReader = {|E128224:new MemoryStream(data)|}; + using var reader = XmlReader.Create(forReader); + + using var forHash = {|E128224:new MemoryStream(data)|}; + using var sha = SHA256.Create(); + var hash = sha.ComputeHash(forHash); + + using var forBrotli = {|E128224:new MemoryStream(data)|}; + using var brotli = new BrotliStream(forBrotli, CompressionMode.Decompress); + + using var forDeflate = {|E128224:new MemoryStream(data)|}; + using var deflate = new DeflateStream(forDeflate, CompressionMode.Decompress); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAConsumerIsNotOnTheReadOnlyList() + { + return VerifyAsync(""" + class Parser + { + public static void Create(Stream stream) + { + } + } + + class C + { + void M(byte[] data) + { + using var buffered = new MemoryStream(data); + using var wrapper = new BufferedStream(buffered); + + using var custom = new MemoryStream(data); + Parser.Create(custom); + + using var other = new MemoryStream(data); + Console.WriteLine(other); + + using var hashed = new MemoryStream(data); + using var sha = SHA256.Create(); + _ = sha.ComputeHashAsync(hashed); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCompressionModeIsNotTheDecompressConstant() + { + return VerifyAsync(""" + class C + { + void M(byte[] data, CompressionMode mode) + { + using var stream = new MemoryStream(data); + using var wrapper = new GZipStream(stream, mode); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityBranchCoverageTests.cs new file mode 100644 index 00000000..59d9d143 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RecordMutableCollectionEqualityBranchCoverageTests.cs @@ -0,0 +1,81 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RecordMutableCollectionEqualityBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForStaticAndConstantFields() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record Widget + { + public static List Shared = new(); + public const List? Missing = null; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnInstanceFieldNextToAStaticField() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record Widget + { + public static List Shared = new(); + public List {|E128177:Items = new()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForPropertiesThatNeverJoinEquality() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + abstract record Widget + { + public static List Shared { get; set; } = new(); + public abstract List Declared { get; init; } + public List Computed => new(); + public List WithBody { get { return new(); } } + public List WithSetterBody { get; set { _ = value; } } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnArrayInARecordStruct() + { + return AnalyzerTestRunner.VerifyAsync(""" + record struct Pair({|E128177:int[] Values|}); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForADerivedRecordWhenTheBaseHasOnlyTheGeneratedHashCode() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Collections.Generic; + + record Base(int Id); + + record Derived(int Id) : Base(Id) + { + {|E128177:public HashSet Tags { get; init; } = new();|} + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RecursiveDeleteRootBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/RecursiveDeleteRootBranchCoverageTests.cs new file mode 100644 index 00000000..0d644634 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RecursiveDeleteRootBranchCoverageTests.cs @@ -0,0 +1,908 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RecursiveDeleteRootBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + private static Task VerifyNameAsync(string code, string name) + { + var expected = new DiagnosticResult("E128184", DiagnosticSeverity.Info) + .WithLocation(0) + .WithArguments(name); + + return AnalyzerTestRunner.VerifyAsync(code, expected); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotARecursiveDirectoryDelete() + { + return VerifyAsync(""" + using System; + using System.IO; + class Own + { + public void Delete(string path, bool recursive) { } + } + + class C + { + void Delete(string path, bool recursive) { } + + void M(string path, bool flag, Own own, dynamic dyn) + { + Directory.Delete(path); + Directory.Delete(path, false); + Directory.Delete(path, flag); + File.Delete(path); + own.Delete(path, true); + Delete(path, true); + dyn.Delete(path, true); + } + + void ThroughDelegate(string path, Action Delete) + { + Delete(path, true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NamedArgumentsInAnyOrder() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M(string path, DirectoryInfo directory) + { + {|E128184:Directory.Delete(path: path, recursive: true)|}; + {|E128184:Directory.Delete(recursive: true, path: path)|}; + {|E128184:Directory.Delete(path, recursive: true)|}; + {|E128184:directory.Delete(recursive: true)|}; + directory.Delete(); + Directory.Delete(path: path, recursive: false); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ADeleteThroughAStaticUsing() + { + return VerifyAsync(""" + using static System.IO.Directory; + class C + { + void M(string path) + { + {|E128184:Delete(path, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_RootedAndDriveRootConstants() + { + return VerifyAsync(""" + using System.IO; + class C + { + const string Rooted = "/var/data"; + const string Relative = "data"; + + void M() + { + {|E128184:Directory.Delete("/", true)|}; + {|E128184:Directory.Delete(" / ", true)|}; + {|E128184:Directory.Delete("\\", true)|}; + {|E128184:Directory.Delete("C:", true)|}; + {|E128184:Directory.Delete("c:/", true)|}; + {|E128184:Directory.Delete("D:\\", true)|}; + {|E128184:Directory.Delete("C:data", true)|}; + {|E128184:Directory.Delete("\\\\server\\share", true)|}; + {|E128184:Directory.Delete(Rooted, true)|}; + {|E128184:Directory.Delete("/" + "var", true)|}; + Directory.Delete(Relative, true); + Directory.Delete("data", true); + Directory.Delete("a", true); + Directory.Delete("1:", true); + Directory.Delete(("data"), true); + Directory.Delete((string)"data", true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_PathsThroughGetFullPathAndCombine() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M(string path) + { + Directory.Delete(Path.GetFullPath("data"), true); + Directory.Delete(Path.GetFullPath(Path.GetTempPath()), true); + Directory.Delete(Path.GetFullPath(Path.Combine(Path.GetTempPath(), "x")), true); + Directory.Delete(Path.Combine(Path.Combine(Path.GetTempPath(), "a"), "b"), true); + Directory.Delete(Path.Combine("data", path), true); + {|E128184:Directory.Delete(Path.GetFullPath("/etc"), true)|}; + {|E128184:Directory.Delete(Path.GetFullPath(path), true)|}; + {|E128184:Directory.Delete(Path.Combine(path), true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePathIsComputedByACallTheRuleCannotTrace() + { + return VerifyAsync(""" + using System.IO; + class C + { + static string Compute() => "x"; + + void M(string path) + { + Directory.Delete(Compute(), true); + Directory.Delete(Path.Combine(Compute(), "x"), true); + Directory.Delete(new string('a', 3), true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Follows_LocalAliasesAndCastsToTheirSource() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M(string path) + { + var a = path; + var b = (string)a; + {|E128184:Directory.Delete(b, true)|}; + + var temp = Path.GetTempPath(); + var child = temp; + Directory.Delete(child, true); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_DirectoryInfoCreationsAndLocals() + { + return VerifyAsync(""" + using System.IO; + class C + { + void M(string path) + { + {|E128184:new DirectoryInfo(path).Delete(true)|}; + new DirectoryInfo(Path.GetTempPath()).Delete(true); + new DirectoryInfo("data").Delete(true); + {|E128184:new DirectoryInfo("/data").Delete(true)|}; + + var info = new DirectoryInfo(path); + {|E128184:info.Delete(true)|}; + + var safe = new DirectoryInfo(Path.GetTempPath()); + safe.Delete(true); + safe.Delete(false); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_PrivateHelperParametersByTheirCallSites() + { + return VerifyAsync(""" + using System.IO; + class C + { + static string Compute() => "x"; + + void SafeOnly(string target) + { + Directory.Delete(target, true); + } + + void UnsafeAndSafe(string target) + { + {|E128184:Directory.Delete(target, true)|}; + } + + void WithUnknown(string target) + { + Directory.Delete(target, true); + } + + void UnknownThenUnsafe(string target) + { + {|E128184:Directory.Delete(target, true)|}; + } + + void Run(string path) + { + SafeOnly(Path.GetTempPath()); + SafeOnly(target: "data"); + UnsafeAndSafe(Path.GetTempPath()); + UnsafeAndSafe(path); + WithUnknown(Compute()); + WithUnknown(Path.GetTempPath()); + UnknownThenUnsafe(Compute()); + UnknownThenUnsafe(path); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_PrivateHelperWithoutCallersWithSelfCallsAndWithOverloads() + { + return VerifyAsync(""" + using System.IO; + class C + { + void NoCaller(string target) + { + {|E128184:Directory.Delete(target, true)|}; + } + + void Recursive(string target, bool again) + { + {|E128184:Directory.Delete(target, true)|}; + if (again) + { + Recursive(target, false); + } + } + + void Overloaded(string target) + { + Directory.Delete(target, true); + } + + void Overloaded(string target, int extra) + { + } + + void Run(string path) + { + Recursive(Path.GetTempPath(), true); + Overloaded(Path.GetTempPath()); + Overloaded(path, 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ParametersThatNoPrivateMethodOwns() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + public C(string path) + { + {|E128184:Directory.Delete(path, true)|}; + } + + internal void Internal(string path) + { + {|E128184:Directory.Delete(path, true)|}; + } + + string this[string key] + { + get + { + {|E128184:Directory.Delete(key, true)|}; + return key; + } + } + + void M() + { + void Local(string path) + { + {|E128184:Directory.Delete(path, true)|}; + } + + Action lambda = path => {|E128184:Directory.Delete(path, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_APrivateHelperOfATypeSplitAcrossFiles() + { + return AnalyzerTestRunner.VerifyAsync( + [ + """ + using System.IO; + partial class C + { + private void Clean(string target) + { + {|E128184:Directory.Delete(target, true)|}; + } + } + """, + """ + using System.IO; + partial class C + { + void Run() + { + Clean(Path.GetTempPath()); + } + } + """ + ]); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_PrivateHelperCalledFromAPartOfTheSameFile() + { + return VerifyAsync(""" + using System.IO; + partial class C + { + private void Clean(string target) + { + Directory.Delete(target, true); + } + } + + partial class C + { + void Run() + { + Clean(Path.GetTempPath()); + } + } + + record struct R(int Value) + { + private void Clean(string target) + { + Directory.Delete(target, true); + } + + void Run() + { + Clean(Path.GetTempPath()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public async Task Reports_TheDisplayNameOfEachPathShape() + { + await VerifyNameAsync( + """ + using System.IO; + class C + { + void M(string path) + { + {|#0:Directory.Delete(path, true)|}; + } + } + """, + "path"); + await VerifyNameAsync( + """ + using System.IO; + class C + { + string root = "x"; + + void M() + { + {|#0:Directory.Delete(root, true)|}; + } + } + """, + "root"); + await VerifyNameAsync( + """ + using System.IO; + class C + { + string Root { get; set; } = "x"; + + void M() + { + {|#0:Directory.Delete((string)Root, true)|}; + } + } + """, + "Root"); + await VerifyNameAsync( + """ + using System.IO; + class C + { + void M(string path) + { + {|#0:Directory.Delete(Path.Combine(path, "cache"), true)|}; + } + } + """, + "Path.Combine(path, \"cache\")"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnEnclosingGuardProvesTheStartsWithResult() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path, bool flag, string[] args) + { + var root = Path.GetTempPath(); + if (path.StartsWith(root, StringComparison.Ordinal) && flag) + { + Directory.Delete(path, true); + } + + if ((path.StartsWith(root, StringComparison.OrdinalIgnoreCase))) + { + Directory.Delete(path, true); + } + + if (path.StartsWith(value: root, comparisonType: StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (args[0].StartsWith(root, StringComparison.Ordinal)) + { + Directory.Delete(args[ 0 ], true); + } + + if (Path.GetFullPath(path).StartsWith(root, StringComparison.Ordinal)) + { + Directory.Delete(Path.GetFullPath(path), true); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheEnclosingGuardProvesTooLittle() + { + return VerifyAsync(""" + using System; + using System.IO; + class Probe + { + public bool StartsWith(string value, StringComparison comparison) => true; + } + + class C + { + bool Check(string value) => true; + + void M(string path, string other, bool flag, Probe probe, StringComparison comparison, string[] args) + { + var root = Path.GetTempPath(); + + if (path.StartsWith(root, StringComparison.Ordinal) || flag) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(root, StringComparison.Ordinal)) + { + } + else + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (other.StartsWith(root, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (probe.StartsWith(root, comparison)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (Check(path)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheEnclosingGuardComparesLoosely() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path, string other, StringComparison comparison, string[] args) + { + var root = Path.GetTempPath(); + + if (path.StartsWith(root, comparison)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith('/')) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (args[0].StartsWith(root, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(root, StringComparison.Ordinal)) + { + path = other; + {|E128184:Directory.Delete(path, true)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePrecedingStatementExitsUnlessTheStartsWithResultIsTrue() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path, bool flag, int count) + { + var root = Path.GetTempPath(); + + if (!(path.StartsWith(root, StringComparison.Ordinal)) || flag) + { + throw new InvalidOperationException(); + } + + Directory.Delete(path, true); + + if (path.StartsWith(root, StringComparison.Ordinal)) + { + count++; + --count; + ++count; + count--; + Directory.Delete(path, true); + } + + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + if (flag) + { + Directory.Delete(path, true); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenThePrecedingGuardProvesTooLittle() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void M(string path, string other, bool flag) + { + var root = Path.GetTempPath(); + + if (path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + {|E128184:Directory.Delete(path, true)|}; + + if (!path.StartsWith(root, StringComparison.Ordinal) && flag) + { + return; + } + + {|E128184:Directory.Delete(path, true)|}; + + if (!!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + {|E128184:Directory.Delete(path, true)|}; + + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + else + { + flag = true; + } + + {|E128184:Directory.Delete(path, true)|}; + + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + flag = !flag; + {|E128184:Directory.Delete(path, true)|}; + + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + path = other; + {|E128184:Directory.Delete(path, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenNoStatementDirectlyPrecedesTheDeleteWithAGuard() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + string Holder + { + get + { + {|E128184:Directory.Delete(Holder, true)|}; + return string.Empty; + } + } + + void M(string path, bool flag) + { + {|E128184:Directory.Delete(path, true)|}; + } + + void FarFromTheGuard(string path, bool flag) + { + var root = Path.GetTempPath(); + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + var x = 1; + {|E128184:Directory.Delete(path, true)|}; + } + + void Nested(string path, bool flag) + { + var root = Path.GetTempPath(); + if (!path.StartsWith(root, StringComparison.Ordinal)) + { + return; + } + + if (flag) + { + Directory.Delete(path, true); + } + + Action inner = () => {|E128184:Directory.Delete(path, true)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardRootIsBoundedByASeparator() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + const string Fixed = "data/"; + const string Bare = "data"; + + void M(string path) + { + if (path.StartsWith(Fixed, StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (path.StartsWith(Bare + "/", StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (path.StartsWith(Path.GetTempPath() + "/", StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (path.StartsWith(Path.GetTempPath() + Path.AltDirectorySeparatorChar, StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (path.StartsWith(Path.GetTempPath() + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + + if (path.StartsWith((Fixed), StringComparison.Ordinal)) + { + Directory.Delete(path, true); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardRootIsNotBoundedOrNotSafe() + { + return VerifyAsync(""" + using System; + using System.IO; + class Other + { + public const char DirectorySeparatorChar = '/'; + } + + class C + { + const string Bare = "data"; + void M(string path, char sep) + { + if (path.StartsWith(Bare, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Path.GetFullPath(Path.GetTempPath()), StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Path.GetTempPath() + sep, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Path.GetTempPath() + Path.PathSeparator, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Path.GetTempPath() + Other.DirectorySeparatorChar, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Path.GetTempPath() + "x", StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardRootIsComputedAtRunTime() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + static readonly string Dynamic = Environment.GetEnvironmentVariable("ROOT") ?? "x/"; + + static string Compute() => "x/"; + + void M(string path, string param) + { + string uninitialized; + uninitialized = "x/"; + + if (path.StartsWith(param + "/", StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Dynamic, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(Compute(), StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + + if (path.StartsWith(uninitialized, StringComparison.Ordinal)) + { + {|E128184:Directory.Delete(path, true)|}; + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/RuntimeRegexToGeneratedBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/RuntimeRegexToGeneratedBranchCoverageTests.cs new file mode 100644 index 00000000..6e23d949 --- /dev/null +++ b/tests/E128.Analyzers.Tests/RuntimeRegexToGeneratedBranchCoverageTests.cs @@ -0,0 +1,196 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class RuntimeRegexToGeneratedBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + // The fixed code needs the GeneratedRegex source generator, which the test harness does not run. + return new CSharpCodeFixTest< + RuntimeRegexToGeneratedAnalyzer, + RuntimeRegexToGeneratedCodeFixProvider, + DefaultVerifier> + { + TestCode = source, + FixedCode = fixedCode, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + CompilerDiagnostics = CompilerDiagnostics.None, + }.RunAsync(TestContext.Current.CancellationToken); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync( + source, + behaviors: CodeFixTestBehaviors.None); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_BeforeCSharp13() + { + return AnalyzerTestRunner.VerifyAsync( + """ + using System.Text.RegularExpressions; + class C + { + private static readonly Regex Digits = new Regex("[0-9]+"); + } + """, + options: new AnalyzerTestOptions { LanguageVersion = LanguageVersion.CSharp12 }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheFieldShapeCannotBecomeAGeneratedProperty() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Text.RegularExpressions; + class C + { + private readonly Regex _instance = new Regex("[0-9]+"); + + private static Regex _mutable = new Regex("[0-9]+"); + + private static readonly Regex First = new Regex("a"), Second = new Regex("b"); + + private static readonly object NotRegex = new object(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheConstructionIsNotAPlainPatternLiteral() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Text.RegularExpressions; + class C + { + private const string Pattern = "[0-9]+"; + + private static readonly Regex FromConstant = new Regex(Pattern); + + private static readonly Regex Interpolated = new Regex($"[{Pattern}]"); + + private static readonly Regex WithTimeout = new Regex("a", RegexOptions.None, TimeSpan.FromSeconds(1)); + + private static readonly Regex Escaped = Escape(); + + private static readonly Regex Implicit = new("[0-9]+"); + + private static Regex Escape() => new Regex("a"); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Reports_ForStructAndRecordFields() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Text.RegularExpressions; + struct S + { + {|E128123:public static readonly Regex Digits = new Regex("[0-9]+");|} + } + + record R + { + {|E128123:internal static readonly Regex Letters = new Regex("[a-z]+");|} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsAnAlreadyPartialTypeAndOtherFlags() + { + return VerifyFixAsync( + """ + using System.Text.RegularExpressions; + partial class C + { + {|E128123:public static readonly Regex Digits = new Regex("[0-9]+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);|} + } + """, + """ + using System.Text.RegularExpressions; + partial class C + { + [System.Text.RegularExpressions.GeneratedRegex("[0-9]+", RegexOptions.IgnoreCase | RegexOptions.Multiline, matchTimeoutMilliseconds: System.Threading.Timeout.Infinite)] + public static partial Regex Digits { get; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ConvertsAFieldOfAStruct() + { + return VerifyFixAsync( + """ + using System.Text.RegularExpressions; + struct S + { + {|E128123:internal static readonly Regex Digits = new Regex("[0-9]+");|} + } + """, + """ + using System.Text.RegularExpressions; + partial struct S + { + [System.Text.RegularExpressions.GeneratedRegex("[0-9]+", RegexOptions.None, matchTimeoutMilliseconds: System.Threading.Timeout.Infinite)] + internal static partial Regex Digits { get; } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheFieldAlreadyHasAnAttribute() + { + return VerifyNoFixAsync(""" + using System; + using System.Text.RegularExpressions; + class C + { + {|E128123:[Obsolete] + private static readonly Regex Digits = new Regex("[0-9]+");|} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheOptionsAreNotAPlainFlagList() + { + return VerifyNoFixAsync(""" + using System.Text.RegularExpressions; + class C + { + {|E128123:private static readonly Regex Digits = new Regex("[0-9]+", (RegexOptions)1 | RegexOptions.None);|} + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheOptionsUseAnotherOperator() + { + return VerifyNoFixAsync(""" + using System.Text.RegularExpressions; + class C + { + {|E128123:private static readonly Regex Digits = new Regex("[0-9]+", RegexOptions.IgnoreCase & RegexOptions.Compiled);|} + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SaveChangesInLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SaveChangesInLoopBranchCoverageTests.cs new file mode 100644 index 00000000..0a05fc83 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SaveChangesInLoopBranchCoverageTests.cs @@ -0,0 +1,174 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SaveChangesInLoopBranchCoverageTests +{ + private const string EfStub = """ + namespace Microsoft.EntityFrameworkCore + { + public class DbContext + { + public virtual int SaveChanges() => 0; + } + + public class DbSet + { + } + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code + "\n" + EfStub); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenADerivedContextCallsSaveChangesWithoutAReceiver() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + class AppContext : DbContext + { + void Run(List rows) + { + foreach (var row in rows) + { + {|E128185:SaveChanges()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenSaveChangesIsADelegateField() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + class Holder + { + public Func SaveChanges = () => 0; + } + + class C + { + void M(Holder holder, List rows, DbContext db) + { + foreach (var row in rows) + { + _ = holder.SaveChanges(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAnExtensionMethodTakesAContextReceiver() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + static class Extensions + { + public static int SaveChanges(this DbContext context, int retries) => retries; + } + + class C + { + void M(DbContext db, List rows) + { + foreach (var row in rows) + { + {|E128185:db.SaveChanges(3)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_WhenAnExtensionMethodTakesAnEntityFrameworkTypeThatIsNotAContext() + { + return VerifyAsync(""" + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + static class Extensions + { + public static int SaveChanges(this DbSet set) => 0; + } + + class C + { + void M(DbSet set, List rows) + { + foreach (var row in rows) + { + {|E128185:set.SaveChanges()|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnExtensionMethodAndItsReceiverAreNotEntityFramework() + { + return VerifyAsync(""" + using System.Collections.Generic; + + static class Extensions + { + public static int SaveChanges(this List source) => 0; + } + + class C + { + void M(List rows) + { + foreach (var row in rows) + { + _ = rows.SaveChanges(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNameIsNotAnInvocationOfAMemberOrName() + { + return VerifyAsync(""" + using System; + using System.Collections.Generic; + using Microsoft.EntityFrameworkCore; + + class C + { + void M(Func> factory, List rows, DbContext db) + { + foreach (var row in rows) + { + _ = factory()(); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseBranchCoverageTests.cs new file mode 100644 index 00000000..b14956db --- /dev/null +++ b/tests/E128.Analyzers.Tests/SemaphoreSlimReleaseBranchCoverageTests.cs @@ -0,0 +1,576 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the wait and release pairing shapes the main semaphore suite leaves out. +/// +public sealed class SemaphoreSlimReleaseBranchCoverageTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + + """; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(Header + source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitTakesACancellationToken() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M(CancellationToken token) + { + {|E128175:_sem.Wait(token)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsAFieldInitializer() + { + return VerifyAsync(""" + class C + { + private static readonly SemaphoreSlim Sem = new(1, 1); + + private static readonly Task Pending = {|E128175:Sem.WaitAsync()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsAssignedToAVariable() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + Task pending = {|E128175:_sem.WaitAsync()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsAnEmbeddedStatement() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M(bool flag) + { + if (flag) + {|E128175:_sem.Wait()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsInsideAnExpressionBodiedLambda() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + Task.Run(() => {|E128175:_sem.Wait()|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsInsideABlockLambda() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + Task.Run(() => + { + {|E128175:_sem.Wait()|}; + }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsInsideALocalFunction_AndTheOuterTryReleases() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + try + { + void Inner() + { + {|E128175:_sem.Wait()|}; + } + + Inner(); + } + finally + { + _sem.Release(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheWaitIsAnExpressionBodiedLocalFunction() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + void Inner() => {|E128175:_sem.Wait()|}; + Inner(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnEnclosingTryHasOnlyACatch() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + try + { + {|E128175:_sem.Wait()|}; + } + catch (InvalidOperationException) + { + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAThrowFollowsTheWait() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + {|E128175:_sem.Wait()|}; + throw new InvalidOperationException(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAGotoFollowsTheWait() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + {|E128175:_sem.Wait()|}; + goto Done; + Done: + return; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAYieldFollowsTheWait() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + IEnumerable M() + { + {|E128175:_sem.Wait()|}; + yield return 1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheOnlyReleaseComesAfterTheExit() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + int M(bool flag) + { + {|E128175:_sem.Wait()|}; + if (flag) + { + return 1; + } + else + { + _sem.Release(); + } + + return 0; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnotherCallPrecedesTheExit() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + int M(bool flag) + { + {|E128175:_sem.Wait()|}; + if (flag) + { + Console.WriteLine("exit"); + return 1; + } + + return 0; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALaterLambdaReturnsBeforeThePairedTry() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + _sem.Wait(); + Func compute = () => + { + return 1; + }; + int local = 0; + try + { + local = compute(); + } + finally + { + _sem.Release(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsCalledWithoutAReceiver() + { + return VerifyAsync(""" + class MySemaphore : SemaphoreSlim + { + public MySemaphore() + : base(1) + { + } + + void M() + { + Wait(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitReceiverHasNoSymbol() + { + return VerifyAsync(""" + class C + { + void M(SemaphoreSlim first, SemaphoreSlim second) + { + (first ?? second).Wait(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallDoesNotBind() + { + return VerifyAsync( + """ + class C + { + void M(SemaphoreSlim sem) + { + sem.Wait(unknown); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyReleasesThroughAnUnboundCall() + { + return VerifyAsync( + """ + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M(dynamic other) + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + other.Release(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyReleasesThroughAnUnqualifiedCall() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void Release() + { + } + + void M() + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + Release(); + _sem.Dispose(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyReleasesAReceiverWithoutASymbol() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M(SemaphoreSlim other) + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + (other ?? _sem).Release(); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyReleasesInsideALambda() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + Task.Run(() => _sem.Release()); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFinallyReleasesInsideALocalFunction() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + void Give() => _sem.Release(); + } + } + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("var skipped = flag ? _sem.Release() : 0;")] + [InlineData("switch (count) { case 1: _sem.Release(); break; }")] + [InlineData("for (var i = 0; i < count; i++) { _sem.Release(); }")] + [InlineData("foreach (var i in new[] { 1 }) { _sem.Release(); }")] + [InlineData("while (flag) { _sem.Release(); flag = false; }")] + [InlineData("do { _sem.Release(); } while (flag);")] + public Task Reports_WhenTheReleaseInTheFinallyIsConditional(string releaseStatement) + { + return VerifyAsync($$""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M(bool flag, int count) + { + {|E128175:_sem.Wait()|}; + try + { + Console.WriteLine(); + } + finally + { + {{releaseStatement}} + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReleaseIsAnUnconditionalNestedBlock() + { + return VerifyAsync(""" + class C + { + private readonly SemaphoreSlim _sem = new(1, 1); + + void M() + { + _sem.Wait(); + try + { + Console.WriteLine(); + } + finally + { + { + _sem.Release(); + } + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SensitiveLogArgumentBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SensitiveLogArgumentBranchCoverageTests.cs new file mode 100644 index 00000000..4fb3e6eb --- /dev/null +++ b/tests/E128.Analyzers.Tests/SensitiveLogArgumentBranchCoverageTests.cs @@ -0,0 +1,167 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SensitiveLogArgumentBranchCoverageTests +{ + private static readonly ReferenceAssemblies Net100WithLogging = ReferenceAssemblies.Net.Net100 + .AddPackages([new PackageIdentity("Microsoft.Extensions.Logging.Abstractions", "10.0.13")]); + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions { References = Net100WithLogging }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ElementsOfTheParamsArrayAtTheArgumentOrTheElement() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string password, string user, string secret) + { + logger.LogInformation("a {A}", {|E128166:(object)password|}); + logger.LogInformation("b {A}", {|E128166:(password)|}); + logger.LogInformation("c {A}", new object[] { {|E128166:password|}, user }); + logger.LogInformation("d {A} {B}", user, {|E128166:secret|}); + logger.LogInformation("e {A}", new object[] { {|E128166:(secret)|} }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_NamesThroughCallsAccessesAndCasts() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class Session + { + public string? Token { get; set; } + + public string GetPassword() => ""; + } + + class C + { + void M(ILogger logger, string? password, Session? session) + { + logger.LogInformation("a {A}", {|E128166:password.ToString()|}); + logger.LogInformation("b {A}", {|E128166:password?.ToString()|}); + logger.LogInformation("c {A}", {|E128166:password!.Trim()|}); + logger.LogInformation("d {A}", {|E128166:session?.Token|}); + logger.LogInformation("e {A}", {|E128166:session?.Token?.Trim()|}); + logger.LogInformation("f {A}", {|E128166:password as string|}); + logger.LogInformation("g {A}", {|E128166:(string?)password|}); + logger.LogInformation("h {A}", {|E128166:password|}!); + logger.LogInformation("i {A}", session!.GetPassword()); + logger.LogInformation("j {A}", session.GetPassword().Trim('x')); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNameShowsMetadataOrACancellationToken() + { + return VerifyAsync(""" + using System.Threading; + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string passwordName, string tokenType, int passwordCount, int secretLength, string tokenExpiry, string secretHeader, string tokenId, string passwordHint, CancellationToken cancellationToken, string processNumber, string cancellation_secret) + { + logger.LogInformation("a {A} {B} {C} {D}", passwordName, tokenType, passwordCount, secretLength); + logger.LogInformation("b {A} {B} {C} {D}", tokenExpiry, secretHeader, tokenId, passwordHint); + logger.LogInformation("c {A} {B} {C}", cancellationToken, processNumber, cancellation_secret); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ShortSensitiveWordsOnlyAsWholeWords() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string pwd, string user_ssn, string userSsn, string processNumber, string classNumber, string ssnumber) + { + logger.LogInformation("a {A}", {|E128166:pwd|}); + logger.LogInformation("b {A}", {|E128166:user_ssn|}); + logger.LogInformation("c {A}", {|E128166:userSsn|}); + logger.LogInformation("d {A}", processNumber); + logger.LogInformation("e {A}", classNumber); + logger.LogInformation("f {A}", ssnumber); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Handles_TheGenericLogCallAndTemplateStrings() + { + return VerifyAsync(""" + using System; + using Microsoft.Extensions.Logging; + class C + { + void M(ILogger logger, string password, string message, Exception exception) + { + logger.LogInformation(password); + logger.LogError(exception, "failed {A}", {|E128166:password|}); + logger.LogInformation(message); + logger.LogInformation("plain"); + logger.LogInformation({|E128166:$"value {password}"|}); + logger.LogInformation($"value {message}"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_GeneratedLoggerMessageMethodsThroughEitherPartialPart() + { + return VerifyAsync(""" + using Microsoft.Extensions.Logging; + partial class C + { + [LoggerMessage(1, LogLevel.Information, "first")] + static partial void LogFirst(ILogger logger, string password); + + static partial void LogFirst(ILogger logger, string password) { } + + static partial void LogSecond(ILogger logger, string password); + + [LoggerMessage(2, LogLevel.Information, "second")] + static partial void LogSecond(ILogger logger, string password) { } + + [LoggerMessage(3, LogLevel.Information, "third")] + static partial void LogThird(ILogger logger, string user, int count = 0); + + static partial void LogThird(ILogger logger, string user, int count) { } + + void M(ILogger logger, string password, string user) + { + LogFirst(logger, {|E128166:password|}); + LogSecond(logger, {|E128166:password|}); + LogThird(logger, user); + LogThird(logger, {|E128166:password|}); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SequenceEqualLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SequenceEqualLoopBranchCoverageTests.cs new file mode 100644 index 00000000..1acff7ed --- /dev/null +++ b/tests/E128.Analyzers.Tests/SequenceEqualLoopBranchCoverageTests.cs @@ -0,0 +1,412 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SequenceEqualLoopBranchCoverageTests +{ + private const string Enums = """ + enum Color : byte + { + Red, + Green, + } + + """; + + private static Task VerifyAsync(string parameters, string body) + { + var code = Enums + + "class C\n{\n bool M(" + parameters + ")\n {\n" + + body + + " }\n}\n"; + return AnalyzerTestRunner.VerifyAsync(code); + } + + private static string Loop(string markup, string loopHeader = "for (int i = 0; i < left.Length; i++)", string comparison = "left[i] != right[i]") + { + return $$""" + if (left.Length != right.Length) + { + return false; + } + + {{markup}}{{loopHeader}} + { + if ({{comparison}}) + { + return false; + } + }{{(markup.Length > 0 ? "|}" : string.Empty)}} + return true; + + """; + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("bool")] + [InlineData("char")] + [InlineData("sbyte")] + [InlineData("byte")] + [InlineData("short")] + [InlineData("ushort")] + [InlineData("int")] + [InlineData("uint")] + [InlineData("long")] + [InlineData("ulong")] + [InlineData("Color")] + public Task Reports_ForIntegralAndEnumElements(string element) + { + return VerifyAsync(element + "[] left, " + element + "[] right", Loop("{|E128121:")); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("string")] + [InlineData("object")] + [InlineData("decimal")] + [InlineData("float")] + [InlineData("double")] + public Task Silent_ForOtherElementTypes(string element) + { + return VerifyAsync(element + "[] left, " + element + "[] right", Loop(string.Empty)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheLoopBoundIsTheRightArray() + { + return VerifyAsync( + "int[] left, int[] right", + Loop("{|E128121:", "for (int i = 0; i < right.Length; i++)")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardComparesTheLengthsInTheOtherOrder() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (right.Length != left.Length) return false; + + {|E128121:for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + }|} + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardComparesOtherArrays() + { + return VerifyAsync( + "int[] left, int[] right, int[] other", + """ + if (other.Length != right.Length) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardDoesNotReturnFalse() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) + { + return true; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardBodyDoesMoreThanReturn() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) + { + left = right; + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardHasAnElseBranch() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) + { + return false; + } + else + { + left = right; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardComparesSomethingOtherThanLengths() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != 3) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNothingFollowsTheLoopOrItDoesNotReturnTrue() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + + return false; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopIsTheLastStatement() + { + return AnalyzerTestRunner.VerifyAsync( + """ + class C + { + void M(int[] left, int[] right) + { + if (left.Length != right.Length) + { + return; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return; + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheComparisonIsNotNotEquals() + { + return VerifyAsync( + "int[] left, int[] right", + Loop(string.Empty, comparison: "left[i] == right[i]")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnOperandIsNotAnElementOfTheLoopIndex() + { + return VerifyAsync( + "int[] left, int[] right, int[,] grid", + Loop(string.Empty, comparison: "left[i] != 0") + + Loop(string.Empty, comparison: "left[i + 1] != right[i]") + + Loop(string.Empty, comparison: "grid[i, 0] != right[i]") + + Loop(string.Empty, comparison: "left[0] != right[i]")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArraysHaveDifferentElementTypes() + { + return VerifyAsync("int[] left, long[] right", Loop(string.Empty)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheOperandsAreStringsOrMultiDimensional() + { + return VerifyAsync( + "string left, string right", + Loop(string.Empty)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopBodyIsNotASingleIfReturn() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + if (left[i] != right[i]) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return true; + } + } + + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + + continue; + } + + for (int i = 0; i < left.Length; i++) + { + _ = left[i]; + } + + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLoopIsNotDirectlyInABlock() + { + return VerifyAsync( + "int[] left, int[] right, bool flag", + """ + if (flag) + for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + } + + return true; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardIsAnUnbracedReturn() + { + return VerifyAsync( + "int[] left, int[] right", + """ + if (left.Length != right.Length) return false; + {|E128121:for (int i = 0; i < left.Length; i++) + { + if (left[i] != right[i]) + { + return false; + } + }|} + return true; + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageTests.cs new file mode 100644 index 00000000..869ae50c --- /dev/null +++ b/tests/E128.Analyzers.Tests/SequentialRenameFixAllProviderBranchCoverageTests.cs @@ -0,0 +1,161 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using E128.Analyzers.Style; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Microsoft.CodeAnalysis.Text; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SequentialRenameFixAllProviderBranchCoverageTests +{ + private const string Source = "class C { int a; int b; }"; + + private static (Solution Solution, DocumentId Id, ProjectId ProjectId) CreateSolution(AdhocWorkspace workspace) + { + var project = workspace.AddProject("P", LanguageNames.CSharp) + .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); + var document = project.AddDocument("Test.cs", Source); + return (document.Project.Solution, document.Id, project.Id); + } + + private static async Task RenameAsync(Solution solution, DocumentId id, params SequentialRenameFixAllProvider.RenameInfo[] renames) + { + var result = await SequentialRenameFixAllProvider.ApplyRenamesSequentiallyAsync( + solution, + [.. renames], + CancellationToken.None); + var text = await result.GetDocument(id)!.GetTextAsync(TestContext.Current.CancellationToken); + return text.ToString(); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRenames_ChangesNothingForAnEmptyList() + { + using var workspace = new AdhocWorkspace(); + var (solution, id, _) = CreateSolution(workspace); + Assert.Equal(Source, await RenameAsync(solution, id)); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRenames_SkipsADocumentThatIsNotInTheSolution() + { + using var workspace = new AdhocWorkspace(); + var (solution, id, projectId) = CreateSolution(workspace); + var missing = DocumentId.CreateNewId(projectId); + + var text = await RenameAsync(solution, id, new SequentialRenameFixAllProvider.RenameInfo(missing, new TextSpan(0, 1), "a", "alpha")); + + Assert.Equal(Source, text); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRenames_SkipsASymbolWhoseNameChanged() + { + using var workspace = new AdhocWorkspace(); + var (solution, id, _) = CreateSolution(workspace); + var start = Source.IndexOf("int a;", StringComparison.Ordinal) + 4; + + var text = await RenameAsync(solution, id, new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(start, 1), "other", "alpha")); + + Assert.Equal(Source, text); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRenames_SkipsASpanThatHoldsNoSymbol() + { + using var workspace = new AdhocWorkspace(); + var (solution, id, _) = CreateSolution(workspace); + var start = Source.IndexOf("int a;", StringComparison.Ordinal) + 5; + + var text = await RenameAsync(solution, id, new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(start, 1), "a", "alpha")); + + Assert.Equal(Source, text); + } + + [Fact] + [Trait("Category", "CI")] + public async Task ApplyRenames_AppliesEveryValidRenameInOrder() + { + using var workspace = new AdhocWorkspace(); + var (solution, id, _) = CreateSolution(workspace); + var aStart = Source.IndexOf("int a;", StringComparison.Ordinal) + 4; + var bStart = Source.IndexOf("int b;", StringComparison.Ordinal) + 4; + + var text = await RenameAsync( + solution, + id, + new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(bStart, 1), "b", "beta"), + new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(aStart, 1), "a", "alpha")); + + Assert.Equal("class C { int alpha; int beta; }", text); + } + + [Fact] + [Trait("Category", "CI")] + public void RenameInfo_ComparesAllFourParts() + { + var id = DocumentId.CreateNewId(ProjectId.CreateNewId()); + var other = DocumentId.CreateNewId(ProjectId.CreateNewId()); + var baseline = new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "a", "b"); + + Assert.True(baseline == new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "a", "b")); + Assert.True(baseline != new SequentialRenameFixAllProvider.RenameInfo(other, new TextSpan(1, 2), "a", "b")); + Assert.True(baseline != new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 3), "a", "b")); + Assert.True(baseline != new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "x", "b")); + Assert.True(baseline != new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "a", "y")); + } + + [Fact] + [Trait("Category", "CI")] + public void RenameInfo_ObjectEqualityAndHashFollowTheValue() + { + var id = DocumentId.CreateNewId(ProjectId.CreateNewId()); + var first = new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "a", "b"); + object boxed = new SequentialRenameFixAllProvider.RenameInfo(id, new TextSpan(1, 2), "a", "b"); + + Assert.True(first.Equals(boxed)); + Assert.False(first.Equals("text")); + Assert.False(first.Equals(null)); + Assert.Equal(first.GetHashCode(), boxed.GetHashCode()); + Assert.Equal("a to b", first.ToString()); + } + + [Fact] + [Trait("Category", "CI")] + public Task FixAll_RenamesEveryViolationInOneDocument() + { + return new CSharpCodeFixTest + { + TestCode = """ + class C + { + private int {|IDE1006:first|} = 0; + private int {|IDE1006:second|} = 0; + private int {|IDE1006:third|} = 0; + + public int Sum() => first + second + third; + } + """, + FixedCode = """ + class C + { + private int _first = 0; + private int _second = 0; + private int _third = 0; + + public int Sum() => _first + _second + _third; + } + """, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + NumberOfFixAllIterations = 1 + }.RunAsync(TestContext.Current.CancellationToken); + } +} diff --git a/tests/E128.Analyzers.Tests/SortInLoopBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SortInLoopBranchCoverageTests.cs new file mode 100644 index 00000000..0884ea0e --- /dev/null +++ b/tests/E128.Analyzers.Tests/SortInLoopBranchCoverageTests.cs @@ -0,0 +1,176 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SortInLoopBranchCoverageTests +{ + private static Task VerifyAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(code, expected: null, options: options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fires_ForEveryThenByStageInALoop() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + class C + { + void M(List items, int[] ids) + { + foreach (var id in ids) + { + _ = {|E128068:{|E128068:items.OrderBy(x => x)|}.ThenBy(x => x)|}; + _ = {|E128068:{|E128068:items.OrderByDescending(x => x)|}.ThenByDescending(x => x)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForSortMethodsThatAreNotEnumerableOrListOrArraySorts() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + + class Custom + { + public void Sort() + { + } + + public Custom OrderBy(System.Func key) => this; + } + + class C + { + void M(Custom custom, IQueryable query, int[] ids) + { + foreach (var id in ids) + { + custom.Sort(); + _ = custom.OrderBy(x => x); + _ = query.OrderBy(x => x); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSortCallDoesNotBind() + { + return VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(List items, int[] ids) + { + foreach (var id in ids) + { + items.Sort(1, 2, 3, 4, 5); + } + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenInsertOrRemoveAtZeroTargetsAnotherType() + { + return VerifyAsync(""" + using System.Text; + class C + { + void M(StringBuilder builder, string text, int[] ids) + { + foreach (var id in ids) + { + _ = builder.Insert(0, "x"); + _ = builder.Remove(0, 1); + _ = text.Insert(0, "x"); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheShiftIndexIsNotTheLiteralZero() + { + return VerifyAsync(""" + using System.Collections.Generic; + class C + { + const int Zero = 0; + + void M(List items, int[] ids) + { + foreach (var id in ids) + { + items.Insert(Zero, id); + items.Insert(id, id); + items.RemoveAt(Zero); + items.RemoveAt(id); + items.RemoveAt(0L > 1 ? 1 : 2); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenInsertOrRemoveAtHasNoArguments() + { + return VerifyAsync( + """ + using System.Collections.Generic; + class C + { + void M(List items, int[] ids) + { + foreach (var id in ids) + { + items.Insert(); + items.RemoveAt(); + } + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallHasNoReceiver() + { + return VerifyAsync(""" + using System.Collections.Generic; + class Bag : List + { + void Run(int[] ids) + { + foreach (var id in ids) + { + Sort(); + Insert(0, id); + } + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StackAllocSafetyBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StackAllocSafetyBranchCoverageTests.cs new file mode 100644 index 00000000..00e1b4d9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StackAllocSafetyBranchCoverageTests.cs @@ -0,0 +1,170 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StackAllocSafetyBranchCoverageTests +{ + private static Task VerifyAsync(string body, bool allowUnsafe = false) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nclass C\n{\n void M(int length, int count, bool flag)\n {\n" + body + "\n }\n}\n", + options: new AnalyzerTestOptions { AllowUnsafe = allowUnsafe }); + } + + private static Task VerifyNoFixAsync(string code) + { + var test = new CSharpCodeFixTest + { + TestCode = code, + FixedCode = code, + ReferenceAssemblies = ReferenceAssemblies.Net.Net100, + }; + test.SolutionTransforms.Add(CodeFixTestRunner.AllowUnsafe); + + return test.RunAsync(TestContext.Current.CancellationToken); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("foreach (var item in new[] { 1 }) { Span buffer = {|E128109:stackalloc byte[16]|}; }")] + [InlineData("while (flag) { Span buffer = {|E128109:stackalloc byte[16]|}; }")] + [InlineData("do { Span buffer = {|E128109:stackalloc byte[16]|}; } while (flag);")] + public Task Reports_InsideEveryLoopKind(string body) + { + return VerifyAsync(body); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForALambdaInsideALoopWithASmallBuffer() + { + return VerifyAsync(""" + for (var i = 0; i < count; i++) + { + Action action = () => { Span buffer = stackalloc byte[16]; }; + action(); + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("int", "257", "1028")] + [InlineData("char", "513", "1026")] + [InlineData("long", "129", "1032")] + [InlineData("byte", "1025", "1025")] + public Task Reports_WhenTheConstantSizeInBytesExceedsTheLimit(string element, string count, string bytes) + { + return AnalyzerTestRunner.VerifyAsync( + $$""" + using System; + class C + { + void M() + { + Span<{{element}}> buffer = {|#0:stackalloc {{element}}[{{count}}]|}; + } + } + """, + new DiagnosticResult(StackAllocSafetyAnalyzer.DiagnosticId, Microsoft.CodeAnalysis.DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments($"its size is {bytes} bytes, above the 1024 byte limit")); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInitializerStackAllocWithoutALength() + { + return VerifyAsync(""" + Span sized = stackalloc int[] { 1, 2, 3 }; + Span implicitly = stackalloc[] { 1, 2, 3 }; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAConditionalExpressionGuardsTheLength() + { + return VerifyAsync(""" + Span buffer = length <= 256 ? stackalloc byte[length] : new byte[length]; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardSitsOutsideTheLambda() + { + return VerifyAsync(""" + if (length <= 256) + { + Action action = () => { Span buffer = {|E128109:stackalloc byte[length]|}; }; + action(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnIfStatementGuardsAnExpressionOverTheLength() + { + return VerifyAsync(""" + if (length * 2 <= 256) + { + Span buffer = stackalloc byte[length * 2]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDeclarationHoldsTwoPointers() + { + return VerifyNoFixAsync(""" + unsafe class C + { + void M() + { + int* first = {|E128109:stackalloc int[4]|}, second = null; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenThePointerIsUsedBeyondElementAccess() + { + return VerifyNoFixAsync(""" + unsafe class C + { + static void Use(int* pointer) { } + + void M() + { + int* buffer = {|E128109:stackalloc int[4]|}; + Use(buffer); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnotherNameUsesElementAccessOnADifferentVariable() + { + return VerifyNoFixAsync(""" + unsafe class C + { + void M(int* other) + { + int* buffer = {|E128109:stackalloc int[4]|}; + other[0] = buffer[1] + (buffer + 1)[0]; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StaleReferenceAssembliesAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StaleReferenceAssembliesAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..8177f03c --- /dev/null +++ b/tests/E128.Analyzers.Tests/StaleReferenceAssembliesAnalyzerBranchCoverageTests.cs @@ -0,0 +1,70 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StaleReferenceAssembliesAnalyzerBranchCoverageTests +{ + private const string Stubs = """ + class ReferenceAssemblies + { + public static class Net + { + public static int Net80 => 80; + public static int Net100 => 100; + public static int Unknown => 0; + public static int Net90Field; + public static int Net90() => 90; + } + + public static class Other + { + public static int Net80 => 80; + } + } + + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnUnknownVersionAndAnUpToDateVersion() + { + return VerifyAsync(""" + class C + { + int M() => ReferenceAssemblies.Net.Unknown + ReferenceAssemblies.Net.Net100; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnOuterNameOrMiddleNameThatDoesNotMatch() + { + return VerifyAsync(""" + class C + { + int M() => ReferenceAssemblies.Other.Net80; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAFieldOrMethodNamedLikeAVersion() + { + return VerifyAsync(""" + class C + { + int M() => ReferenceAssemblies.Net.Net90() + ReferenceAssemblies.Net.Net90Field; + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/StatementExitsBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StatementExitsBranchCoverageTests.cs new file mode 100644 index 00000000..fc8149aa --- /dev/null +++ b/tests/E128.Analyzers.Tests/StatementExitsBranchCoverageTests.cs @@ -0,0 +1,30 @@ +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StatementExitsBranchCoverageTests +{ + [Theory] + [Trait("Category", "CI")] + [InlineData("return;", true)] + [InlineData("throw new System.Exception();", true)] + [InlineData("continue;", true)] + [InlineData("break;", true)] + [InlineData("{ }", false)] + [InlineData("{ Use(); }", false)] + [InlineData("{ Use(); return; }", true)] + [InlineData("{ { return; } }", true)] + [InlineData("{ return; Use(); }", false)] + [InlineData("if (b) return;", false)] + [InlineData("if (b) return; else Use();", false)] + [InlineData("if (b) Use(); else return;", false)] + [InlineData("if (b) return; else break;", true)] + [InlineData("if (b) { return; } else if (c) { continue; } else { throw new System.Exception(); }", true)] + [InlineData("if (b) { return; } else if (c) { continue; }", false)] + [InlineData("Use();", false)] + public void EndsInExit_ReadsBlocksAndIfBranches(string statement, bool expected) + { + Assert.Equal(expected, StatementExits.EndsInExit(SyntaxFactory.ParseStatement(statement))); + } +} diff --git a/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..9ba02803 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StaticNumericIncrementCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,160 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StaticNumericIncrementCodeFixProviderBranchCoverageTests +{ + private static Microsoft.CodeAnalysis.Testing.DiagnosticResult Remaining(int line, int column, int endLine, int endColumn) + { + return new Microsoft.CodeAnalysis.Testing.DiagnosticResult("E128087", Microsoft.CodeAnalysis.DiagnosticSeverity.Warning) + .WithSpan(line, column, endLine, endColumn) + .WithArguments("_value", "++"); + } + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAPrefixIncrementWithInterlocked() + { + return VerifyFixAsync( + """ + using System.Threading; + + class C + { + private static int _counter; + void M() { {|E128087:++|}_counter; } + } + """, + """ + using System.Threading; + + class C + { + private static int _counter; + void M() { _ = Interlocked.Increment(ref _counter); } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAPostfixDecrementWithInterlocked() + { + return VerifyFixAsync( + """ + using System.Threading; + + class C + { + private static long _counter; + void M() { _counter{|E128087:--|}; } + } + """, + """ + using System.Threading; + + class C + { + private static long _counter; + void M() { _ = Interlocked.Decrement(ref _counter); } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAnAddAssignmentOfALongWithInterlockedAdd() + { + return VerifyFixAsync( + """ + using System.Threading; + + class C + { + private static long _total; + void M(long amount) { _total {|E128087:+=|} amount; } + } + """, + """ + using System.Threading; + + class C + { + private static long _total; + void M(long amount) { _ = Interlocked.Add(ref _total, amount); } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_OffersNothingInAStaticMemberOfAnInstanceClass() + { + return CodeFixTestRunner.RunAsync( + """ + class C + { + private static double _value; + static void M() { _value{|E128087:++|}; } + } + """, + """ + class C + { + private static double _value; + static void M() { _value{|E128087:++|}; } + } + """.Replace("{|E128087:++|}", "++", System.StringComparison.Ordinal), + options: new CodeFixTestOptions { FixedExpected = [Remaining(4, 29, 4, 31)] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_OffersNothingForAFieldOfAStaticClass() + { + return CodeFixTestRunner.RunAsync( + """ + static class C + { + private static double _value; + public static void M() { _value{|E128087:++|}; } + } + """, + """ + static class C + { + private static double _value; + public static void M() { _value++; } + } + """, + options: new CodeFixTestOptions { FixedExpected = [Remaining(4, 36, 4, 38)] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_OffersNoInterlockedFixForAnAddAssignmentInValuePosition() + { + return VerifyFixAsync( + """ + class C + { + private static int _total; + int M() { return _total {|E128087:+=|} 2; } + } + """, + """ + class C + { + private int _total; + int M() { return _total += 2; } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..f5439c38 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StringConcatInLoopCodeFixBranchCoverageTests.cs @@ -0,0 +1,462 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StringConcatInLoopCodeFixBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_SkipsEarlierLocalsWithOtherInitializers() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines) + { + var other = "x"; + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result + other; + } + } + """, + """ + using System.Collections.Generic; + using System.Text; + + class C + { + string M(List lines) + { + var other = "x"; + var result = ""; + var sb = new StringBuilder(); + foreach (var line in lines) + { + sb.Append(line); + } + result = sb.ToString(); + + return result + other; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAWhileLoopAndLeavesOtherAddAssignmentsAlone() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines, int[] numbers) + { + var result = ""; + var i = 0; + var count = 0; + while (i < lines.Count) + { + {|E128067:result += lines[i]|}; + count += 1; + numbers[0] += 1; + i++; + } + + return result + count; + } + } + """, + """ + using System.Collections.Generic; + using System.Text; + + class C + { + string M(List lines, int[] numbers) + { + var result = ""; + var i = 0; + var count = 0; + var sb = new StringBuilder(); + while (i < lines.Count) + { + sb.Append(lines[i]); + count += 1; + numbers[0] += 1; + i++; + } + result = sb.ToString(); + + return result + count; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_PicksTheNextBuilderNameWhenTheFirstIsTaken() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + private int sb; + + string M(List lines, int stringBuilder) + { + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result + stringBuilder; + } + } + """, + """ + using System.Collections.Generic; + using System.Text; + + class C + { + private int sb; + + string M(List lines, int stringBuilder) + { + var result = ""; + var builder = new StringBuilder(); + foreach (var line in lines) + { + builder.Append(line); + } + result = builder.ToString(); + + return result + stringBuilder; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AvoidsNamesOfLocalFunctionsInTheMember() + { + return VerifyFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines) + { + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + void sb() + { + } + + sb(); + return result; + } + } + """, + """ + using System.Collections.Generic; + using System.Text; + + class C + { + string M(List lines) + { + var result = ""; + var stringBuilder = new StringBuilder(); + foreach (var line in lines) + { + stringBuilder.Append(line); + } + result = stringBuilder.ToString(); + + void sb() + { + } + + sb(); + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenEveryBuilderNameIsTaken() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines, int sb, int stringBuilder, int builder, int accumulator) + { + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result + sb + stringBuilder + builder + accumulator; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSeedIsNotAStringLiteral() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class Holder + { + public static string Empty { get; } = ""; + } + + class C + { + static string Seed() => ""; + + string FromProperty(List lines) + { + var result = Holder.Empty; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + + string FromCall(List lines) + { + var result = Seed(); + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLocalHasNoInitializer() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines) + { + string result; + result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDeclarationHoldsSeveralVariables() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines) + { + string result = "", other = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result + other; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLoopLeavesTheMethod() + { + return VerifyNoFixAsync( + """ + using System; + using System.Collections.Generic; + class C + { + string Returns(List lines) + { + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + return result; + } + + return result; + } + + string Throws(List lines) + { + var result = ""; + foreach (var line in lines) + { + {|E128067:result += line|}; + throw new InvalidOperationException(); + } + + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLoopIsNotDirectlyInABlock() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines, bool flag) + { + var result = ""; + if (flag) + foreach (var line in lines) + { + {|E128067:result += line|}; + } + + return result; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheTargetIsNotALocal() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + private string _text = ""; + + string[] Parts { get; } = new string[1]; + + void M(List lines, string[] items) + { + foreach (var line in lines) + { + {|E128067:_text += line|}; + {|E128067:items[0] += line|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheAssignmentIsPartOfALargerExpression() + { + return VerifyNoFixAsync( + """ + using System.Collections.Generic; + class C + { + string M(List lines) + { + var result = ""; + var copy = ""; + foreach (var line in lines) + { + copy = {|E128067:result += line|}; + } + + return result + copy; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheLocalIsAppendedFromInsideALambda() + { + return VerifyNoFixAsync( + """ + using System; + using System.Collections.Generic; + class C + { + string M(List lines) + { + var result = ""; + foreach (var line in lines) + { + Action append = () => {|E128067:result += line|}; + append(); + } + + return result; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/StringFormatToInterpolationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/StringFormatToInterpolationBranchCoverageTests.cs new file mode 100644 index 00000000..dd301799 --- /dev/null +++ b/tests/E128.Analyzers.Tests/StringFormatToInterpolationBranchCoverageTests.cs @@ -0,0 +1,274 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class StringFormatToInterpolationBranchCoverageTests +{ + private static Task VerifyAnalyzerAsync(string code, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(code, expected: null, options: options); + } + + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync(source); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenFormatIsCalledWithoutAReceiver() + { + return VerifyAnalyzerAsync(""" + using static System.String; + class C + { + void M(int n) + { + var s = Format("Value: {0}", n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheMethodIsNotFormat() + { + return VerifyAnalyzerAsync(""" + class C + { + void M(int n) + { + var s = string.Concat("Value: ", n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenFormatHasOnlyTheFormatString() + { + return VerifyAnalyzerAsync(""" + class C + { + void M() + { + var s = string.Format("Value"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheCallDoesNotBind() + { + return VerifyAnalyzerAsync( + """ + class C + { + void M() + { + var s = string.Format(1, 2); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenFormatBelongsToAnotherType() + { + return VerifyAnalyzerAsync(""" + class Formatter + { + public static string Format(string template, int value) + { + return template + value; + } + } + + class C + { + void M(int n) + { + var s = Formatter.Format("Value: {0}", n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheFormatIsACompositeFormatVariable() + { + return VerifyAnalyzerAsync(""" + using System.Globalization; + using System.Text; + class C + { + void M(CompositeFormat format, int n) + { + var s = string.Format(CultureInfo.InvariantCulture, format, n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenTheConstantFormatIsNull() + { + return VerifyAnalyzerAsync(""" + class C + { + const string? Template = null; + + void M(int n) + { + var s = string.Format(Template, n); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheFormatSpecifier() + { + return VerifyFixAsync( + """ + class C + { + void M(double price, int count) + { + var s = {|E128015:string.Format("Price {0:N2} for {1}", price, count)|}; + } + } + """, + """ + class C + { + void M(double price, int count) + { + var s = $"Price {price:N2} for {count}"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_EscapesTabsQuotesBackslashesAndCarriageReturns() + { + return VerifyFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("tab\t quote\" back\\ cr\r {0}", n)|}; + } + } + """, + """ + class C + { + void M(int n) + { + var s = $"tab\t quote\" back\\ cr\r {n}"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAPlaceholderIsNotClosed() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("value {0", n)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAPlaceholderPointsPastTheArguments() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("value {1}", n)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAPlaceholderIsNotAnIndex() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("value {name} {-1}", n)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAPlaceholderCarriesAlignment() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("value {0,5}", n)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAClosingBraceIsAtTheEnd() + { + return VerifyNoFixAsync( + """ + class C + { + void M(int n) + { + var s = {|E128015:string.Format("{0} }", n)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SubstringLengthUnderflowBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SubstringLengthUnderflowBranchCoverageTests.cs new file mode 100644 index 00000000..91fb1be1 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SubstringLengthUnderflowBranchCoverageTests.cs @@ -0,0 +1,103 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SubstringLengthUnderflowBranchCoverageTests +{ + private static Task VerifyAsync(string members) + { + return AnalyzerTestRunner.VerifyAsync("class C\n{\n" + members + "}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForALiteralReceiverWithNoSymbol() + { + return VerifyAsync(""" + string M() => {|E128198:"abc".Substring(0, "abc".Length - 1)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForParenthesesAndChainedSubtraction() + { + return VerifyAsync(""" + string M(string s) => {|E128198:s.Substring(0, (s.Length - 1))|}; + + string N(string s) => {|E128198:s.Substring(0, (s.Length - 1) - 2)|}; + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCountIsNotAPositiveLengthSubtraction() + { + return VerifyAsync(""" + string A(string s) => s.Substring(0, s.Length + 1); + + string B(string s) => s.Substring(0, s.Length - 0); + + string D(string s, int n) => s.Substring(0, n - 1); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardFollowsTheCall() + { + return VerifyAsync(""" + string M(string s) + { + var head = {|E128198:s.Substring(0, s.Length - 1)|}; + if (s.Length < 2) + { + return string.Empty; + } + + return head; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnEqualityTestReadsTheLength() + { + return VerifyAsync(""" + string M(string s) + { + if (s.Length != 3) + { + return s.Substring(0, s.Length - 1); + } + + return s; + } + + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNegatedGuardIsParenthesized() + { + return VerifyAsync(""" + string M(string s) + { + if (!(string.IsNullOrEmpty(s))) + { + return s.Substring(0, s.Length - 1); + } + + return s; + } + + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..f0986a37 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SwitchEnumExhaustivenessAnalyzerBranchCoverageTests.cs @@ -0,0 +1,156 @@ +using System.Threading.Tasks; +using E128.Analyzers.Maintainability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SwitchEnumExhaustivenessAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + "enum Color { Red, Green, Blue }\n" + code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnExhaustiveSwitchExpression() + { + return VerifyAsync(""" + class C + { + int M(Color c) => c switch + { + Color.Red => 1, + Color.Green => 2, + Color.Blue => 3, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnExpressionWithADiscardArm() + { + return VerifyAsync(""" + class C + { + int M(Color c) => c switch + { + Color.Red => 1, + _ => 0, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAStatementWithAVarPattern() + { + return VerifyAsync(""" + class C + { + int M(Color c) + { + switch (c) + { + case Color.Red: + return 1; + case var other: + return (int)other; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnExpressionWithAVarPattern() + { + return VerifyAsync(""" + class C + { + int M(Color c) => c switch + { + Color.Red => 1, + var other => (int)other, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAGuardedVarPatternThatDoesNotCoverTheEnum() + { + return VerifyAsync(""" + class C + { + void M(Color c) + { + {|E128088:switch|} (c) + { + case Color.Red: + break; + case var value when value == Color.Green: + break; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForTheRemainingMemberAfterAnOrPattern() + { + return VerifyAsync(""" + class C + { + int M(Color c) => c {|E128088:switch|} + { + Color.Red or Color.Green => 1, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForASwitchExpressionOverAString() + { + return VerifyAsync(""" + class C + { + int M(string text) => text switch + { + "x" => 1, + _ => 0, + }; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForASwitchOverANullableEnum() + { + return VerifyAsync(""" + class C + { + void M(Color? c) + { + switch (c) + { + case Color.Red: + break; + } + } + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/SyncLocalFunctionCallBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SyncLocalFunctionCallBranchCoverageTests.cs new file mode 100644 index 00000000..c378a5ac --- /dev/null +++ b/tests/E128.Analyzers.Tests/SyncLocalFunctionCallBranchCoverageTests.cs @@ -0,0 +1,69 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SyncLocalFunctionCallBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForOtherMembersAndAWaitMethodGroup() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Threading.Tasks; + + class C + { + void M() + { + async Task LoadAsync() { await Task.CompletedTask; } + var awaiter = LoadAsync().GetAwaiter(); + Action wait = LoadAsync().Wait; + _ = (awaiter, wait); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_Declines_WhenTheCallSitsInAConstructor() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Threading.Tasks; + + class C + { + public C() + { + async Task LoadAsync() { await Task.CompletedTask; } + {|E128096:LoadAsync()|}.Wait(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_Declines_WhenTheCallSitsInALambda() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System; + using System.Threading.Tasks; + + class C + { + void M() + { + async Task LoadAsync() => await Task.FromResult(1); + Func read = () => {|E128096:LoadAsync()|}.Result; + _ = read(); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/SyncOverAsyncCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/SyncOverAsyncCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..c066e913 --- /dev/null +++ b/tests/E128.Analyzers.Tests/SyncOverAsyncCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,109 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class SyncOverAsyncCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + private static Task VerifyNoFixAsync(string code) + { + return CodeFixTestRunner.NoFixAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheReturnTypeOfAnAlreadyAsyncMethod() + { + return VerifyFixAsync( + """ + using System.Threading.Tasks; + class C + { + async Task M(Task task) + { + await Task.Yield(); + return {|E128008:task.Result|}; + } + } + """, + """ + using System.Threading.Tasks; + class C + { + async Task M(Task task) + { + await Task.Yield(); + return await task; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForALocalFunction() + { + return VerifyNoFixAsync(""" + using System.Threading.Tasks; + class C + { + int M(Task task) + { + int Local() => {|E128008:task.Result|}; + return Local(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForAPropertyGetter() + { + return VerifyNoFixAsync(""" + using System.Threading.Tasks; + class C + { + private Task _task = Task.FromResult(1); + int Value + { + get { return {|E128008:_task.Result|}; } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForAnIndexer() + { + return VerifyNoFixAsync(""" + using System.Threading.Tasks; + class C + { + private Task _task = Task.FromResult(1); + int this[int i] => {|E128008:_task.Result|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_ForAFieldInitializer() + { + return VerifyNoFixAsync(""" + using System.Threading.Tasks; + class C + { + private int _value = {|E128008:Task.FromResult(1).Result|}; + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsBranchCoverageTests.cs new file mode 100644 index 00000000..28974a7d --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskCompletionSourceOptionsBranchCoverageTests.cs @@ -0,0 +1,257 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the creation and completion shapes of the TaskCompletionSource rule and its code fix. +/// +public sealed class TaskCompletionSourceOptionsBranchCoverageTests +{ + private static readonly AnalyzerTestOptions Options = new() { MarkupOptions = MarkupOptions.UseFirstDescriptor }; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(source, expected: null, options ?? Options); + } + + private static Task FixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync( + source, + fixedCode, + markupOptions: MarkupOptions.UseFirstDescriptor); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCompleterIsCalledWithoutAReceiver() + { + return VerifyAsync(""" + using System.Threading.Tasks; + class MySource : TaskCompletionSource + { + public MySource() + : base(TaskCreationOptions.RunContinuationsAsynchronously) + { + } + + void Finish() + { + SetResult(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardInTheConditionIsNotAnInterlockedExchange() + { + return VerifyAsync(""" + using System.Threading; + using System.Threading.Tasks; + class C + { + private readonly TaskCompletionSource source = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _count; + + bool Check() => true; + + void M(int value) + { + if (Check()) + { + {|E128159:source.SetResult(value)|}; + } + + if (Interlocked.Increment(ref _count) == 1) + { + {|E128159:source.SetResult(value)|}; + } + + var local = 0; + if (Interlocked.Exchange(ref local, 1) == 0) + { + {|E128159:source.SetResult(value)|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCreationCannotBeBound() + { + return VerifyAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource(missing)|}; + } + } + """, + new AnalyzerTestOptions + { + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CompilerDiagnostics = CompilerDiagnostics.None + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheStateOverloadHasNoOptions() + { + return VerifyAsync(""" + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource("state")|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCreationHasOnlyAnInitializer() + { + return VerifyAsync(""" + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource { }|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AddsTheOptionsAfterAStateArgument() + { + return FixAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource("state")|}; + } + } + """, + """ + using System.Threading.Tasks; + class C + { + object M() + { + return new TaskCompletionSource("state", TaskCreationOptions.RunContinuationsAsynchronously); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ParenthesizesABinaryOptionsExpression() + { + return FixAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource(TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning)|}; + } + } + """, + """ + using System.Threading.Tasks; + class C + { + object M() + { + return new TaskCompletionSource((TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning) | TaskCreationOptions.RunContinuationsAsynchronously); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ParenthesizesAConditionalOptionsExpression() + { + return FixAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return {|E128159:new TaskCompletionSource(true ? TaskCreationOptions.LongRunning : TaskCreationOptions.None)|}; + } + } + """, + """ + using System.Threading.Tasks; + class C + { + object M() + { + return new TaskCompletionSource((true ? TaskCreationOptions.LongRunning : TaskCreationOptions.None) | TaskCreationOptions.RunContinuationsAsynchronously); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnArgumentIsNamed() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return new TaskCompletionSource(state: "state"); + } + } + """, + expected: new DiagnosticResult("E128159", DiagnosticSeverity.Warning).WithSpan(6, 16, 6, 61)); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheCreationHasNoArgumentList() + { + return CodeFixTestRunner.NoFixAsync( + """ + using System.Threading.Tasks; + class C + { + object M() + { + return new TaskCompletionSource { }; + } + } + """, + expected: new DiagnosticResult("E128159", DiagnosticSeverity.Warning).WithSpan(6, 16, 6, 49)); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskFromResultSyncIoBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoBranchCoverageTests.cs new file mode 100644 index 00000000..c0b81ff9 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskFromResultSyncIoBranchCoverageTests.cs @@ -0,0 +1,221 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the wrapper types, I/O owners, and rewrites of the FromResult rule and its code fix. +/// +public sealed class TaskFromResultSyncIoBranchCoverageTests +{ + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(source, expected: null, options); + } + + private static Task FixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForValueTaskFromResult() + { + return VerifyAsync(""" + using System.IO; + using System.Threading.Tasks; + class C + { + ValueTask M(string path) + { + File.WriteAllText(path, "x"); + return {|E128028:ValueTask.FromResult(1)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForABaseStreamCopy() + { + return VerifyAsync(""" + using System.IO; + using System.Threading.Tasks; + class C + { + Task M(Stream source, Stream target) + { + source.CopyTo(target); + return {|E128028:Task.FromResult(1)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForASynchronousHttpSend() + { + return VerifyAsync(""" + using System.Net.Http; + using System.Threading.Tasks; + class C + { + Task M(HttpClient client, HttpRequestMessage request) + { + client.Send(request); + return {|E128028:Task.FromResult(1)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFromResultBelongsToAnotherType() + { + return VerifyAsync(""" + using System.IO; + using System.Threading.Tasks; + class Results + { + public static Task FromResult(int value) => Task.CompletedTask.ContinueWith(_ => value); + } + + class C + { + Task M(string path) + { + File.WriteAllText(path, "x"); + return Results.FromResult(1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheFromResultIsInAPropertyBody() + { + return VerifyAsync(""" + using System.IO; + using System.Threading.Tasks; + class C + { + private readonly string _path = "x"; + + Task Text => Task.FromResult(File.ReadAllText(_path)); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallsBelongToLookAlikeTypes() + { + return VerifyAsync(""" + using System.IO; + using System.Text; + using System.Threading.Tasks; + class File + { + public static string ReadAllText(string path) => path; + + public static Task ReadAllTextAsync(string path) => Task.FromResult(path); + } + + class C + { + Task M(string path, StreamReader reader, StringBuilder builder) + { + var first = File.ReadAllText(path); + var second = reader.Read(); + builder.Append(first); + return Task.FromResult(first); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSyncCallDoesNotBind() + { + return VerifyAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + Task M() + { + File.ReadAllText(missing); + unknown.ReadAllText(); + return Task.FromResult(1); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAnExpressionBodiedMethod() + { + return FixAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + Task M(string path) => {|E128028:Task.FromResult(File.ReadAllText(path))|}; + } + """, + """ + using System.IO; + using System.Threading.Tasks; + class C + { + async Task M(string path) => await File.ReadAllTextAsync(path); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_RewritesAValueTaskAndAStreamCopy() + { + return FixAsync( + """ + using System.IO; + using System.Threading.Tasks; + class C + { + ValueTask M(string path, Stream source, Stream target) + { + source.CopyTo(target); + File.WriteAllText(path, "x"); + return {|E128028:ValueTask.FromResult(1)|}; + } + } + """, + """ + using System.IO; + using System.Threading.Tasks; + class C + { + async ValueTask M(string path, Stream source, Stream target) + { + await source.CopyToAsync(target); + await File.WriteAllTextAsync(path, "x"); + return 1; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationBranchCoverageTests.cs new file mode 100644 index 00000000..5f9146b6 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationBranchCoverageTests.cs @@ -0,0 +1,251 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the lambda shapes the cancellation propagation rule and its code fix inspect. +/// +public sealed class TaskWhenAllCancellationPropagationBranchCoverageTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + class PageOptions + { + public CancellationToken CancellationToken { get; set; } + + public int Timeout { get; set; } + } + + class Page + { + public Task GotoAsync(string url, PageOptions? options = null) => Task.CompletedTask; + + public Task ClickAsync(string selector, CancellationToken token) => Task.CompletedTask; + } + + """; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(Header + source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAPlaywrightCallWithoutAToken() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable urls, Page page, CancellationToken ct) + { + await {|E128038:Task.WhenAll(urls.Select(async url => await page.GotoAsync(url)))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheOptionsObjectCarriesTheToken() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable urls, Page page, CancellationToken ct) + { + await Task.WhenAll(urls.Select(async url => await page.GotoAsync(url, new PageOptions { CancellationToken = ct }))); + await Task.WhenAll(urls.Select(async url => await page.GotoAsync(url, new() { CancellationToken = ct }))); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheOptionsObjectCarriesNoToken() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable urls, Page page, CancellationToken ct) + { + await {|E128038:Task.WhenAll(urls.Select(async url => await page.GotoAsync(url, new PageOptions { Timeout = 5 })))|}; + await {|E128038:Task.WhenAll(urls.Select(async url => await page.GotoAsync(url, new PageOptions())))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenIsAPositionalArgument() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable urls, Page page, CancellationToken ct) + { + await Task.WhenAll(urls.Select(async url => await page.ClickAsync(url, ct))); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenWhenAllTakesSeveralArguments() + { + return VerifyAsync(""" + class C + { + async Task M(Task first, Task second, CancellationToken ct) + { + await Task.WhenAll(first, second); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenWhenAllTakesAVariable() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable tasks, CancellationToken ct) + { + await Task.WhenAll(tasks); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsNotASelectCall() + { + return VerifyAsync(""" + class C + { + static IEnumerable Select(IEnumerable urls) => Array.Empty(); + + async Task M(IEnumerable urls, IEnumerable tasks, CancellationToken ct) + { + await Task.WhenAll(Select(urls)); + await Task.WhenAll(tasks.Where(task => task.IsCompleted)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectLambdaIsNotAsync() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable urls, HttpClient client, CancellationToken ct) + { + await Task.WhenAll(urls.Select(url => client.GetAsync(url))); + await Task.WhenAll(urls.Select((url) => client.GetAsync(url))); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectorIsAMethodGroup() + { + return VerifyAsync(""" + class C + { + static Task Fetch(string url) => Task.CompletedTask; + + async Task M(IEnumerable urls, CancellationToken ct) + { + await Task.WhenAll(urls.Select(Fetch)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectHasNoArguments() + { + return VerifyAsync( + """ + class C + { + async Task M(IEnumerable urls, CancellationToken ct) + { + await Task.WhenAll(urls.Select()); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNoMethodEncloses_TheWhenAll() + { + return VerifyAsync(""" + class C + { + private static readonly Func, HttpClient, Task> Run = + (urls, client) => Task.WhenAll(urls.Select(async url => await client.GetAsync(url))); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenTypeDoesNotBind() + { + return VerifyAsync( + """ + class C + { + async Task M(IEnumerable urls, HttpClient client, MissingToken ct) + { + await Task.WhenAll(urls.Select(async url => await client.GetAsync(url))); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLambdaCallsAnUnqualifiedOrGenericMethod() + { + return VerifyAsync(""" + class C + { + static Task GetAsync(string url) => Task.FromResult(url); + + static Task Fetch(string url) => Task.FromResult(default(T)!); + + async Task M(IEnumerable urls, HttpClient client, CancellationToken ct) + { + await Task.WhenAll(urls.Select(async url => await GetAsync(url))); + await Task.WhenAll(urls.Select(async url => await Fetch(url))); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..0e72023e --- /dev/null +++ b/tests/E128.Analyzers.Tests/TaskWhenAllCancellationPropagationCodeFixBranchCoverageTests.cs @@ -0,0 +1,56 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the token rewrites of the cancellation propagation code fix. +/// +public sealed class TaskWhenAllCancellationPropagationCodeFixBranchCoverageTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + """; + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AppendsTheTokenToEveryCallThatLacksIt_UsingTheParameterName() + { + return CodeFixTestRunner.RunAsync( + Header + """ + class C + { + async Task M(IEnumerable urls, HttpClient client, int retries, CancellationToken stopToken) + { + await {|E128038:Task.WhenAll(urls.Select(async url => + { + await client.GetAsync(url); + await client.GetStringAsync(url, stopToken); + await client.DeleteAsync(url); + }))|}; + } + } + """, + Header + """ + class C + { + async Task M(IEnumerable urls, HttpClient client, int retries, CancellationToken stopToken) + { + await Task.WhenAll(urls.Select(async url => + { + await client.GetAsync(url, stopToken); + await client.GetStringAsync(url, stopToken); + await client.DeleteAsync(url, stopToken); + })); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..e0a6b915 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TempDirCleanupAnalyzerBranchCoverageTests.cs @@ -0,0 +1,163 @@ +using System.Threading.Tasks; +using E128.Analyzers.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TempDirCleanupAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAPropertyInitializer() + { + return VerifyAsync(""" + using System.IO; + + class {|E128054:MyTests|} + { + private string Root { get; } = Path.GetTempPath(); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAConstructorThatStoresThePathInAProperty() + { + return VerifyAsync(""" + using System.IO; + + class {|E128054:MyTests|} + { + private string Root { get; set; } = ""; + + public MyTests() + { + Root = Path.GetTempPath(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAConstructorThatKeepsThePathInALocal() + { + return VerifyAsync(""" + using System.IO; + + class {|E128054:MyTests|} + { + public MyTests() + { + var local = Path.GetTempPath(); + _ = local; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForANestedClassOnlyOnTheInnerClass() + { + return VerifyAsync(""" + using System.IO; + + class Outer + { + class {|E128054:Inner|} + { + private readonly string _root = Path.GetTempPath(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTheSameCallInAPropertyAccessorOrLocalFunction() + { + return VerifyAsync(""" + using System.IO; + + class MyTests + { + public string Root + { + get { return Path.GetTempPath(); } + } + + public MyTests() + { + string Local() { return Path.GetTempPath(); } + _ = Local(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForTypesThatAreNotClassesAndForOtherPathTypes() + { + return VerifyAsync(""" + using System.IO; + + struct StructTests + { + private static readonly string s_root = Path.GetTempPath(); + } + + record RecordTests + { + public string Root { get; } = Path.GetTempPath(); + } + + static class Path2 + { + public static string GetTempPath() { return ""; } + } + + namespace Other + { + static class Path + { + public static string GetTempPath() { return ""; } + } + + class Fake + { + private readonly string _root = Path.GetTempPath(); + private readonly string _again = Path2.GetTempPath(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheCleanupInterfaceIsFromAnotherNamespace() + { + return VerifyAsync(""" + using System.IO; + + namespace Other + { + interface IDisposable + { + } + } + + class {|E128054:MyTests|} : Other.IDisposable + { + private readonly string _root = Path.GetTempPath(); + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TestMethodReflectionAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TestMethodReflectionAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..f7b43358 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TestMethodReflectionAnalyzerBranchCoverageTests.cs @@ -0,0 +1,118 @@ +using System.Threading.Tasks; +using E128.Analyzers.Maintainability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TestMethodReflectionAnalyzerBranchCoverageTests +{ + private const string Stubs = """ + using System; + using System.Reflection; + + namespace Xunit + { + sealed class FactAttribute : Attribute { } + sealed class TheoryAttribute : Attribute { } + } + + class FactAttribute : Attribute { } + class TheoryAttribute : Attribute { } + class OtherAttribute : Attribute { } + + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(Stubs + code); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Fact")] + [InlineData("Theory")] + [InlineData("Xunit.Fact")] + [InlineData("Xunit.Theory")] + public Task Reports_ForEachRecognizedTestAttribute(string attribute) + { + return VerifyAsync( + "class C { [" + attribute + "] void M() { var x = {|E128090:typeof(C).GetMethod(\"M\")|}; } }"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAReflectionMethodGroup() + { + return VerifyAsync(""" + class C + { + [Fact] + void M(Type type) + { + Func find = {|E128090:type.GetMethod|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForUnrelatedAttributesAndMethods() + { + return VerifyAsync(""" + class C + { + [Other] + void M(Type type) + { + var x = type.GetMethod("M"); + var flags = BindingFlags.NonPublic; + } + + [Fact] + void N(Type type) + { + var x = type.GetMethods(); + var y = type.Name; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnUnboundOrUserDefinedGetMethod() + { + return VerifyAsync(""" + class OtherType + { + public int GetMethod(string name) => 0; + } + + class C + { + [Fact] + void M(OtherType other) + { + var x = other.GetMethod("M"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForATypeNameInADeclarationAndCast() + { + return VerifyAsync(""" + class C + { + [Fact] + void M(object value) + { + {|E128090:BindingFlags|} flags = ({|E128090:BindingFlags|})value; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TextContentGuardBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TextContentGuardBranchCoverageTests.cs new file mode 100644 index 00000000..9f8f6458 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TextContentGuardBranchCoverageTests.cs @@ -0,0 +1,160 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the guard shapes that decide whether a TextContent match needs a length check. +/// +public sealed class TextContentGuardBranchCoverageTests +{ + private static Task VerifyAsync(string members, AnalyzerTestOptions? options = null) + { + var source = $$""" + using System; + {{TestStubs.AngleSharpDom}} + class C + { + bool flag; + int limit = 500; + + {{members}} + } + """; + return AnalyzerTestRunner.VerifyAsync(source, expected: null, options); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("e.TextContent.Length <= 500 && e.TextContent.Contains(\"x\")")] + [InlineData("500 > e.TextContent.Length && e.TextContent.Contains(\"x\")")] + [InlineData("500 >= e.TextContent.Length && e.TextContent.Contains(\"x\")")] + [InlineData("e.TextContent.Contains(\"x\") && 100 > e.TextContent.Length")] + [InlineData("flag && e.TextContent.Length < 500 && e.TextContent.Contains(\"x\")")] + [InlineData("e.TextContent.Length < 500 && flag && e.TextContent.EndsWith(\"x\")")] + public Task Silent_WhenALengthGuardAccompaniesTheMatch(string condition) + { + return VerifyAsync($$""" + bool M(AngleSharp.Dom.IElement e) + { + return {{condition}}; + } + """); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("e.TextContent.Length > 50 && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("e.TextContent.Length > 200 && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("200 < e.TextContent.Length && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("50 < e.TextContent.Length && {|E128077:e.TextContent.Equals(\"x\")|}")] + [InlineData("e.TextContent.Length < limit && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("e.TextContent.Length < 'a' && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("e.TextContent.Length < 5000000000L && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("e.TextContent.Length < 500 || {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("flag && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("e.Other.Length < 500 && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("args.Length < 500 && {|E128077:e.TextContent.Contains(\"x\")|}")] + [InlineData("other.TextContent.Length < 500 && {|E128077:e.TextContent.Contains(\"x\")|}")] + public Task Reports_WhenNoUsableGuardAccompaniesTheMatch(string condition) + { + return VerifyAsync($$""" + bool M(AngleSharp.Dom.IElement e, AngleSharp.Dom.IElement other, string[] args) + { + return {{condition}}; + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnOrChainSplitsTheGuardFromTheMatch() + { + return VerifyAsync(""" + bool M(AngleSharp.Dom.IElement e) + { + return e.TextContent.Length < 500 && flag || {|E128077:e.TextContent.Contains("x")|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheGuardChainIsFollowedByAnOr() + { + return VerifyAsync(""" + bool M(AngleSharp.Dom.IElement e) + { + return e.TextContent.Length < 500 && e.TextContent.Contains("x") || flag; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheMatchIsAMethodBodyWithoutLambda() + { + return VerifyAsync(""" + bool M(AngleSharp.Dom.IElement e) => {|E128077:e.TextContent.Equals("x")|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAMemberCall() + { + return VerifyAsync(""" + bool Contains(string text) => text.Length > 0; + + bool M(AngleSharp.Dom.IElement e) => Contains("x"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheReceiverIsNotAMemberAccess() + { + return VerifyAsync(""" + bool M(string text) => text.Contains("x"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheMemberIsNotTextContent() + { + return VerifyAsync(""" + bool M(AngleSharp.Dom.IElement e) => e.ToString().Contains("x"); + + bool N(Uri uri) => uri.Host.Contains("x"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTextContentIsAField() + { + return VerifyAsync(""" + private sealed class Widget + { + public string TextContent = string.Empty; + } + + bool M(Widget widget) => widget.TextContent.Contains("x"); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTextContentDoesNotBind() + { + return VerifyAsync( + """ + bool M(Missing missing) => missing.TextContent.Contains("x"); + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageTests.cs new file mode 100644 index 00000000..427951c2 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TimingSafeComparisonBranchCoverageTests.cs @@ -0,0 +1,219 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TimingSafeComparisonBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_SequenceEqualOnSpansWhenEitherSideLooksSecret() + { + return VerifyAsync(""" + using System; + class C + { + bool M(Span computedTag, ReadOnlySpan expectedTag, byte[] data, int[] numbers, int[] otherNumbers) + { + var a = {|E128157:computedTag.SequenceEqual(expectedTag)|}; + var b = {|E128157:data.AsSpan().SequenceEqual(expectedTag)|}; + var c = {|E128157:expectedTag.SequenceEqual(data)|}; + var d = data.AsSpan().SequenceEqual(data); + var e = numbers.AsSpan().SequenceEqual(otherNumbers); + return a && b && c && d && e; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenSequenceEqualBelongsToAnotherTypeOrTakesAComparer() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Linq; + static class Own + { + public static bool SequenceEqual(byte[] a, byte[] b) => true; + } + + class C + { + bool M(byte[] computedTag, byte[] expectedTag, IEqualityComparer comparer) + { + var a = Own.SequenceEqual(computedTag, expectedTag); + var b = computedTag.SequenceEqual(expectedTag, comparer); + return a && b; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_SecretNamesBySuffixOrSegment() + { + return VerifyAsync(""" + using System.Linq; + class C + { + bool M(byte[] my_tag_value, byte[] received_hmac, byte[] other, byte[] signature, byte[] plain) + { + var a = {|E128157:my_tag_value.SequenceEqual(other)|}; + var b = {|E128157:other.SequenceEqual(received_hmac)|}; + var c = {|E128157:signature.SequenceEqual(plain)|}; + var d = plain.SequenceEqual(other); + return a && b && c && d; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ValuesProducedByHmacMembersAndEncoders() + { + return VerifyAsync(""" + using System; + using System.Buffers.Text; + using System.Linq; + using System.Security.Cryptography; + class C + { + string Field = ""; + + bool M(HMACSHA256 hmac, byte[] key, byte[] data, byte[] other, string text) + { + var a = {|E128157:hmac.ComputeHash(data).SequenceEqual(other)|}; + var b = {|E128157:HMACSHA256.HashData(key, data).SequenceEqual(other)|}; + var c = {|E128157:(hmac.Hash).SequenceEqual(other)|}; + var d = {|E128157:Convert.ToHexString(hmac.ComputeHash(data)) == text|}; + var e = {|E128157:Convert.ToBase64String(hmac.ComputeHash(data)).ToLowerInvariant() == text|}; + var f = {|E128157:Base64Url.EncodeToString(hmac.ComputeHash(data)) == text|}; + var computed = hmac.ComputeHash(data); + var g = {|E128157:computed.SequenceEqual(other)|}; + var encoded = Convert.ToHexString(hmac.ComputeHash(data)); + var h = {|E128157:encoded == text|}; + var i = {|E128157:text.Equals(encoded)|}; + return a && b && c && d && e && f && g && h && i; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheProducerIsNotAnHmacOrTheEncoderIsUnknown() + { + return VerifyAsync(""" + using System; + using System.Linq; + using System.Security.Cryptography; + class Holder + { + public byte[] Hash = new byte[0]; + } + + class C + { + bool M(SHA256 sha, Holder holder, byte[] data, byte[] other, string text) + { + var a = sha.ComputeHash(data).SequenceEqual(other); + var b = holder.Hash.SequenceEqual(other); + var c = sha.Hash!.SequenceEqual(other); + var d = Convert.ToHexString(sha.ComputeHash(data)) == text; + var e = Convert.ToHexStringLower(other) == text; + var f = string.Join(",", other) == text; + var g = Convert.FromHexString(text).SequenceEqual(other); + var h = (a ? other : data).SequenceEqual(other); + return a && b && c && d && e && f && g && h; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_IncrementalHmacReadersThroughALocalOrAFieldOrDirectly() + { + return VerifyAsync(""" + using System.Linq; + using System.Security.Cryptography; + class C + { + private readonly IncrementalHash field = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, new byte[32]); + + bool M(byte[] key, byte[] other, IncrementalHash parameter) + { + var local = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, key); + var a = {|E128157:local.GetCurrentHash().SequenceEqual(other)|}; + var b = {|E128157:field.GetHashAndReset().SequenceEqual(other)|}; + var c = {|E128157:IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, key).GetHashAndReset().SequenceEqual(other)|}; + var d = parameter.GetCurrentHash().SequenceEqual(other); + var plain = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var e = plain.GetCurrentHash().SequenceEqual(other); + return a && b && c && d && e; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_StringEqualityFormsForSecretStrings() + { + return VerifyAsync(""" + using System; + class C + { + bool M(string computedTag, string expectedTag, string name, string other, object boxed) + { + var a = {|E128157:computedTag == expectedTag|}; + var b = {|E128157:computedTag != name|}; + var c = {|E128157:string.Equals(computedTag, name)|}; + var d = {|E128157:name.Equals(computedTag)|}; + var e = {|E128157:string.Equals(name, computedTag, StringComparison.Ordinal)|}; + var f = {|E128157:object.Equals(computedTag, name)|}; + var g = {|E128157:Equals(computedTag, name)|}; + var h = name.Equals(other); + var i = computedTag == "constant"; + var j = computedTag.Equals(boxed); + var k = Equals(name); + var l = name.GetHashCode() == other.GetHashCode(); + return a && b && c && d && e && f && g && h && i && j && k && l; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_StringsOnlyWhenBothNamesCarryAWeakWord() + { + return VerifyAsync(""" + class C + { + bool M(string token, string expectedToken, string digest, string hash, string contentHash, string other, string name) + { + var a = {|E128157:token == expectedToken|}; + var b = {|E128157:digest == hash|}; + var c = {|E128157:hash == digest|}; + var d = hash == contentHash; + var e = token == other; + var f = other == token; + var g = token == name + other; + var h = token == null; + var i = token.Length == other.Length; + return a && b && c && d && e && f && g && h && i; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TimingSafeComparisonCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TimingSafeComparisonCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..54ed8253 --- /dev/null +++ b/tests/E128.Analyzers.Tests/TimingSafeComparisonCodeFixBranchCoverageTests.cs @@ -0,0 +1,99 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TimingSafeComparisonCodeFixBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDiagnosticIsAStringComparison() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + bool M(string computedTag, string name) + { + return {|E128157:computedTag == name|}; + } + + bool Call(string computedTag, string name) + { + return Check({|E128157:computedTag == name|}); + } + + bool Check(bool value) => value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheDiagnosticIsAStringEqualsCall() + { + return CodeFixTestRunner.NoFixAsync( + """ + class C + { + bool M(string computedTag, string name) + { + return {|E128157:string.Equals(computedTag, name)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenOnlyTheSecondOperandMayBeNull() + { + return CodeFixTestRunner.NoFixAsync( + """ + #nullable enable + using System.Linq; + + class C + { + byte[]? Maybe(byte[]? value) => value; + + bool M(byte[] computedTag, byte[]? expectedTag) + { + return {|E128157:computedTag.SequenceEqual(Maybe(expectedTag))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task CodeFix_KeepsTheExistingUsingAndTrivia() + { + return CodeFixTestRunner.RunAsync( + """ + using System.Linq; + using System.Security.Cryptography; + + class C + { + bool M(byte[] computedTag, byte[] expectedTag) + { + return !{|E128157:computedTag.SequenceEqual(expectedTag)|}; // compare + } + } + """, + """ + using System.Linq; + using System.Security.Cryptography; + + class C + { + bool M(byte[] computedTag, byte[] expectedTag) + { + return !CryptographicOperations.FixedTimeEquals(computedTag, expectedTag); // compare + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/TypeSymbolsBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/TypeSymbolsBranchCoverageTests.cs new file mode 100644 index 00000000..634e397a --- /dev/null +++ b/tests/E128.Analyzers.Tests/TypeSymbolsBranchCoverageTests.cs @@ -0,0 +1,98 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class TypeSymbolsBranchCoverageTests +{ + private const string Source = """ + using System; + using System.Collections.Generic; + + class Base { } + class Derived : Base { } + class Leaf : Derived { } + class Unrelated { } + class Holder { } + class Members + { + public int? Maybe; + public int Plain; + public Holder Closed; + public List Numbers; + } + """; + + private static (CSharpCompilation Compilation, INamedTypeSymbol Members) Compile() + { + var tree = CSharpSyntaxTree.ParseText(Source, cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "TypeProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return (compilation, compilation.GetTypeByMetadataName("Members")!); + } + + private static ITypeSymbol FieldType(INamedTypeSymbol type, string name) + { + return ((IFieldSymbol)type.GetMembers(name)[0]).Type; + } + + [Fact] + [Trait("Category", "CI")] + public void UnwrapNullable_ReturnsTheInnerTypeOnlyForNullableOfT() + { + var (_, members) = Compile(); + + Assert.Equal(SpecialType.System_Int32, TypeSymbols.UnwrapNullable(FieldType(members, "Maybe")).SpecialType); + Assert.Equal(SpecialType.System_Int32, TypeSymbols.UnwrapNullable(FieldType(members, "Plain")).SpecialType); + Assert.Same(FieldType(members, "Closed"), TypeSymbols.UnwrapNullable(FieldType(members, "Closed"))); + } + + [Fact] + [Trait("Category", "CI")] + public void DerivesFrom_WalksTheBaseChain() + { + var (compilation, _) = Compile(); + var baseType = compilation.GetTypeByMetadataName("Base"); + var leaf = compilation.GetTypeByMetadataName("Leaf"); + var unrelated = compilation.GetTypeByMetadataName("Unrelated"); + + Assert.True(TypeSymbols.DerivesFrom(leaf, baseType)); + Assert.True(TypeSymbols.DerivesFrom(baseType, baseType)); + Assert.False(TypeSymbols.DerivesFrom(baseType, leaf)); + Assert.False(TypeSymbols.DerivesFrom(unrelated, baseType)); + Assert.False(TypeSymbols.DerivesFrom(leaf, null)); + Assert.False(TypeSymbols.DerivesFrom(null, baseType)); + } + + [Fact] + [Trait("Category", "CI")] + public void Matches_ComparesTheTypeWithTheTarget() + { + var (compilation, _) = Compile(); + var baseType = compilation.GetTypeByMetadataName("Base"); + var derived = compilation.GetTypeByMetadataName("Derived"); + + Assert.True(TypeSymbols.Matches(baseType, baseType)); + Assert.False(TypeSymbols.Matches(derived, baseType)); + Assert.False(TypeSymbols.Matches(baseType, null)); + Assert.False(TypeSymbols.Matches(null, baseType)); + } + + [Fact] + [Trait("Category", "CI")] + public void MatchesOriginalDefinition_ComparesTheGenericDefinition() + { + var (compilation, members) = Compile(); + var holder = compilation.GetTypeByMetadataName("Holder`1"); + var closed = FieldType(members, "Closed"); + + Assert.True(TypeSymbols.MatchesOriginalDefinition(closed, holder)); + Assert.True(TypeSymbols.MatchesOriginalDefinition(holder, holder)); + Assert.False(TypeSymbols.MatchesOriginalDefinition(FieldType(members, "Numbers"), holder)); + Assert.False(TypeSymbols.MatchesOriginalDefinition(closed, null)); + Assert.False(TypeSymbols.MatchesOriginalDefinition(null, holder)); + } +} diff --git a/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllBranchCoverageTests.cs new file mode 100644 index 00000000..78aeea84 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnboundedTaskWhenAllBranchCoverageTests.cs @@ -0,0 +1,266 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the fan-out shapes of the unbounded WhenAll rule that the main suite leaves out. +/// +public sealed class UnboundedTaskWhenAllBranchCoverageTests +{ + private const string Header = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + + """; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync(Header + source, expected: null, options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnAsyncSelectIsMaterializedToAList() + { + return VerifyAsync(""" + class C + { + static Task Work(int item) => Task.CompletedTask; + + async Task M(IEnumerable items) + { + await {|E128037:Task.WhenAll(items.Select(async x => await Work(x)).ToList())|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectorIsAMethodGroup() + { + return VerifyAsync(""" + class C + { + static Task Work(int item) => Task.CompletedTask; + + async Task M(IEnumerable items) + { + await Task.WhenAll(items.Select(Work)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSelectHasNoArguments() + { + return VerifyAsync( + """ + class C + { + async Task M(IEnumerable items) + { + await Task.WhenAll(items.Select()); + } + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheThrottleIsAnUnqualifiedCallInsideTheLambda() + { + return VerifyAsync(""" + class C + { + static Task Work(int item) => Task.CompletedTask; + + async Task M(IEnumerable items) + { + await Task.WhenAll(items.Select(async x => await Work(x)).Where(task => task != null)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsACallResult() + { + return VerifyAsync(""" + class C + { + static IEnumerable Make() => Array.Empty(); + + async Task M() + { + await Task.WhenAll(Make()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsAFilteredSequence() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable tasks) + { + await Task.WhenAll(tasks.Where(task => task.IsCompleted).ToArray()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsAnArrayLiteral() + { + return VerifyAsync(""" + class C + { + async Task M() + { + await Task.WhenAll(new[] { Task.CompletedTask, Task.CompletedTask }); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArgumentIsAParameter() + { + return VerifyAsync(""" + class C + { + async Task M(IEnumerable tasks) + { + await Task.WhenAll(tasks); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsFilledByOtherCalls() + { + return VerifyAsync(""" + class C + { + static void Add(Task task) + { + } + + async Task M(IReadOnlyList items) + { + var tasks = new List(); + foreach (var item in items) + { + Add(Task.Run(() => item)); + tasks.Insert(0, Task.Run(() => item)); + tasks.Add(Task.Delay(item)); + tasks.Add(Task.Factory.StartNew(() => item)); + tasks.Add(Task.CompletedTask); + tasks.Add(Runner.Run(() => item)); + } + + await Task.WhenAll(tasks); + } + } + + static class Runner + { + public static Task Run(Func work) => Task.CompletedTask; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheRunLambdaWaitsOnALookAlikeSemaphore() + { + return VerifyAsync(""" + namespace Other + { + public sealed class SemaphoreSlim + { + public Task WaitAsync() => Task.CompletedTask; + } + } + + class C + { + async Task M(IReadOnlyList items, Other.SemaphoreSlim gate) + { + var tasks = new List(); + foreach (var item in items) + { + tasks.Add({|E128037:Task.Run(async () => await gate.WaitAsync())|}); + } + + await Task.WhenAll(tasks); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheRunLambdaCallsAnUnqualifiedHelper() + { + return VerifyAsync(""" + class C + { + static void Work(int item) + { + } + + async Task M(IReadOnlyList items) + { + var tasks = new List(); + foreach (var item in items) + { + tasks.Add({|E128037:Task.Run(() => Work(item))|}); + } + + await Task.WhenAll(tasks); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheRunIsAddedThroughALocalFunctionAddCall() + { + return VerifyAsync(""" + class C + { + async Task M(IReadOnlyList items) + { + var tasks = new List(); + void Add(Task task) => tasks.Add(task); + foreach (var item in items) + { + Add(Task.Run(() => item)); + } + + await Task.WhenAll(tasks); + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UncontainedRootJoinBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UncontainedRootJoinBranchCoverageTests.cs new file mode 100644 index 00000000..bb0c5034 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UncontainedRootJoinBranchCoverageTests.cs @@ -0,0 +1,264 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UncontainedRootJoinBranchCoverageTests +{ + private const string Guards = """ + static class Guard + { + public static bool IsInside(object path) => true; + + public static void ValidateDomainPath(object path) { } + + public static void ResolveInside(object path) { } + + public static bool IsInside(T path) => true; + } + """; + + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync(code + "\n" + Guards); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheCallIsNotAnUncontainedPathCombine() + { + return VerifyAsync(""" + using System.IO; + class Own + { + public static string Combine(string a, string b) => a + b; + } + + class C + { + string M(DirectoryInfo root, string leaf, string third) + { + var a = Path.Join(root.FullName, leaf); + var b = Path.Combine(root.FullName, leaf, third); + var c = Own.Combine(root.FullName, leaf); + var d = Path.Combine(root.Name, leaf); + var e = Path.Combine(leaf, root.FullName); + var f = Path.Combine(leaf, leaf); + var g = Combine(leaf, leaf); + return a + b + c + d + e + f + g; + } + + string Combine(string a, string b) => a + b; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ParenthesizedRootAndLeafThatIsNotANameProducer() + { + return VerifyAsync(""" + using System.IO; + class C + { + string Name(string value) => value; + + string M(DirectoryInfo root, string leaf) + { + var a = {|E128222:Path.Combine((root.FullName), leaf)|}; + var b = {|E128222:Path.Combine(root.FullName, Name(leaf))|}; + var c = {|E128222:Path.Combine(root.FullName, leaf.Trim())|}; + var d = {|E128222:Path.Combine(root.FullName, (leaf))|}; + return a + b + c + d; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLeafComesFromANameProducer() + { + return VerifyAsync(""" + using System.IO; + class C + { + static string SanitizeFileName(string value) => value; + + string M(DirectoryInfo root, string leaf) + { + var a = Path.Combine(root.FullName, Path.GetFileNameWithoutExtension(leaf)); + var b = Path.Combine(root.FullName, Path.ChangeExtension(leaf, ".txt")); + var c = Path.Combine(root.FullName, Path.GetTempFileName()); + var d = Path.Combine(root.FullName, (Path.GetFileName(leaf))); + var e = Path.Combine(root.FullName, SanitizeFileName(leaf)); + return a + b + c + d + e; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Handles_InterpolatedLeavesByTheirHolesAndText() + { + return VerifyAsync(""" + using System.IO; + class C + { + string M(DirectoryInfo root, int index, long big, double ratio, string text, object boxed, decimal money) + { + var a = Path.Combine(root.FullName, $"file{index}.txt"); + var b = Path.Combine(root.FullName, $"{big}-{ratio}-{money}"); + var c = {|E128222:Path.Combine(root.FullName, $"file{text}.txt")|}; + var d = {|E128222:Path.Combine(root.FullName, $"file{boxed}")|}; + var e = {|E128222:Path.Combine(root.FullName, $"a\\{index}")|}; + var f = {|E128222:Path.Combine(root.FullName, $"..{index}")|}; + var g = {|E128222:Path.Combine(root.FullName, $"{index}/x")|}; + var h = Path.Combine(root.FullName, $"plain"); + var i = {|E128222:Path.Combine(root.FullName, $"{index}" + text)|}; + return a + b + c + d + e + f + g + h + i; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAGuardCallReceivesTheJoinThroughLocalsFieldsOrAWrapper() + { + return VerifyAsync(""" + using System.IO; + class C + { + private string stored = ""; + + private string Prop { get; set; } = ""; + + void ByLocal(DirectoryInfo root, string leaf) + { + var joined = Path.Combine(root.FullName, leaf); + Guard.IsInside(joined); + } + + void ByChain(DirectoryInfo root, string leaf) + { + var first = Path.Combine(root.FullName, leaf); + var second = first; + var third = (second); + Guard.ValidateDomainPath(third); + } + + void ByAssignment(DirectoryInfo root, string leaf) + { + string target; + target = Path.Combine(root.FullName, leaf); + Guard.ResolveInside(target); + } + + void ByField(DirectoryInfo root, string leaf) + { + stored = Path.Combine(root.FullName, leaf); + Guard.IsInside(this.stored); + } + + void ByThisProperty(DirectoryInfo root, string leaf) + { + this.Prop = Path.Combine(root.FullName, leaf); + Guard.IsInside(this.Prop); + } + + void ByWrapper(DirectoryInfo root, string leaf) + { + Guard.IsInside(new FileInfo(Path.Combine(root.FullName, leaf))); + Guard.IsInside((Path.Combine(root.FullName, leaf))); + } + + void ByGeneric(DirectoryInfo root, string leaf) + { + var joined = Path.Combine(root.FullName, leaf); + Guard.IsInside(joined); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheGuardSeesAnotherValueOrIsOutOfScope() + { + return VerifyAsync(""" + using System; + using System.IO; + class C + { + void Other(DirectoryInfo root, string leaf, string unrelated) + { + var joined = {|E128222:Path.Combine(root.FullName, leaf)|}; + Guard.IsInside(unrelated); + Guard.IsInside(joined.Length); + Guard.IsInside(unrelated + unrelated); + } + + void Lambda(DirectoryInfo root, string leaf) + { + Func make = () => {|E128222:Path.Combine(root.FullName, leaf)|}; + Guard.IsInside(make()); + } + + void LocalFunction(DirectoryInfo root, string leaf) + { + string Make() => {|E128222:Path.Combine(root.FullName, leaf)|}; + Guard.IsInside(Make()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Handles_JoinsInConstructorsAccessorsAndFieldInitializers() + { + return VerifyAsync(""" + using System.IO; + class C + { + private static readonly DirectoryInfo Root = new DirectoryInfo("."); + + private static string leaf = ""; + + private readonly string field = {|E128222:Path.Combine(Root.FullName, leaf)|}; + + private readonly string guarded = Path.Combine(Root.FullName, leaf); + + private string Prop { get; } = Path.Combine(Root.FullName, leaf); + + C() + { + var joined = {|E128222:Path.Combine(Root.FullName, leaf)|}; + } + + string Property + { + get + { + var joined = {|E128222:Path.Combine(Root.FullName, leaf)|}; + return joined; + } + } + + void Check() + { + Guard.IsInside(guarded); + Guard.IsInside(this.Prop); + } + + ~C() + { + var joined = {|E128222:Path.Combine(Root.FullName, leaf)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixBranchCoverageTests.cs new file mode 100644 index 00000000..ac7d57f3 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UncontainedRootJoinCodeFixBranchCoverageTests.cs @@ -0,0 +1,100 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UncontainedRootJoinCodeFixBranchCoverageTests +{ + private const string Containment = """ + namespace Pug.Core + { + public static class FilePathContainment + { + public static System.IO.FileInfo ResolveInside(System.IO.DirectoryInfo root, string leaf) + => new System.IO.FileInfo(leaf); + } + } + """; + + private static Task NoFixAsync(string source) + { + return CodeFixTestRunner.NoFixAsync( + source + "\n" + Containment); + } + + [Fact] + [Trait("Category", "CI")] + public Task CodeFix_HandlesAQualifiedTypeAndParenthesizedOperands() + { + return CodeFixTestRunner.RunAsync( + """ + using Pug.Core; + using System.IO; + + class C + { + FileInfo M(DirectoryInfo root, string leaf) + { + return new System.IO.FileInfo(({|E128222:Path.Combine((root.FullName), (leaf))|})); + } + } + """ + "\n" + Containment, + """ + using Pug.Core; + using System.IO; + + class C + { + FileInfo M(DirectoryInfo root, string leaf) + { + return FilePathContainment.ResolveInside(root, (leaf)); + } + } + """ + "\n" + Containment); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenAnotherTypeIsNamedFileInfo() + { + return NoFixAsync(""" + using System.IO; + + namespace Other + { + public sealed class FileInfo + { + public FileInfo(string path) { } + } + } + + class C + { + Other.FileInfo M(DirectoryInfo root, string leaf) + { + return new Other.FileInfo({|E128222:Path.Combine(root.FullName, leaf)|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheJoinFeedsADifferentConstructionOrATargetTypedOne() + { + return NoFixAsync(""" + using System.IO; + + class C + { + void M(DirectoryInfo root, string leaf) + { + var reader = new StreamReader({|E128222:Path.Combine(root.FullName, leaf)|}); + FileInfo info = new({|E128222:Path.Combine(root.FullName, leaf)|}); + var text = {|E128222:Path.Combine(root.FullName, leaf)|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnguardedSplitIndexBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnguardedSplitIndexBranchCoverageTests.cs new file mode 100644 index 00000000..7aa01183 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnguardedSplitIndexBranchCoverageTests.cs @@ -0,0 +1,228 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the array origins and length guards that the split index rule reads. +/// +public sealed class UnguardedSplitIndexBranchCoverageTests +{ + private const string Header = """ + class Splitter + { + public string[] Split(char separator) => new[] { "a" }; + } + + """; + + private static Task VerifyAsync(string members, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + Header + "class C\n{\n" + members + "\n}\n", + expected: null, + options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheSplitBelongsToAnotherType() + { + return VerifyAsync(""" + string M(Splitter splitter) + { + return splitter.Split(',')[1]; + } + + string N(Splitter splitter) + { + var parts = splitter.Split(','); + return parts[1]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalComesFromAnotherInvocation() + { + return VerifyAsync(""" + string[] Make() => new[] { "a" }; + + string M() + { + var parts = Make(); + return parts[1]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalComesFromANonInvocation() + { + return VerifyAsync(""" + string M() + { + string[] parts = new[] { "a" }; + return parts[1]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalHasNoInitializer() + { + return VerifyAsync(""" + string M(string line) + { + string[] parts; + parts = line.Split(','); + return parts[1]; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsALoopVariable() + { + return VerifyAsync(""" + string M(string[][] rows) + { + foreach (var parts in rows) + { + return parts[1]; + } + + return string.Empty; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheArrayIsAParameterOrAField() + { + return VerifyAsync(""" + private readonly string[] _parts = new[] { "a" }; + + string M(string[] parts) => parts[1]; + + string N() => _parts[1]; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_TheLocalThatHoldsTheSplitInAMultiDeclarator() + { + return VerifyAsync(""" + string M(string line) + { + string[] first = line.Split(','), second = line.Split(';'); + return {|E128170:second[1]|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenOnlyAnotherArrayHasItsLengthRead() + { + return VerifyAsync(""" + string M(string line, string[] other) + { + var parts = line.Split(','); + if (other.Length > 2) + { + return {|E128170:parts[1]|}; + } + + return string.Empty; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheMemberAccessBeforeTheIndexIsNotLength() + { + return VerifyAsync(""" + string M(string line) + { + var parts = line.Split(','); + var count = parts.Rank; + return {|E128170:parts[1]|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheNullConditionalReadIsNotLength() + { + return VerifyAsync(""" + string M(string line) + { + var parts = line.Split(','); + var rank = parts?.Rank; + var first = parts?[0]; + return {|E128170:parts[1]|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenThePatternBeforeTheIndexChecksNoLength() + { + return VerifyAsync(""" + string M(string line) + { + var parts = line.Split(','); + var notNull = parts is not null; + var typed = parts is string[] copy; + var ranked = parts is { Rank: 1 }; + return {|E128170:parts[1]|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALengthPropertyPatternPrecedesTheIndex() + { + return VerifyAsync(""" + string M(string line) + { + var parts = line.Split(','); + if (parts is { Length: > 1 }) + { + return parts[1]; + } + + return string.Empty; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAPositionalPatternHasNoPropertyClause() + { + return VerifyAsync( + """ + string M(string line) + { + var parts = line.Split(','); + var matched = parts is string[] (); + return {|E128170:parts[1]|}; + } + """, + new AnalyzerTestOptions { CompilerDiagnostics = CompilerDiagnostics.None }); + } +} diff --git a/tests/E128.Analyzers.Tests/UnionTypesBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnionTypesBranchCoverageTests.cs new file mode 100644 index 00000000..87b58306 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnionTypesBranchCoverageTests.cs @@ -0,0 +1,71 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnionTypesBranchCoverageTests +{ + private static INamedTypeSymbol Compile(string code, string typeName) + { + var tree = CSharpSyntaxTree.ParseText(code, cancellationToken: TestContext.Current.CancellationToken); + var compilation = CSharpCompilation.Create( + "UnionProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + return compilation.GetTypeByMetadataName(typeName)!; + } + + [Fact] + [Trait("Category", "CI")] + public void IsUnion_IsFalseForNull() + { + Assert.False(UnionTypes.IsUnion(null)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("enum Probe { A }")] + [InlineData("interface Probe { }")] + [InlineData("delegate void Probe();")] + public void IsUnion_IsFalseForTypesThatAreNeitherClassNorStruct(string declaration) + { + Assert.False(UnionTypes.IsUnion(Compile(declaration, "Probe"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("class")] + [InlineData("struct")] + public void IsUnion_IsTrueForATypeWithTheCompilerUnionInterface(string kind) + { + var code = "namespace System.Runtime.CompilerServices { public interface IUnion { } }\n" + + kind + " Probe : System.Runtime.CompilerServices.IUnion { }"; + Assert.True(UnionTypes.IsUnion(Compile(code, "Probe"))); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("namespace Other { public interface IUnion { } }", "Other.IUnion")] + [InlineData("namespace CompilerServices { public interface IUnion { } }", "CompilerServices.IUnion")] + [InlineData("namespace Other.CompilerServices { public interface IUnion { } }", "Other.CompilerServices.IUnion")] + [InlineData("namespace Runtime.CompilerServices { public interface IUnion { } }", "Runtime.CompilerServices.IUnion")] + [InlineData("namespace Other.Runtime.CompilerServices { public interface IUnion { } }", "Other.Runtime.CompilerServices.IUnion")] + [InlineData("namespace System.CompilerServices { public interface IUnion { } }", "System.CompilerServices.IUnion")] + [InlineData("namespace System.Runtime.Other { public interface IUnion { } }", "System.Runtime.Other.IUnion")] + [InlineData("namespace Outer.System.Runtime.CompilerServices { public interface IUnion { } }", "Outer.System.Runtime.CompilerServices.IUnion")] + [InlineData("namespace System.Runtime.CompilerServices { public interface IUnionLike { } }", "System.Runtime.CompilerServices.IUnionLike")] + [InlineData("public interface IUnion { }", "IUnion")] + public void IsUnion_IsFalseWhenTheInterfaceSitsInAnotherNamespace(string interfaceDeclaration, string interfaceName) + { + var code = interfaceDeclaration + "\nclass Probe : " + interfaceName + " { }"; + Assert.False(UnionTypes.IsUnion(Compile(code, "Probe"))); + } + + [Fact] + [Trait("Category", "CI")] + public void IsUnion_IsFalseForAPlainClass() + { + Assert.False(UnionTypes.IsUnion(Compile("class Probe { }", "Probe"))); + } +} diff --git a/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerBranchCoverageTests.cs new file mode 100644 index 00000000..b99252e4 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnionValueReadAnalyzerBranchCoverageTests.cs @@ -0,0 +1,126 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnionValueReadAnalyzerBranchCoverageTests +{ + private static Task VerifyAsync(string code) + { + return AnalyzerTestRunner.VerifyAsync( + code, + options: new AnalyzerTestOptions + { + LanguageVersion = LanguageVersion.Preview, + Sources = [UnionTestRuntime.StubSource], + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAValuePropertyOnAHandWrittenUnion() + { + return VerifyAsync(""" + struct Outcome : System.Runtime.CompilerServices.IUnion + { + public object Value => 1; + } + + class C + { + object M(Outcome outcome) => {|E128221:outcome.Value|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnExplicitCastFromAUnion() + { + return VerifyAsync(""" + struct Outcome : System.Runtime.CompilerServices.IUnion + { + public static explicit operator int(Outcome value) => 1; + } + + class C + { + int M(Outcome outcome) => {|E128221:(int)outcome|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnIdentityCastAndANonUnionCast() + { + return VerifyAsync(""" + struct Outcome : System.Runtime.CompilerServices.IUnion + { + } + + class C + { + Outcome M(Outcome outcome) => (Outcome)outcome; + int N(long value) => (int)value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAFieldNamedValueOnAUnion() + { + return VerifyAsync(""" + struct Outcome : System.Runtime.CompilerServices.IUnion + { + public int Value; + } + + class C + { + int M(Outcome outcome) => outcome.Value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnInheritedValueProperty() + { + return VerifyAsync(""" + class Base + { + public int Value => 1; + } + + class Outcome : Base, System.Runtime.CompilerServices.IUnion + { + } + + class C + { + int M(Outcome outcome) => outcome.Value; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForOtherMembersOnAUnion() + { + return VerifyAsync(""" + struct Outcome : System.Runtime.CompilerServices.IUnion + { + public int Other => 1; + } + + class C + { + int M(Outcome outcome) => outcome.Other; + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnregisteredServiceResolveBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnregisteredServiceResolveBranchCoverageTests.cs new file mode 100644 index 00000000..7bc9248d --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnregisteredServiceResolveBranchCoverageTests.cs @@ -0,0 +1,349 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Microsoft.CodeAnalysis.Testing; +using Xunit; + +namespace E128.Analyzers.Tests; + +/// +/// Covers the registration and resolve shapes of the DI rule with local stand-ins for the +/// dependency injection API, so the tests need no package download. +/// +public sealed class UnregisteredServiceResolveBranchCoverageTests +{ + private const string Stubs = """ + using System; + using System.Net.Http; + using Microsoft.Extensions.DependencyInjection; + + namespace System.Net.Http + { + public interface IHttpClientFactory + { + HttpClient CreateClient(string name); + } + } + + namespace Microsoft.Extensions.DependencyInjection + { + public interface IServiceCollection + { + } + + public static class ServiceProviderServiceExtensions + { + public static T GetRequiredService(this IServiceProvider provider) where T : notnull => default!; + + public static object GetRequiredService(this IServiceProvider provider, Type serviceType) => default!; + } + + public static class ServiceCollectionServiceExtensions + { + public static IServiceCollection AddSingleton(this IServiceCollection services) where T : class => services; + + public static IServiceCollection AddSingleton(this IServiceCollection services, Type service, Type implementation) => services; + } + + public static class HttpClientFactoryServiceCollectionExtensions + { + public static IServiceCollection AddHttpClient(this IServiceCollection services, string name) => services; + + public static IServiceCollection AddHttpClient(this IServiceCollection services) where T : class => services; + } + } + + class Service + { + } + + """; + + private static readonly AnalyzerTestOptions Options = new() { MarkupOptions = MarkupOptions.UseFirstDescriptor }; + + private static Task VerifyAsync(string source, AnalyzerTestOptions? options = null) + { + return AnalyzerTestRunner.VerifyAsync( + Stubs + source, + expected: null, + options ?? Options); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResolveSitsInALambdaThatIsNotAnArgument() + { + return VerifyAsync(""" + class C + { + void M() + { + Func create = sp => {|E128103:sp.GetRequiredService()|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResolveSitsInALambdaPassedToANonRegistrationCall() + { + return VerifyAsync(""" + class C + { + static void Run(Func create) + { + } + + void M() + { + Run(sp => {|E128103:sp.GetRequiredService()|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResolveSitsInALambdaPassedToAnIndexedCallback() + { + return VerifyAsync(""" + class C + { + void M(Action>[] callbacks) + { + callbacks[0](sp => {|E128103:sp.GetRequiredService()|}); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResolveSitsInAnAddFactoryLambda() + { + return VerifyAsync(""" + static class Extensions + { + public static IServiceCollection AddThing(this IServiceCollection services, Func factory) => services; + } + + class C + { + void M(IServiceCollection services) + { + services.AddThing(sp => sp.GetRequiredService()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResolveUsesATypeArgumentThatIsNotNamed() + { + return VerifyAsync(""" + class C + { + void M(IServiceProvider provider) + where T : notnull + { + provider.GetRequiredService(); + provider.GetRequiredService(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResolveUsesTheNonGenericOverload() + { + return VerifyAsync(""" + class C + { + void M(IServiceProvider provider) + { + provider.GetRequiredService(typeof(Service)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheInvokedExpressionHasNoName() + { + return VerifyAsync(""" + class C + { + void M(Action[] actions) + { + actions[0](); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnAddCallDoesNotBind() + { + return VerifyAsync( + """ + class C + { + void M(IServiceCollection services) + { + services.AddMissing(); + services.GetRequiredService(); + } + } + """, + new AnalyzerTestOptions + { + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CompilerDiagnostics = CompilerDiagnostics.None + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRegistrationUsesTypeArgumentsThatAreNotNamed() + { + return VerifyAsync(""" + class C + { + void M(IServiceCollection services) + where T : class + { + services.AddSingleton(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_OnlyParametersThatCanBeServices() + { + return VerifyAsync(""" + struct Settings + { + } + + class Missing + { + } + + class Consumer + { + public Consumer(int count, string name, Settings settings, Service[] items, {|E128103:Missing missing|}) + { + } + } + + class C + { + void M(IServiceCollection services) + { + services.AddSingleton(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheNamedClientCallDoesNotBind() + { + return VerifyAsync( + """ + class C + { + void M(IServiceCollection services, IHttpClientFactory factory) + { + services.AddHttpClient(missing); + factory.CreateClient(missing); + unknown.CreateClient("x"); + } + } + """, + new AnalyzerTestOptions + { + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CompilerDiagnostics = CompilerDiagnostics.None + }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheClientNameIsNotAConstant() + { + return VerifyAsync(""" + class C + { + void M(IHttpClientFactory factory, string name) + { + factory.CreateClient(name); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheRegisteredClientNameIsEmpty() + { + return VerifyAsync(""" + class C + { + void M(IServiceCollection services, IHttpClientFactory factory) + { + services.AddHttpClient(""); + factory.CreateClient(""); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTypedClientRegistrationCarriesNoName() + { + return VerifyAsync(""" + class C + { + void M(IServiceCollection services) + { + services.AddHttpClient(); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheOpenGenericRegistrationNamesAnotherType() + { + return VerifyAsync(""" + interface IRepo + { + } + + class Repo : IRepo + { + } + + class C + { + void M(IServiceCollection services, IServiceProvider provider) + { + services.AddSingleton(typeof(IRepo<>), typeof(Repo<>)); + services.AddSingleton(Type.GetType("x")!, Type.GetType("y")!); + provider.GetRequiredService>(); + {|E128103:provider.GetRequiredService()|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..b4a4c42e --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnsafeBooleanConversionsCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,110 @@ +using System.Threading.Tasks; +using E128.Analyzers.Unsafe; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnsafeBooleanConversionsCodeFixProviderBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReadsAMemberWithoutAddingParentheses() + { + return VerifyFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + private int _value; + bool M() => {|E128115:Unsafe.As(ref this._value)|}; + } + """, + """ + using System.Runtime.CompilerServices; + class C + { + private int _value; + bool M() => (this._value != 0); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReadsAnArrayElementWithoutAddingParentheses() + { + return VerifyFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + bool M(int[] values) => {|E128115:Unsafe.As(ref values[0])|}; + } + """, + """ + using System.Runtime.CompilerServices; + class C + { + bool M(int[] values) => (values[0] != 0); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ReadsARefReturningCallWithoutAddingParentheses() + { + return VerifyFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + private bool _flag; + ref bool GetFlag() => ref _flag; + int M() => {|E128115:Unsafe.As(ref GetFlag())|}; + } + """, + """ + using System.Runtime.CompilerServices; + class C + { + private bool _flag; + ref bool GetFlag() => ref _flag; + int M() => (GetFlag() ? 1 : 0); + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_ParenthesizesAConditionalRefExpression() + { + return VerifyFixAsync( + """ + using System.Runtime.CompilerServices; + class C + { + bool M(bool choice, ref int first, ref int second) + { + return {|E128115:Unsafe.As(ref (choice ? ref first : ref second))|}; + } + } + """, + """ + using System.Runtime.CompilerServices; + class C + { + bool M(bool choice, ref int first, ref int second) + { + return (((choice ? ref first : ref second)) != 0); + } + } + """); + } + +} diff --git a/tests/E128.Analyzers.Tests/UntimedProcessExitBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UntimedProcessExitBranchCoverageTests.cs new file mode 100644 index 00000000..2022ab20 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UntimedProcessExitBranchCoverageTests.cs @@ -0,0 +1,152 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UntimedProcessExitBranchCoverageTests +{ + private const string Usings = "using System;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\n"; + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheTokenIsCancellationTokenNone() + { + return AnalyzerTestRunner.VerifyAsync(Usings + """ + class C + { + async Task M(Process process) + { + await {|E128099:process.WaitForExitAsync(CancellationToken.None)|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenComesFromAnotherSource() + { + return AnalyzerTestRunner.VerifyAsync(Usings + """ + class C + { + private readonly CancellationTokenSource _source = new(TimeSpan.FromSeconds(5)); + private CancellationToken Token => _source.Token; + + async Task M(Process process, CancellationTokenSource parameterSource) + { + var local = _source.Token; + await process.WaitForExitAsync(local); + await process.WaitForExitAsync(Token); + await process.WaitForExitAsync(_source.Token); + await process.WaitForExitAsync(parameterSource.Token); + await process.WaitForExitAsync(default); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheWaitIsOnAnotherType() + { + return AnalyzerTestRunner.VerifyAsync(Usings + """ + class Waiter + { + public void WaitForExit() { } + public Task WaitForExitAsync(CancellationToken token) => Task.CompletedTask; + } + class C + { + async Task M(Waiter waiter) + { + waiter.WaitForExit(); + await waiter.WaitForExitAsync(CancellationToken.None); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAnUnqualifiedOrDifferentlyNamedCall() + { + return AnalyzerTestRunner.VerifyAsync(Usings + """ + class C + { + void M(Process process) + { + process.Start(); + Local(); + + static void Local() { } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_AddsTheTimeoutWhenTheTokenIsCancellationTokenNone() + { + return CodeFixTestRunner.RunAsync( + Usings + """ + class C + { + async Task M(Process process) + { + await {|E128099:process.WaitForExitAsync(CancellationToken.None)|}; + } + } + """, + Usings + """ + class C + { + async Task M(Process process) + { + { + using var __timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + try + { + await process.WaitForExitAsync(__timeoutCts.Token); + } + catch (OperationCanceledException) when (__timeoutCts.IsCancellationRequested) + { + process.Kill(true); + } + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheSyncWaitIsNotAStatement() + { + return CodeFixTestRunner.NoFixAsync( + Usings + """ + class C + { + void M(Process process) => {|E128099:process.WaitForExit()|}; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task NoFix_WhenTheAsyncWaitIsNotAwaitedInAStatement() + { + return CodeFixTestRunner.NoFixAsync( + Usings + """ + class C + { + Task M(Process process) + { + var pending = {|E128099:process.WaitForExitAsync()|}; + return pending; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnusedInterfaceParamCodeFixProviderBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnusedInterfaceParamCodeFixProviderBranchCoverageTests.cs new file mode 100644 index 00000000..7807d328 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnusedInterfaceParamCodeFixProviderBranchCoverageTests.cs @@ -0,0 +1,78 @@ +using System.Threading.Tasks; +using E128.Analyzers.Design; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnusedInterfaceParamCodeFixProviderBranchCoverageTests +{ + [Fact] + [Trait("Category", "CI")] + public Task Fix_PrefixesAnUnusedParameterWithAnUnderscore() + { + return CodeFixTestRunner.RunAsync( + """ + interface IProcessor + { + string Process(string input); + } + + class Processor : IProcessor + { + public string Process({|E128059:string input|}) + { + return "constant"; + } + } + """, + """ + interface IProcessor + { + string Process(string input); + } + + class Processor : IProcessor + { + public string Process(string _input) + { + return "constant"; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task FixAll_RenamesEveryUnusedParameterInTheDocument() + { + return CodeFixTestRunner.RunAsync( + """ + interface IProcessor + { + string Process(string input, int count); + } + + class Processor : IProcessor + { + public string Process({|E128059:string input|}, {|E128059:int count|}) + { + return "constant"; + } + } + """, + """ + interface IProcessor + { + string Process(string input, int count); + } + + class Processor : IProcessor + { + public string Process(string _input, int _count) + { + return "constant"; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageTests.cs new file mode 100644 index 00000000..f3eab5aa --- /dev/null +++ b/tests/E128.Analyzers.Tests/UnvalidatedJwtIdentityBranchCoverageTests.cs @@ -0,0 +1,763 @@ +using System.Threading.Tasks; +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UnvalidatedJwtIdentityBranchCoverageTests +{ + private const string TokenBaseStub = """ + namespace Microsoft.IdentityModel.Tokens + { + public class SecurityToken { } + public class TokenValidationParameters { } + public class TokenValidationResult { public bool IsValid { get; set; } } + } + """; + + private const string JwtStub = """ + namespace System.IdentityModel.Tokens.Jwt + { + public class JwtSecurityToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public JwtSecurityToken() { } + public JwtSecurityToken(string token) { } + public System.Collections.Generic.IEnumerable Claims => []; + } + public class JwtSecurityTokenHandler + { + public virtual JwtSecurityToken ReadJwtToken(string token) => new(); + public virtual System.Security.Claims.ClaimsPrincipal ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken) + { + validatedToken = new(); + return new(); + } + public virtual System.Threading.Tasks.Task ValidateTokenAsync(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => System.Threading.Tasks.Task.FromResult(new Microsoft.IdentityModel.Tokens.TokenValidationResult()); + } + } + """; + + private const string JsonStub = """ + namespace Microsoft.IdentityModel.JsonWebTokens + { + public class JsonWebToken : Microsoft.IdentityModel.Tokens.SecurityToken + { + public System.Collections.Generic.IEnumerable Claims => []; + public System.Security.Claims.Claim GetClaim(string name) => new(name, string.Empty); + public bool TryGetClaim(string name, out System.Security.Claims.Claim claim) + { + claim = GetClaim(name); + return true; + } + } + public class JsonWebTokenHandler + { + public virtual JsonWebToken ReadJsonWebToken(string token) => new(); + public virtual Microsoft.IdentityModel.Tokens.TokenValidationResult ValidateToken(string token, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) => new(); + } + } + """; + + private const string HttpStub = """ + namespace Microsoft.AspNetCore.Http + { + public abstract class HttpContext + { + public abstract System.Security.Claims.ClaimsPrincipal User { get; set; } + } + } + """; + + private const string TicketStub = """ + namespace Microsoft.AspNetCore.Authentication + { + public class AuthenticationTicket + { + public AuthenticationTicket(System.Security.Claims.ClaimsPrincipal principal, string authenticationScheme) { } + } + } + """; + + private static readonly string FullStubs = string.Join("\n", TokenBaseStub, JwtStub, JsonStub, HttpStub, TicketStub); + + private static Task VerifyAsync(string source) + { + return VerifyWithAsync(source, FullStubs); + } + + private static Task VerifyWithAsync(string source, string stubs) + { + return AnalyzerTestRunner.VerifyAsync( + source, + options: new AnalyzerTestOptions { Sources = [stubs] }); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AJsonHandlerTicketWhenNoJwtHandlerOrHttpContextExists() + { + return VerifyWithAsync( + """ + using System.Security.Claims; + using Microsoft.AspNetCore.Authentication; + using Microsoft.IdentityModel.JsonWebTokens; + class C + { + AuthenticationTicket M(JsonWebTokenHandler handler, string token) + { + return {|E128202:new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(handler.ReadJsonWebToken(token).Claims, "jwt")), "jwt")|}; + } + } + """, + string.Join("\n", TokenBaseStub, JsonStub, TicketStub)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNoTokenHandlerTypeExists() + { + return VerifyWithAsync( + """ + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, ClaimsIdentity identity) + { + context.User = new ClaimsPrincipal(identity); + } + } + """, + string.Join("\n", TokenBaseStub, HttpStub)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenNeitherAnHttpContextNorATicketTypeExists() + { + return VerifyWithAsync( + """ + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + class C + { + ClaimsPrincipal M(JwtSecurityTokenHandler handler, string token) + { + return new ClaimsPrincipal(new ClaimsIdentity(handler.ReadJwtToken(token).Claims, "jwt")); + } + } + """, + string.Join("\n", TokenBaseStub, JwtStub)); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ADecodedTokenReadInAnIfElseBranch() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token, bool flag) + { + var parsed = handler.ReadJwtToken(token); + if (flag) + { + context.User = new ClaimsPrincipal(); + } + else + { + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheIdentityIsUnauthenticatedByAnEmptyOrNullType() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "")); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, null)); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenThePropertyIsNotTheUserOfAnHttpContext() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + class Session + { + public ClaimsPrincipal? User { get; set; } + + public ClaimsPrincipal? Other { get; set; } + } + + class C + { + void M(Session session, JwtSecurityTokenHandler handler, string token) + { + var parsed = handler.ReadJwtToken(token); + session.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + session.Other = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheTokenDoesNotComeFromAKnownDecoder() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class OwnHandler + { + public JwtSecurityToken ReadJwtToken(string token) => new(); + } + + class C + { + void M(HttpContext context, string token) + { + context.User = new ClaimsPrincipal(new ClaimsIdentity(new OwnHandler().ReadJwtToken(token).Claims, "jwt")); + context.User = new ClaimsPrincipal(new ClaimsIdentity(new JwtSecurityToken().Claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAClaimsLocalIsPassedByReferenceBeforeItIsUsed() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class Holder + { + public Holder(ref IEnumerable claims) { } + } + + class C + { + static void Mutate(ref IEnumerable claims) { } + + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var parsed = handler.ReadJwtToken(token); + var viaCall = parsed.Claims; + Mutate(ref viaCall); + context.User = new ClaimsPrincipal(new ClaimsIdentity(viaCall, "jwt")); + + var viaConstructor = parsed.Claims; + _ = new Holder(ref viaConstructor); + context.User = new ClaimsPrincipal(new ClaimsIdentity(viaConstructor, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAClaimsLocalComesFromAnOutArgumentOfAnotherMethod() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + static void Fill(out IEnumerable claims) { claims = []; } + + void M(HttpContext context) + { + Fill(out var claims); + context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_AClaimReadByTryGetClaim() + { + return VerifyAsync(""" + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.JsonWebTokens; + class C + { + void M(HttpContext context, JsonWebTokenHandler handler, string token) + { + var parsed = handler.ReadJsonWebToken(token); + if (parsed.TryGetClaim("sub", out var claim)) + { + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }, "jwt"))|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAFieldIsCoalesceAssignedAPrincipal() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + static class Registry + { + public static void Add(Claim claim) { } + } + + class C + { + ClaimsPrincipal? cached; + + void M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var parsed = handler.ReadJwtToken(token); + cached ??= new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + Registry.Add(new Claim("sub", "value")); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ATokenCapturedByTwoNestedLambdas() + { + return VerifyAsync(""" + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + class C + { + Action M(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var parsed = handler.ReadJwtToken(token); + return () => + { + Action inner = () => + { + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + }; + inner(); + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenANestedLambdaReadsTheValidationResultOfTheOuterBody() + { + return VerifyAsync(""" + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task M(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + return () => + { + Action inner = () => + { + if (result.IsValid) + { + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + }; + inner(); + }; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResultOfTheCheckIsNotFromAValidationCall() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + static class Checks + { + public static Task CheckAsync(string token) => Task.FromResult(new TokenValidationResult()); + } + + class C + { + Task Own(string token) => Task.FromResult(new TokenValidationResult()); + + async Task FromOwnMethod(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var result = await Own(token); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + async Task FromStaticHelper(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var result = await Checks.CheckAsync(token).ConfigureAwait(false); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheResultOfTheCheckComesFromAHandlerHelperOrANewResult() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class Handler : JwtSecurityTokenHandler + { + public Task Check(string token) => Task.FromResult(new TokenValidationResult()); + } + + class C + { + async Task FromHandlerMethod(HttpContext context, Handler handler, string token) + { + var result = await handler.Check(token); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void FromNewResult(HttpContext context, JwtSecurityTokenHandler handler, string token) + { + var result = new TokenValidationResult(); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheValidationResultIsReassignedOrPassedByReference() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + static void Reset(ref TokenValidationResult result) { } + + async Task Reassigned(HttpContext context, JwtSecurityTokenHandler handler, string token, string other, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + result = await handler.ValidateTokenAsync(other, parameters); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + async Task ByReference(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + Reset(ref result); + if (!result.IsValid) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResultGuardTakesAnyRecognizedShape() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task ComparedToTrue(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid == true) + { + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + + async Task AndedWithAnotherTest(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters, bool flag) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (flag && result.IsValid) + { + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResultGuardExitsOrBranchesOnTheFailedResult() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task ComparedToFalse(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (result.IsValid == false) + { + throw new System.InvalidOperationException(); + } + + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + + async Task FailedBranchWithElse(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (!result.IsValid) + { + System.Console.WriteLine("invalid"); + } + else + { + var parsed = handler.ReadJwtToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenTheFailedResultGuardDoesNotExit() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + async Task EmptyBlock(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (!result.IsValid) + { + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + async Task UnrelatedTest(HttpContext context, JwtSecurityTokenHandler handler, string token, TokenValidationParameters parameters, bool flag) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (!flag) + { + return; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + async Task LoopContinue(HttpContext context, JwtSecurityTokenHandler handler, string[] tokens, TokenValidationParameters parameters) + { + foreach (var token in tokens) + { + var result = await handler.ValidateTokenAsync(token, parameters); + if (!result.IsValid) + { + continue; + } + + var parsed = handler.ReadJwtToken(token); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenAnIteratorLeavesWithYieldBreakAfterAFailedResult() + { + return VerifyAsync(""" + using System.Collections.Generic; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.JsonWebTokens; + using Microsoft.IdentityModel.Tokens; + class C + { + IEnumerable M(HttpContext context, JsonWebTokenHandler handler, string token, TokenValidationParameters parameters) + { + var result = handler.ValidateToken(token, parameters); + if (!result.IsValid) + { + yield break; + } + + var parsed = handler.ReadJsonWebToken(token); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + yield return 1; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Classifies_TokensHeldInPropertiesByTheirStability() + { + return VerifyAsync(""" + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Http; + using Microsoft.IdentityModel.Tokens; + class C + { + string Auto { get; set; } = string.Empty; + + string Expression => string.Empty; + + string Block + { + get { return string.Empty; } + } + + string this[int index] => string.Empty; + + void Stable(HttpContext context, JwtSecurityTokenHandler handler, TokenValidationParameters parameters) + { + handler.ValidateToken(this.Auto, parameters, out _); + var parsed = handler.ReadJwtToken(Auto); + context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt")); + } + + void OtherInstance(HttpContext context, JwtSecurityTokenHandler handler, C other, TokenValidationParameters parameters) + { + handler.ValidateToken(other.Auto, parameters, out _); + var parsed = handler.ReadJwtToken(Auto); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void ExpressionBodied(HttpContext context, JwtSecurityTokenHandler handler, TokenValidationParameters parameters) + { + handler.ValidateToken(Expression, parameters, out _); + var parsed = handler.ReadJwtToken(Expression); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void BlockBodied(HttpContext context, JwtSecurityTokenHandler handler, TokenValidationParameters parameters) + { + handler.ValidateToken(Block, parameters, out _); + var parsed = handler.ReadJwtToken(Block); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + + void Indexed(HttpContext context, JwtSecurityTokenHandler handler, TokenValidationParameters parameters) + { + handler.ValidateToken(this[0], parameters, out _); + var parsed = handler.ReadJwtToken(this[0]); + {|E128202:context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"))|}; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UseAfterDisposeBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UseAfterDisposeBranchCoverageTests.cs new file mode 100644 index 00000000..c9a746c5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UseAfterDisposeBranchCoverageTests.cs @@ -0,0 +1,123 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UseAfterDisposeBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.IO;\nclass Res : IDisposable { public int Value; public void Dispose() { } public void Dispose(bool disposing) { } }\n" + + "class C\n{\n Res _field = new();\n void M(bool flag)\n {\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheDisposedReceiverIsAFieldOrAParameter() + { + return VerifyAsync(""" + _field.Dispose(); + var length = _field.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForADisposeOverloadWithArguments() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(true); + var value = res.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheDisposeIsInsideABracelessIf() + { + return VerifyAsync(""" + var res = new Res(); + if (flag) res.Dispose(); + var value = res.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAMemberReadAfterTheDispose() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(); + var value = {|E128162:res|}.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsReassignedBeforeTheNextRead() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(); + res = new Res(); + var value = res.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForNonMemberUsesAfterTheDispose() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(); + var name = nameof(res.Value); + var isNull = res is null; + var same = res == null; + res.Dispose(); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALambdaOrLocalFunctionReadsTheLocal() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(); + Func read = () => res.Value; + int Local() => res.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenAnIgnorableUseSitsBeforeTheMemberRead() + { + return VerifyAsync(""" + var res = new Res(); + res.Dispose(); + var isNull = res is null; + var value = {|E128162:res|}.Value; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForADisposeOnAnUnrelatedInvocationShape() + { + return VerifyAsync(""" + var res = new Res(); + Dispose(); + Action action = res.Dispose; + var stream = new MemoryStream(); + stream.Dispose(); + + static void Dispose() { } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/UsingDirectivesBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/UsingDirectivesBranchCoverageTests.cs new file mode 100644 index 00000000..9eebe3b5 --- /dev/null +++ b/tests/E128.Analyzers.Tests/UsingDirectivesBranchCoverageTests.cs @@ -0,0 +1,93 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class UsingDirectivesBranchCoverageTests +{ + private static string Add(string code, string ns) + { + var root = SyntaxFactory.ParseCompilationUnit(code); + return UsingDirectives.AddIfMissing(root, ns).NormalizeWhitespace(eol: "\n").ToFullString(); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_ReturnsANodeThatIsNotACompilationUnitUnchanged() + { + var node = SyntaxFactory.ParseStatement("return;"); + Assert.Same(node, UsingDirectives.AddIfMissing(node, "System.IO")); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_KeepsAFileThatHasTheDirective() + { + const string code = "using System.IO;\nclass C { }\n"; + Assert.Equal(SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(eol: "\n").ToFullString(), Add(code, "System.IO")); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_InsertsAfterTheLastDirectiveThatSortsBefore() + { + Assert.Equal( + "using System;\nusing System.IO;\nusing System.Text;\n\nclass C\n{\n}", + Add("using System;\nusing System.Text;\nclass C { }\n", "System.IO")); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_InsertsAtTheEndWhenEveryDirectiveSortsBefore() + { + Assert.Equal( + "using System;\nusing System.IO;\n\nclass C\n{\n}", + Add("using System;\nclass C { }\n", "System.IO")); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_MovesTheFileHeaderFromTheFirstDirective() + { + var result = Add("// header\nusing System.Text;\nclass C { }\n", "System.IO"); + Assert.StartsWith("// header\nusing System.IO;\nusing System.Text;", result, System.StringComparison.Ordinal); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_MovesTheFileHeaderFromTheFirstMemberWhenThereAreNoDirectives() + { + var result = Add("// header\nclass C { }\n", "System.IO"); + Assert.StartsWith("// header\nusing System.IO;", result, System.StringComparison.Ordinal); + Assert.Contains("class C", result, System.StringComparison.Ordinal); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_WorksForAnEmptyFile() + { + Assert.StartsWith("using System.IO;", Add(string.Empty, "System.IO"), System.StringComparison.Ordinal); + } + + [Fact] + [Trait("Category", "CI")] + public void AddIfMissing_WorksForAFileWithoutLeadingTrivia() + { + Assert.StartsWith("using System.IO;", Add("class C { }", "System.IO"), System.StringComparison.Ordinal); + } + + [Fact] + [Trait("Category", "CI")] + public async System.Threading.Tasks.Task EnsureAddedAsync_AddsTheDirectiveToTheDocument() + { + using var workspace = new AdhocWorkspace(); + var document = workspace.AddProject("P", LanguageNames.CSharp).AddDocument("Test.cs", "class C { }"); + + var result = await UsingDirectives.EnsureAddedAsync(document, "System.IO", TestContext.Current.CancellationToken); + + var root = await result.GetSyntaxRootAsync(TestContext.Current.CancellationToken); + Assert.NotNull(root); + Assert.StartsWith("using System.IO;", root.NormalizeWhitespace().ToFullString(), System.StringComparison.Ordinal); + } +} diff --git a/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralBranchCoverageTests.cs new file mode 100644 index 00000000..70bd20ca --- /dev/null +++ b/tests/E128.Analyzers.Tests/Utf8GetBytesLiteralBranchCoverageTests.cs @@ -0,0 +1,252 @@ +using System.Threading.Tasks; +using E128.Analyzers.Performance; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class Utf8GetBytesLiteralBranchCoverageTests +{ + private static Task VerifyFixAsync(string source, string fixedCode) + { + return CodeFixTestRunner.RunAsync(source, fixedCode); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_ForOtherEncodingsAndMembers() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System; + using System.Text; + class Custom + { + public static Custom UTF8 => new(); + + public byte[] GetBytes(string text) => new byte[1]; + } + + class C + { + void M(string value, byte[] buffer) + { + _ = Encoding.ASCII.GetBytes("abc"); + _ = Encoding.UTF8.GetByteCount("abc"); + _ = Encoding.UTF8.GetBytes($"abc{value}"); + _ = Encoding.UTF8.GetBytes("abc".AsSpan(), buffer); + _ = Custom.UTF8.GetBytes("abc"); + _ = Encoding.UTF8.GetString(buffer); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Analyzer_Silent_WhenGetBytesIsNotCalledOnAMemberOfAMember() + { + return AnalyzerTestRunner.VerifyAsync(""" + using System.Text; + class C + { + void M(UTF8Encoding utf8) + { + _ = utf8.GetBytes("abc"); + _ = (Encoding.UTF8).GetBytes("abc"); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_PassesTheLiteralToAConstructorTakingAByteSpan() + { + return VerifyFixAsync( + """ + using System; + using System.Text; + class Holder + { + public Holder(ReadOnlySpan bytes) + { + } + } + + class C + { + void N() + { + _ = new Holder({|E128141:Encoding.UTF8.GetBytes("abc")|}); + Holder holder = new({|E128141:Encoding.UTF8.GetBytes("def")|}); + } + } + """, + """ + using System; + using System.Text; + class Holder + { + public Holder(ReadOnlySpan bytes) + { + } + } + + class C + { + void N() + { + _ = new Holder("abc"u8); + Holder holder = new("def"u8); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheArrayWhenAnIndexerTakesIt() + { + return VerifyFixAsync( + """ + using System; + using System.Text; + class Table + { + public int this[byte[] key] => key.Length; + } + + class C + { + int N(Table table) + { + return table[{|E128141:Encoding.UTF8.GetBytes("abc")|}]; + } + } + """, + """ + using System; + using System.Text; + class Table + { + public int this[byte[] key] => key.Length; + } + + class C + { + int N(Table table) + { + return table["abc"u8.ToArray()]; + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheArrayWhenANamedSiblingMakesPositionUnreliable() + { + return VerifyFixAsync( + """ + using System; + using System.Text; + class C + { + void M(ReadOnlySpan first, int second) + { + } + + void N() + { + M({|E128141:Encoding.UTF8.GetBytes("abc")|}, second: 1); + } + } + """, + """ + using System; + using System.Text; + class C + { + void M(ReadOnlySpan first, int second) + { + } + + void N() + { + M("abc"u8.ToArray(), second: 1); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_KeepsTheArrayForAnArgumentBeyondTheDeclaredParameters() + { + return VerifyFixAsync( + """ + using System; + using System.Text; + class C + { + static void M(byte[] first, params byte[][] more) + { + } + + void N(byte[] data) + { + M(data, {|E128141:Encoding.UTF8.GetBytes("abc")|}); + } + } + """, + """ + using System; + using System.Text; + class C + { + static void M(byte[] first, params byte[][] more) + { + } + + void N(byte[] data) + { + M(data, "abc"u8.ToArray()); + } + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Fix_UsesTheSpanOnlyForAReadOnlySpanLocal() + { + return VerifyFixAsync( + """ + using System; + using System.Text; + class C + { + void N(byte[] target) + { + ReadOnlySpan literal = {|E128141:Encoding.UTF8.GetBytes("abc")|}; + var inferred = {|E128141:Encoding.UTF8.GetBytes("def")|}; + target = {|E128141:Encoding.UTF8.GetBytes("ghi")|}; + _ = literal.Length + inferred.Length + target.Length; + } + } + """, + """ + using System; + using System.Text; + class C + { + void N(byte[] target) + { + ReadOnlySpan literal = "abc"u8; + var inferred = "def"u8.ToArray(); + target = "ghi"u8.ToArray(); + _ = literal.Length + inferred.Length + target.Length; + } + } + """); + } +} diff --git a/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedBranchCoverageTests.cs new file mode 100644 index 00000000..c5064e36 --- /dev/null +++ b/tests/E128.Analyzers.Tests/WhenAnyResultUnobservedBranchCoverageTests.cs @@ -0,0 +1,93 @@ +using System.Threading.Tasks; +using E128.Analyzers.Reliability; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class WhenAnyResultUnobservedBranchCoverageTests +{ + private static Task VerifyAsync(string body) + { + return AnalyzerTestRunner.VerifyAsync( + "using System;\nusing System.Threading.Tasks;\nusing static System.Threading.Tasks.Task;\n" + + "class Helper { public static Task WhenAny(Task a, Task b) => Task.FromResult(a); }\n" + + "class C\n{\n Task _field = Task.FromResult(Task.CompletedTask);\n Task Property { get; set; } = Task.FromResult(Task.CompletedTask);\n" + + " void M(Task a, Task b)\n {\n" + body + "\n }\n}\n"); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_ForAnUnqualifiedWhenAnyThatIsDiscarded() + { + return VerifyAsync(""" + {|E128183:WhenAny(a, b)|}; + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_ForAUserMethodNamedWhenAny() + { + return VerifyAsync(""" + Helper.WhenAny(a, b); + var unused = Helper.WhenAny(a, b); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResultFlowsIntoAFieldOrAProperty() + { + return VerifyAsync(""" + _field = Task.WhenAny(a, b); + Property = Task.WhenAny(a, b); + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheResultIsAnArgumentOrReturned() + { + return VerifyAsync(""" + Consume(Task.WhenAny(a, b)); + var pending = Task.WhenAny(a, b); + Consume(pending); + + static void Consume(Task task) { } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenTheLocalIsDeclaredInAForInitializer() + { + return VerifyAsync(""" + for (var pending = Task.WhenAny(a, b); false; ) + { + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Reports_WhenALocalIsNeverReadInABlockWithOtherDeclarations() + { + return VerifyAsync(""" + var pending = {|E128183:Task.WhenAny(a, b)|}; + { + var other = 1; + } + """); + } + + [Fact] + [Trait("Category", "CI")] + public Task Silent_WhenALambdaReadsTheLocal() + { + return VerifyAsync(""" + var pending = Task.WhenAny(a, b); + Action action = () => { _ = pending; }; + action(); + """); + } +} diff --git a/tests/E128.Analyzers.Tests/WordSplitterBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/WordSplitterBranchCoverageTests.cs new file mode 100644 index 00000000..d11c6a57 --- /dev/null +++ b/tests/E128.Analyzers.Tests/WordSplitterBranchCoverageTests.cs @@ -0,0 +1,35 @@ +using E128.Analyzers.Security; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class WordSplitterBranchCoverageTests +{ + [Theory] + [Trait("Category", "CI")] + [InlineData("computedTag", "computed|Tag")] + [InlineData("HMACKey", "HMAC|Key")] + [InlineData("my_tag_value", "my|tag|value")] + [InlineData("_leading_and_trailing_", "leading|and|trailing")] + [InlineData("a.b..c", "a|b|c")] + [InlineData("ALLCAPS", "ALLCAPS")] + [InlineData("lower", "lower")] + [InlineData("", "")] + [InlineData("___", "")] + [InlineData("X", "X")] + public void Split_BreaksAtSeparatorsAndCaseChanges(string name, string expected) + { + var words = WordSplitter.Split(name, "_."); + + Assert.Equal(expected, string.Join('|', words)); + } + + [Fact] + [Trait("Category", "CI")] + public void Split_UsesOnlyTheSeparatorsTheCallerNames() + { + var words = WordSplitter.Split("a-b_c", "-"); + + Assert.Equal(["a", "b_c"], words); + } +} diff --git a/tests/E128.Analyzers.Tests/XunitTestHelperBranchCoverageTests.cs b/tests/E128.Analyzers.Tests/XunitTestHelperBranchCoverageTests.cs new file mode 100644 index 00000000..f2db9798 --- /dev/null +++ b/tests/E128.Analyzers.Tests/XunitTestHelperBranchCoverageTests.cs @@ -0,0 +1,163 @@ +using System.Linq; +using E128.Analyzers.Testing; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Xunit; + +namespace E128.Analyzers.Tests; + +public sealed class XunitTestHelperBranchCoverageTests +{ + private const string FrameworkStubs = """ + namespace Xunit + { + public sealed class FactAttribute : System.Attribute { } + public sealed class TheoryAttribute : System.Attribute { } + public static class Assert { } + } + + namespace Other + { + public sealed class FactAttribute : System.Attribute { } + } + + namespace NUnit.Framework + { + public sealed class TestAttribute : System.Attribute { } + public sealed class TestCaseAttribute : System.Attribute { } + } + + namespace Microsoft.VisualStudio.TestTools.UnitTesting + { + public sealed class TestMethodAttribute : System.Attribute { } + public sealed class DataTestMethodAttribute : System.Attribute { } + } + + """; + + private static CSharpCompilation Compile(string code) + { + var tree = CSharpSyntaxTree.ParseText(code, cancellationToken: TestContext.Current.CancellationToken); + return CSharpCompilation.Create( + "XunitProbe", + [tree], + [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)]); + } + + private static MethodDeclarationSyntax FirstMethod(Compilation compilation) + { + var tree = compilation.SyntaxTrees.Single(); + return tree.GetRoot(TestContext.Current.CancellationToken).DescendantNodes().OfType().First(); + } + + [Fact] + [Trait("Category", "CI")] + public void IsXunitTestMethod_ReadsTheAttributeSymbols() + { + var compilation = Compile(FrameworkStubs + "class C { [Xunit.Fact] void A() { } [Xunit.Theory] void B() { } [Other.Fact] void D() { } void E() { } [System.Obsolete] void F() { } }"); + var type = compilation.GetTypeByMetadataName("C")!; + + Assert.True(XunitTestHelper.IsXunitTestMethod((IMethodSymbol)type.GetMembers("A").Single())); + Assert.True(XunitTestHelper.IsXunitTestMethod((IMethodSymbol)type.GetMembers("B").Single())); + Assert.False(XunitTestHelper.IsXunitTestMethod((IMethodSymbol)type.GetMembers("D").Single())); + Assert.False(XunitTestHelper.IsXunitTestMethod((IMethodSymbol)type.GetMembers("E").Single())); + Assert.False(XunitTestHelper.IsXunitTestMethod((IMethodSymbol)type.GetMembers("F").Single())); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("[Fact]", true)] + [InlineData("[Theory]", true)] + [InlineData("[FactAttribute]", true)] + [InlineData("[TheoryAttribute]", true)] + [InlineData("[Xunit.Fact]", true)] + [InlineData("[global::Xunit.Theory]", true)] + [InlineData("[System.Obsolete, Fact]", true)] + [InlineData("[Obsolete]", false)] + [InlineData("", false)] + public void GetFactOrTheoryAttribute_ReadsTheLastNameSegment(string attributes, bool expected) + { + var method = FirstMethod(Compile("class C { " + attributes + " void M() { } }")); + Assert.Equal(expected, XunitTestHelper.GetFactOrTheoryAttribute(method) is not null); + } + + [Fact] + [Trait("Category", "CI")] + public void CountDataRows_CountsInlineDataAttributes() + { + var method = FirstMethod(Compile("class C { [Theory] [InlineData(1)] [InlineData(2)] [Obsolete] void M(int x) { } }")); + Assert.Equal(2, XunitTestHelper.CountDataRows(method)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsFactOrTheoryAttribute_ChecksTheNameAndTheBoundType() + { + var compilation = Compile(FrameworkStubs + "class C { [Xunit.Fact] void A() { } [Other.Fact] void B() { } [Missing.Fact] void D() { } }"); + var model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()); + var attributes = compilation.SyntaxTrees.Single().GetRoot(TestContext.Current.CancellationToken) + .DescendantNodes().OfType().ToArray(); + + Assert.True(XunitTestHelper.IsFactOrTheoryAttribute(attributes[0], model, TestContext.Current.CancellationToken)); + Assert.False(XunitTestHelper.IsFactOrTheoryAttribute(attributes[1], model, TestContext.Current.CancellationToken)); + Assert.False(XunitTestHelper.IsFactOrTheoryAttribute(attributes[2], model, TestContext.Current.CancellationToken)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("[Xunit.Fact]", true)] + [InlineData("[NUnit.Framework.Test]", true)] + [InlineData("[NUnit.Framework.TestCase]", true)] + [InlineData("[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]", true)] + [InlineData("[Microsoft.VisualStudio.TestTools.UnitTesting.DataTestMethod]", true)] + [InlineData("[System.Obsolete]", false)] + [InlineData("", false)] + public void IsTestCompilation_NeedsAFrameworkAndATestMethod(string attribute, bool expected) + { + var compilation = Compile(FrameworkStubs + "class C { " + attribute + " void M() { } }"); + Assert.Equal(expected, XunitTestHelper.IsTestCompilation(compilation, TestContext.Current.CancellationToken)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsTestCompilation_IsFalseWithoutAFrameworkType() + { + var compilation = Compile("class C { [Fact] void M() { } }"); + Assert.False(XunitTestHelper.IsTestCompilation(compilation, TestContext.Current.CancellationToken)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsAssertType_RequiresTheXunitNamespace() + { + var compilation = Compile(FrameworkStubs + "namespace Other { public static class Assert { } }"); + + Assert.True(XunitTestHelper.IsAssertType(compilation.GetTypeByMetadataName("Xunit.Assert"))); + Assert.False(XunitTestHelper.IsAssertType(compilation.GetTypeByMetadataName("Other.Assert"))); + Assert.False(XunitTestHelper.IsAssertType(compilation.GetTypeByMetadataName("Xunit.FactAttribute"))); + Assert.False(XunitTestHelper.IsAssertType(null)); + } + + [Fact] + [Trait("Category", "CI")] + public void IsXunitNamespace_IsFalseForNullAndForOtherNamespaces() + { + var compilation = Compile(FrameworkStubs); + + Assert.False(XunitTestHelper.IsXunitNamespace(null)); + Assert.False(XunitTestHelper.IsXunitNamespace(compilation.GetTypeByMetadataName("Other.FactAttribute")!.ContainingNamespace)); + Assert.True(XunitTestHelper.IsXunitNamespace(compilation.GetTypeByMetadataName("Xunit.FactAttribute")!.ContainingNamespace)); + } + + [Theory] + [Trait("Category", "CI")] + [InlineData("Fact", "Fact")] + [InlineData("Xunit.Fact", "Fact")] + [InlineData("global::Xunit.Fact", "Fact")] + public void SimpleName_ReturnsTheLastSegment(string text, string expected) + { + var name = SyntaxFactory.ParseName(text); + Assert.Equal(expected, XunitTestHelper.SimpleName(name)); + } +}