diff --git a/Directory.Build.props b/Directory.Build.props
index a727412840a4..f65a0afdebf4 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -130,6 +130,9 @@
$(WarningsNotAsErrors);xUnit1004
+
+ $(NoWarn);xUnit1030
+
$(NoWarn);IL2121
diff --git a/eng/Versions.props b/eng/Versions.props
index f7efc13bd5b4..4f58a5e87377 100644
--- a/eng/Versions.props
+++ b/eng/Versions.props
@@ -322,12 +322,12 @@
6.6.2
19.14.0
2.0.3
- 1.0.0
- 2.4.2
+ 1.15.0
+ 2.9.0
$(XunitVersion)
$(XunitVersion)
$(XunitVersion)
- 2.4.3
+ 2.8.2
4.0.5
1.6.17
1.6.17
diff --git a/src/Analyzers/Microsoft.AspNetCore.Analyzer.Testing/src/Assert.cs b/src/Analyzers/Microsoft.AspNetCore.Analyzer.Testing/src/Assert.cs
index 7f0f69a709f7..7dcaff1b6808 100644
--- a/src/Analyzers/Microsoft.AspNetCore.Analyzer.Testing/src/Assert.cs
+++ b/src/Analyzers/Microsoft.AspNetCore.Analyzer.Testing/src/Assert.cs
@@ -18,7 +18,7 @@ public static void DiagnosticLocation(DiagnosticLocation expected, Location actu
{
if (actualLinePosition.Line + 1 != expected.Line)
{
- throw new DiagnosticLocationAssertException(
+ throw EqualException.ForMismatchedValues(
expected,
actual,
$"Expected diagnostic to be on line \"{expected.Line}\" was actually on line \"{actualLinePosition.Line + 1}\"");
@@ -30,25 +30,11 @@ public static void DiagnosticLocation(DiagnosticLocation expected, Location actu
{
if (actualLinePosition.Character + 1 != expected.Column)
{
- throw new DiagnosticLocationAssertException(
+ throw EqualException.ForMismatchedValues(
expected,
actual,
$"Expected diagnostic to start at column \"{expected.Column}\" was actually on column \"{actualLinePosition.Character + 1}\"");
}
}
}
-
- private sealed class DiagnosticLocationAssertException : EqualException
- {
- public DiagnosticLocationAssertException(
- DiagnosticLocation expected,
- Location actual,
- string message)
- : base(expected, actual)
- {
- Message = message;
- }
-
- public override string Message { get; }
- }
}
diff --git a/src/Antiforgery/test/BinaryBlobTest.cs b/src/Antiforgery/test/BinaryBlobTest.cs
index c239927f9d32..5a1fe5993372 100644
--- a/src/Antiforgery/test/BinaryBlobTest.cs
+++ b/src/Antiforgery/test/BinaryBlobTest.cs
@@ -56,10 +56,10 @@ public void Ctor_Data()
[Theory]
[InlineData((object[]?)null)]
[InlineData(new byte[] { 0x01, 0x02, 0x03 })]
- public void Ctor_Data_Bad(byte[] data)
+ public void Ctor_Data_Bad(byte[]? data)
{
// Act & assert
- var ex = Assert.Throws(() => new BinaryBlob(32, data));
+ var ex = Assert.Throws(() => new BinaryBlob(32, data!));
Assert.Equal("data", ex.ParamName);
}
diff --git a/src/Antiforgery/test/DefaultAntiforgeryTest.cs b/src/Antiforgery/test/DefaultAntiforgeryTest.cs
index a3819c95d12f..4e3fc6b2d41b 100644
--- a/src/Antiforgery/test/DefaultAntiforgeryTest.cs
+++ b/src/Antiforgery/test/DefaultAntiforgeryTest.cs
@@ -1079,7 +1079,7 @@ public void SetCookieTokenAndHeader_OverridesExistingCachingHeaders()
[InlineData(true, null)]
public void SetCookieTokenAndHeader_AddsXFrameOptionsHeader(
bool suppressXFrameOptions,
- string expectedHeaderValue)
+ string? expectedHeaderValue)
{
// Arrange
var options = new AntiforgeryOptions()
diff --git a/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs b/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs
index 65a3536d8051..bfef37e4dd40 100644
--- a/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs
+++ b/src/Antiforgery/test/DefaultAntiforgeryTokenStoreTest.cs
@@ -396,7 +396,7 @@ public void SaveCookieToken_HonorsCookieSecurePolicy_OnOptions(
[InlineData("/", "/")]
[InlineData("/vdir1", "/vdir1")]
[InlineData("/vdir1/vdir2", "/vdir1/vdir2")]
- public void SaveCookieToken_SetsCookieWithApproriatePathBase(string requestPathBase, string expectedCookiePath)
+ public void SaveCookieToken_SetsCookieWithApproriatePathBase(string? requestPathBase, string expectedCookiePath)
{
// Arrange
var token = "serialized-value";
diff --git a/src/Components/Analyzers/test/Verifiers/CodeFixVerifier.cs b/src/Components/Analyzers/test/Verifiers/CodeFixVerifier.cs
index 53c978d3f847..0d156fd8d051 100644
--- a/src/Components/Analyzers/test/Verifiers/CodeFixVerifier.cs
+++ b/src/Components/Analyzers/test/Verifiers/CodeFixVerifier.cs
@@ -109,7 +109,7 @@ private void VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProv
document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace));
newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document));
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
diff --git a/src/Components/Analyzers/test/Verifiers/DiagnosticVerifier.cs b/src/Components/Analyzers/test/Verifiers/DiagnosticVerifier.cs
index 8dde75a73683..f1d5a434de28 100644
--- a/src/Components/Analyzers/test/Verifiers/DiagnosticVerifier.cs
+++ b/src/Components/Analyzers/test/Verifiers/DiagnosticVerifier.cs
@@ -112,7 +112,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
{
string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE.";
- Assert.True(false,
+ Assert.Fail(
string.Format(CultureInfo.InvariantCulture, "Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
}
@@ -125,7 +125,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
{
if (actual.Location != Location.None)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(CultureInfo.InvariantCulture, "Expected:\nA project diagnostic with No location\nActual:\n{0}",
FormatDiagnostics(analyzer, actual)));
}
@@ -137,7 +137,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
if (additionalLocations.Length != expected.Locations.Length - 1)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
@@ -153,7 +153,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
if (actual.Id != expected.Id)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
@@ -162,7 +162,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
if (actual.Severity != expected.Severity)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
@@ -171,7 +171,7 @@ private static void VerifyDiagnosticResults(IEnumerable actualResult
if (actual.GetMessage(CultureInfo.InvariantCulture) != expected.Message)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
@@ -204,7 +204,7 @@ private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagno
{
if (actualLinePosition.Line + 1 != expected.Line)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
@@ -217,7 +217,7 @@ private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagno
{
if (actualLinePosition.Character + 1 != expected.Column)
{
- Assert.True(false,
+ Assert.Fail(
string.Format(
CultureInfo.InvariantCulture,
"Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
diff --git a/src/Components/Authorization/test/AuthorizeViewTest.cs b/src/Components/Authorization/test/AuthorizeViewTest.cs
index 5db236f3afc2..d957d76e311f 100644
--- a/src/Components/Authorization/test/AuthorizeViewTest.cs
+++ b/src/Components/Authorization/test/AuthorizeViewTest.cs
@@ -321,7 +321,7 @@ public async Task RendersAuthorizingUntilAuthorizationCompletedAsync()
// (This wouldn't happen under the sync context or in wasm)
var renderTcs = new TaskCompletionSource();
renderer.OnUpdateDisplayComplete = () => renderTcs.SetResult();
- authTcs.SetResult(CreateAuthenticationState("Monsieur").Result);
+ authTcs.SetResult(await CreateAuthenticationState("Monsieur"));
await renderTcs.Task;
Assert.Equal(2, renderer.Batches.Count);
@@ -347,7 +347,7 @@ public async Task RendersAuthorizingUntilAuthorizationCompletedAsync()
}
[Fact]
- public void RendersAuthorizingUntilAuthorizationCompleted()
+ public async Task RendersAuthorizingUntilAuthorizationCompleted()
{
// Arrange
var @event = new ManualResetEventSlim();
@@ -377,7 +377,7 @@ public void RendersAuthorizingUntilAuthorizationCompleted()
// Act/Assert 2: Auth process completes asynchronously
@event.Reset();
- authTcs.SetResult(CreateAuthenticationState("Monsieur").Result);
+ authTcs.SetResult(await CreateAuthenticationState("Monsieur"));
// We need to wait here because the continuations of SetResult will be scheduled to run asynchronously.
@event.Wait(Timeout);
diff --git a/src/Components/Components/test/LayoutViewTest.cs b/src/Components/Components/test/LayoutViewTest.cs
index ff4971690f4e..e8c103912243 100644
--- a/src/Components/Components/test/LayoutViewTest.cs
+++ b/src/Components/Components/test/LayoutViewTest.cs
@@ -178,7 +178,7 @@ public void CanChangeContentWithSameLayout()
// Assert
Assert.Equal(2, _renderer.Batches.Count);
var batch = _renderer.Batches[1];
- Assert.Equal(0, batch.DisposedComponentIDs.Count);
+ Assert.Empty(batch.DisposedComponentIDs);
Assert.Collection(batch.DiffsInOrder,
diff => Assert.Empty(diff.Edits), // LayoutView rerendered, but with no changes
diff => Assert.Empty(diff.Edits), // RootLayout rerendered, but with no changes
@@ -220,7 +220,7 @@ public void CanChangeLayout()
Assert.True(setParametersTask2.IsCompletedSuccessfully);
Assert.Equal(2, _renderer.Batches.Count);
var batch = _renderer.Batches[1];
- Assert.Equal(1, batch.DisposedComponentIDs.Count); // Disposes NestedLayout
+ Assert.Single(batch.DisposedComponentIDs); // Disposes NestedLayout
Assert.Collection(batch.DiffsInOrder,
diff => Assert.Empty(diff.Edits), // LayoutView rerendered, but with no changes
diff =>
diff --git a/src/Components/Components/test/NavigationManagerTest.cs b/src/Components/Components/test/NavigationManagerTest.cs
index 67f0c6a1b1ce..9b3763b45945 100644
--- a/src/Components/Components/test/NavigationManagerTest.cs
+++ b/src/Components/Components/test/NavigationManagerTest.cs
@@ -223,7 +223,9 @@ public void LocationChangingHandlers_CanContinueTheNavigationSynchronously_WhenO
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
static ValueTask HandleLocationChanging(LocationChangingContext context)
{
@@ -250,7 +252,9 @@ public void LocationChangingHandlers_CanContinueTheNavigationSynchronously_WhenM
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.Equal(initialHandlerCount, completedHandlerCount);
ValueTask HandleLocationChanging(LocationChangingContext context)
@@ -276,7 +280,9 @@ public void LocationChangingHandlers_CanContinueTheNavigationAsynchronously_When
Assert.False(navigation1.IsCompleted);
tcs.SetResult();
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
async ValueTask HandleLocationChanging(LocationChangingContext context)
{
@@ -328,7 +334,9 @@ public void LocationChangingHandlers_CanCancelTheNavigationSynchronously_WhenOne
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
static ValueTask HandleLocationChanging(LocationChangingContext context)
{
@@ -357,7 +365,9 @@ public void LocationChangingHandlers_CanCancelTheNavigationSynchronously_WhenMul
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.Equal(expectedInvokedHandlerCount, invokedHandlerCount);
ValueTask HandleLocationChanging_AllowNavigation(LocationChangingContext context)
@@ -391,7 +401,9 @@ public void LocationChangingHandlers_CanCancelTheNavigationSynchronously_BeforeR
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.True(currentContext.DidPreventNavigation);
Assert.True(currentContext.CancellationToken.IsCancellationRequested);
Assert.False(isHandlerCompleted);
@@ -428,7 +440,9 @@ public void LocationChangingHandlers_CanCancelTheNavigationSynchronously_BeforeR
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.True(currentContext.DidPreventNavigation);
Assert.True(currentContext.CancellationToken.IsCancellationRequested);
Assert.False(isFirstHandlerCompleted);
@@ -455,7 +469,7 @@ ValueTask HandleLocationChanging_AllowNavigation(LocationChangingContext context
}
[Fact]
- public async void LocationChangingHandlers_CanCancelTheNavigationAsynchronously_WhenOneHandlerIsRegistered()
+ public async Task LocationChangingHandlers_CanCancelTheNavigationAsynchronously_WhenOneHandlerIsRegistered()
{
// Arrange
var baseUri = "scheme://host/";
@@ -479,7 +493,7 @@ static async ValueTask HandleLocationChanging(LocationChangingContext context)
}
[Fact]
- public async void LocationChangingHandlers_CanCancelTheNavigationAsynchronously_WhenMultipleHandlersAreRegistered()
+ public async Task LocationChangingHandlers_CanCancelTheNavigationAsynchronously_WhenMultipleHandlersAreRegistered()
{
// Arrange
var baseUri = "scheme://host/";
@@ -503,7 +517,9 @@ public async void LocationChangingHandlers_CanCancelTheNavigationAsynchronously_
// Assert
Assert.True(navigation1.IsCompletedSuccessfully);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(navigation1.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.Equal(blockNavigationHandlerCount, canceledBlockNavigationHandlerCount);
async ValueTask HandleLocationChanging_BlockNavigation(LocationChangingContext context)
@@ -556,11 +572,13 @@ public async Task LocationChangingHandlers_AreCanceledBySuccessiveNavigations_Wh
await tcs.Task.WaitAsync(Timeout);
// Assert
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(navigation1.IsCompletedSuccessfully);
Assert.False(navigation1.Result);
Assert.True(navigation2.IsCompletedSuccessfully);
Assert.True(navigation2.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
async ValueTask HandleLocationChanging(LocationChangingContext context)
{
@@ -615,6 +633,7 @@ public async Task LocationChangingHandlers_AreCanceledBySuccessiveNavigations_Wh
await tcs.Task.WaitAsync(Timeout);
// Assert
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(navigation1.IsCompletedSuccessfully);
Assert.False(navigation1.Result);
@@ -623,6 +642,7 @@ public async Task LocationChangingHandlers_AreCanceledBySuccessiveNavigations_Wh
Assert.True(navigation3.IsCompletedSuccessfully);
Assert.True(navigation3.Result);
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
Assert.Equal(expectedCanceledHandlerCount, canceledHandlerCount);
Assert.Equal(0, completedHandlerCount);
diff --git a/src/Components/Components/test/RendererTest.cs b/src/Components/Components/test/RendererTest.cs
index a71ff665d740..492b5c8cc2f9 100644
--- a/src/Components/Components/test/RendererTest.cs
+++ b/src/Components/Components/test/RendererTest.cs
@@ -3065,8 +3065,8 @@ public void QueuedRenderIsSkippedIfComponentWasAlreadyDisposedInSameBatch()
// Assert: correct render result
Assert.True(renderTask.IsCompletedSuccessfully);
var newBatch = renderer.Batches.Skip(1).Single();
- Assert.Equal(1, newBatch.DisposedComponentIDs.Count);
- Assert.Equal(1, newBatch.DiffsByComponentId.Count);
+ Assert.Single(newBatch.DisposedComponentIDs);
+ Assert.Single(newBatch.DiffsByComponentId);
Assert.Collection(newBatch.DiffsByComponentId[componentId].Single().Edits,
edit =>
{
@@ -3433,7 +3433,7 @@ public void DoesNotCallOnAfterRenderForComponentsNotRendered()
// Assert: Only the re-rendered component was notified of "after render"
var batch2 = renderer.Batches.Skip(1).Single();
Assert.Equal(2, batch2.DiffsInOrder.Count); // Parent and first child
- Assert.Equal(1, batch2.DisposedComponentIDs.Count); // Third child
+ Assert.Single(batch2.DisposedComponentIDs); // Third child
Assert.Equal(2, childComponents[0].OnAfterRenderCallCount); // Retained and re-rendered
Assert.Equal(1, childComponents[1].OnAfterRenderCallCount); // Retained and not re-rendered
Assert.Equal(1, childComponents[2].OnAfterRenderCallCount); // Disposed
diff --git a/src/Components/Components/test/ResourceAssetCollectionTest.cs b/src/Components/Components/test/ResourceAssetCollectionTest.cs
index fa1ed1c09f09..de19ebd48dcf 100644
--- a/src/Components/Components/test/ResourceAssetCollectionTest.cs
+++ b/src/Components/Components/test/ResourceAssetCollectionTest.cs
@@ -17,7 +17,7 @@ public void CanCreateResourceCollection()
var collectionAsReadOnlyList = resourceAssetCollection as IReadOnlyList;
// Assert
- Assert.Equal(1, collectionAsReadOnlyList.Count);
+ Assert.Single(collectionAsReadOnlyList);
Assert.Equal("image1.jpg", collectionAsReadOnlyList[0].Url);
}
diff --git a/src/Components/Components/test/Routing/RouterTest.cs b/src/Components/Components/test/Routing/RouterTest.cs
index 2e8a05bd9145..f393a2edccf0 100644
--- a/src/Components/Components/test/Routing/RouterTest.cs
+++ b/src/Components/Components/test/Routing/RouterTest.cs
@@ -111,7 +111,7 @@ public async Task AlreadyCanceledOnNavigateAsyncDoesNothing()
Assert.True(true);
return;
}
- Assert.True(false, "OnUpdateDisplay called more than once.");
+ Assert.Fail("OnUpdateDisplay called more than once.");
};
_router.OnNavigateAsync = new EventCallback(null, OnNavigateAsync);
@@ -164,7 +164,7 @@ public async Task RefreshesOnceOnCancelledOnNavigateAsync()
Assert.True(true);
return;
}
- Assert.True(false, "OnUpdateDisplay called more than once.");
+ Assert.Fail("OnUpdateDisplay called more than once.");
};
_router.OnNavigateAsync = new EventCallback(null, OnNavigateAsync);
diff --git a/src/Components/Endpoints/test/Builder/RazorComponentsEndpointConventionBuilderExtensionsTest.cs b/src/Components/Endpoints/test/Builder/RazorComponentsEndpointConventionBuilderExtensionsTest.cs
index 4945d46e37e2..e5378452934e 100644
--- a/src/Components/Endpoints/test/Builder/RazorComponentsEndpointConventionBuilderExtensionsTest.cs
+++ b/src/Components/Endpoints/test/Builder/RazorComponentsEndpointConventionBuilderExtensionsTest.cs
@@ -74,7 +74,7 @@ public void WithStaticAssets_AddsResourceCollection_ToEndpoints_NamedManifest()
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("named.css", list[0].Url);
});
}
@@ -95,7 +95,7 @@ public void WithStaticAssets_AddsDefaultResourceCollection_ToEndpoints_ByDefault
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("default.css", list[0].Url);
});
}
@@ -117,7 +117,7 @@ public void WithStaticAssets_AddsResourceCollection_ToEndpoints_DefaultManifest(
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("default.css", list[0].Url);
});
}
@@ -139,7 +139,7 @@ public void WithStaticAssets_AddsDefaultResourceCollectionToEndpoints_WhenNoMani
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("default.css", list[0].Url);
});
}
@@ -162,7 +162,7 @@ public void WithStaticAssets_AddsMatchingResourceCollectionToEndpoints_WhenExpli
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("named.css", list[0].Url);
});
}
@@ -188,7 +188,7 @@ public void WithStaticAssets_AddsCollectionFromGroup_WhenMappedInsideAnEndpointG
var metadata = e.Metadata.GetMetadata();
Assert.NotNull(metadata);
var list = Assert.IsAssignableFrom>(metadata);
- Assert.Equal(1, list.Count);
+ Assert.Single(list);
Assert.Equal("named.css", list[0].Url);
});
}
diff --git a/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs b/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs
index 1144c4360a89..5f8aefe74156 100644
--- a/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs
+++ b/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs
@@ -823,7 +823,7 @@ public async Task CanRender_AsyncComponent()
}
[Fact]
- public async void Duplicate_NamedEventHandlers_AcrossComponents_ThowsOnDispatch()
+ public async Task Duplicate_NamedEventHandlers_AcrossComponents_ThowsOnDispatch()
{
// Arrange
var expectedError = @"There is more than one named submit event with the name 'default'. Ensure named submit events have unique names, or are in scopes with distinct names. The following components use this name:
diff --git a/src/Components/Endpoints/test/RazorComponentResultTest.cs b/src/Components/Endpoints/test/RazorComponentResultTest.cs
index 6c0f0e96d116..cbeb6712402a 100644
--- a/src/Components/Endpoints/test/RazorComponentResultTest.cs
+++ b/src/Components/Endpoints/test/RazorComponentResultTest.cs
@@ -34,7 +34,7 @@ public void AcceptsDictionaryParameters()
{
var paramsDict = new Dictionary { { "First", 123 } };
var result = new RazorComponentResult(typeof(SimpleComponent), paramsDict);
- Assert.Equal(1, result.Parameters.Count);
+ Assert.Single(result.Parameters);
Assert.Equal(123, result.Parameters["First"]);
Assert.Same(paramsDict, result.Parameters);
}
@@ -168,7 +168,7 @@ public async Task EmitsEachComponentOnlyOncePerStreamingUpdate_WhenAnAncestorAls
Assert.Equal(
expectedInitialHtml,
MaskComponentIds(GetStringContent(responseBody)));
-
+
// Act/Assert 2: When loading completes, it emits a streaming batch update in which the
// child is present only within the parent markup, not as a separate entry
tcs.SetResult();
diff --git a/src/Components/Endpoints/test/RazorComponentsServiceCollectionExtensionsTest.cs b/src/Components/Endpoints/test/RazorComponentsServiceCollectionExtensionsTest.cs
index fe8784b759c4..09dfd3a90403 100644
--- a/src/Components/Endpoints/test/RazorComponentsServiceCollectionExtensionsTest.cs
+++ b/src/Components/Endpoints/test/RazorComponentsServiceCollectionExtensionsTest.cs
@@ -128,15 +128,11 @@ private void AssertAllImplementationTypesAreDistinct(
if (implementationTypes.Length == 0)
{
- Assert.True(
- false,
- $"Could not find an implementation type for {serviceType}");
+ Assert.Fail($"Could not find an implementation type for {serviceType}");
}
else if (implementationTypes.Length != implementationTypes.Distinct().Count())
{
- Assert.True(
- false,
- $"Found duplicate implementation types for {serviceType}. Implementation types: {string.Join(", ", implementationTypes.Select(x => x.ToString()))}");
+ Assert.Fail($"Found duplicate implementation types for {serviceType}. Implementation types: {string.Join(", ", implementationTypes.Select(x => x.ToString()))}");
}
}
diff --git a/src/Components/Server/test/Circuits/RemoteRendererTest.cs b/src/Components/Server/test/Circuits/RemoteRendererTest.cs
index 9ca641979610..a2db200c8f0e 100644
--- a/src/Components/Server/test/Circuits/RemoteRendererTest.cs
+++ b/src/Components/Server/test/Circuits/RemoteRendererTest.cs
@@ -183,7 +183,9 @@ public async Task ProcessBufferedRenderBatches_WritesRenders()
// Assert
Assert.Equal(new long[] { 2, 3, 4 }, renderIds);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.True(task.Wait(3000), "One or more render batches weren't acknowledged");
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
await task;
}
diff --git a/src/Components/Web/test/Forms/InputBaseTest.cs b/src/Components/Web/test/Forms/InputBaseTest.cs
index 25901cc7321f..5f2ae4ce135a 100644
--- a/src/Components/Web/test/Forms/InputBaseTest.cs
+++ b/src/Components/Web/test/Forms/InputBaseTest.cs
@@ -451,7 +451,7 @@ public async Task AriaAttributeIsRenderedWhenTheValidationStateIsInvalidOnFirstR
var component = (TestInputComponent)componentFrame1.Component;
Assert.Equal("invalid", component.CssClass);
Assert.NotNull(component.AdditionalAttributes);
- Assert.Equal(1, component.AdditionalAttributes.Count);
+ Assert.Single(component.AdditionalAttributes);
//Check for "true" see https://www.w3.org/TR/wai-aria-1.1/#aria-invalid
Assert.Equal("true", component.AdditionalAttributes["aria-invalid"]);
}
@@ -486,7 +486,7 @@ public async Task UserSpecifiedAriaValueIsNotChangedIfInvalid()
var component = (TestInputComponent)componentFrame1.Component;
Assert.Equal("invalid", component.CssClass);
Assert.NotNull(component.AdditionalAttributes);
- Assert.Equal(1, component.AdditionalAttributes.Count);
+ Assert.Single(component.AdditionalAttributes);
Assert.Equal("userSpecifiedValue", component.AdditionalAttributes["aria-invalid"]);
}
diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs b/src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs
index db724a7296c5..a5133679aa93 100644
--- a/src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs
+++ b/src/Components/WebAssembly/WebAssembly.Authentication/test/AuthorizationMessageHandlerTests.cs
@@ -190,7 +190,7 @@ public async Task UsesCustomScopesAndReturnUrlWhenProvided()
_ = await new HttpClient(handler).GetAsync("https://localhost:5001/weather");
// Assert
- Assert.Equal(1, tokenProvider.Invocations.Count);
+ Assert.Single(tokenProvider.Invocations);
}
}
diff --git a/src/Components/test/E2ETest/ServerRenderingTests/StreamingRenderingTest.cs b/src/Components/test/E2ETest/ServerRenderingTests/StreamingRenderingTest.cs
index 76ba4abec238..5fcf6d2a3813 100644
--- a/src/Components/test/E2ETest/ServerRenderingTests/StreamingRenderingTest.cs
+++ b/src/Components/test/E2ETest/ServerRenderingTests/StreamingRenderingTest.cs
@@ -245,7 +245,7 @@ static async Task BandwidthThrottledGet(string url, int chunkLength, int
[Theory]
[InlineData(false)]
[InlineData(true)]
- public async void StopsProcessingStreamingOutputFromPreviousRequestAfterEnhancedNav(bool duringEnhancedNavigation)
+ public async Task StopsProcessingStreamingOutputFromPreviousRequestAfterEnhancedNav(bool duringEnhancedNavigation)
{
IWebElement originalH1Elem;
diff --git a/src/Components/test/E2ETest/Tests/BootResourceCachingTest.cs b/src/Components/test/E2ETest/Tests/BootResourceCachingTest.cs
index 544e588d5f4c..656515d75efa 100644
--- a/src/Components/test/E2ETest/Tests/BootResourceCachingTest.cs
+++ b/src/Components/test/E2ETest/Tests/BootResourceCachingTest.cs
@@ -60,13 +60,13 @@ public void CachesResourcesAfterFirstLoad()
WaitUntilLoaded();
var subsequentResourcesRequested = GetAndClearRequestedPaths();
Assert.NotEmpty(initialResourcesRequested.Where(path => path.EndsWith("/blazor.boot.json", StringComparison.Ordinal)));
- Assert.Empty(subsequentResourcesRequested.Where(path =>
+ Assert.DoesNotContain(subsequentResourcesRequested, path =>
path.Contains("/dotnet.native.", StringComparison.Ordinal) &&
- path.EndsWith(".wasm", StringComparison.Ordinal)));
+ path.EndsWith(".wasm", StringComparison.Ordinal));
Assert.NotEmpty(subsequentResourcesRequested.Where(path => path.EndsWith(".js", StringComparison.Ordinal)));
- Assert.Empty(subsequentResourcesRequested.Where(path =>
+ Assert.DoesNotContain(subsequentResourcesRequested, path =>
!path.Contains("/dotnet.native.", StringComparison.Ordinal) &&
- path.EndsWith(".wasm", StringComparison.Ordinal)));
+ path.EndsWith(".wasm", StringComparison.Ordinal));
}
[Fact]
diff --git a/src/Components/test/E2ETest/Tests/HostedInAlternativeBasePathTest.cs b/src/Components/test/E2ETest/Tests/HostedInAlternativeBasePathTest.cs
index a513fda50fb5..df1cbaecc556 100644
--- a/src/Components/test/E2ETest/Tests/HostedInAlternativeBasePathTest.cs
+++ b/src/Components/test/E2ETest/Tests/HostedInAlternativeBasePathTest.cs
@@ -32,7 +32,7 @@ protected override void InitializeAsyncCore()
public void CanLoadBlazorAppFromSubPath()
{
Assert.Equal("App loaded on custom path", Browser.Title);
- Assert.Equal(0, Browser.GetBrowserLogs(LogLevel.Severe).Count);
+ Assert.Empty(Browser.GetBrowserLogs(LogLevel.Severe));
}
private void WaitUntilLoaded()
diff --git a/src/Components/test/E2ETest/Tests/InteropTest.cs b/src/Components/test/E2ETest/Tests/InteropTest.cs
index 45ea9805fd0e..f85e4036f398 100644
--- a/src/Components/test/E2ETest/Tests/InteropTest.cs
+++ b/src/Components/test/E2ETest/Tests/InteropTest.cs
@@ -186,7 +186,7 @@ public void CanInvokeDotNetMethods()
{
if (expectedValue.Value != actualValue)
{
- throw new AssertActualExpectedException(expectedValue.Value, actualValue, $"Scenario '{expectedValue.Key}' failed. Expected '{expectedValue.Value}, Actual {actualValue}");
+ throw EqualException.ForMismatchedValues(expectedValue.Value, actualValue, $"Scenario '{expectedValue.Key}' failed. Expected '{expectedValue.Value}, Actual {actualValue}");
}
}
}
diff --git a/src/Components/test/E2ETest/Tests/MultipleHostedAppTest.cs b/src/Components/test/E2ETest/Tests/MultipleHostedAppTest.cs
index 230b1bc11a68..feee1434d50d 100644
--- a/src/Components/test/E2ETest/Tests/MultipleHostedAppTest.cs
+++ b/src/Components/test/E2ETest/Tests/MultipleHostedAppTest.cs
@@ -34,7 +34,7 @@ public void CanLoadBlazorAppFromSubPath()
Navigate("/app/");
WaitUntilLoaded();
Assert.Equal("App loaded on custom path", Browser.Title);
- Assert.Equal(0, Browser.GetBrowserLogs(LogLevel.Severe).Count);
+ Assert.Empty(Browser.GetBrowserLogs(LogLevel.Severe));
}
[Fact]
diff --git a/src/DataProtection/Cryptography.Internal/test/Cng/BCryptUtilTests.cs b/src/DataProtection/Cryptography.Internal/test/Cng/BCryptUtilTests.cs
index d5cd7420582f..6d6d9f9f6d66 100644
--- a/src/DataProtection/Cryptography.Internal/test/Cng/BCryptUtilTests.cs
+++ b/src/DataProtection/Cryptography.Internal/test/Cng/BCryptUtilTests.cs
@@ -55,6 +55,6 @@ public void GenRandom_PopulatesBuffer()
}
}
- Assert.True(false, "Buffer was not filled as expected.");
+ Assert.Fail("Buffer was not filled as expected.");
}
}
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorTests.cs
index d97993ee6074..e8131de80b71 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorTests.cs
@@ -101,8 +101,8 @@ public void CreateAuthenticatedEncryptor_RoundTripsData_AesGcmImplementation(Enc
Assert.Equal(plaintext, roundTripPlaintext);
}
- public static TheoryData CreateAuthenticatedEncryptor_RoundTripsData_ManagedImplementationData
- => new TheoryData>
+ public static TheoryData> CreateAuthenticatedEncryptor_RoundTripsData_ManagedImplementationData
+ => new()
{
{ EncryptionAlgorithm.AES_128_CBC, ValidationAlgorithm.HMACSHA256, () => new HMACSHA256() },
{ EncryptionAlgorithm.AES_192_CBC, ValidationAlgorithm.HMACSHA256, () => new HMACSHA256() },
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/KeyRingProviderTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/KeyRingProviderTests.cs
index 844123f591e8..2436d938c0ed 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/KeyRingProviderTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/KeyRingProviderTests.cs
@@ -709,8 +709,10 @@ public void GetCurrentKeyRing_NoExistingKeyRing_HoldsAllThreadsUntilKeyRingCreat
Assert.True(mreBackgroundThreadHasCalledGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
mreForegroundThreadIsCallingGetCurrentKeyRing.Set();
var foregroundRetVal = keyRingProvider.GetCurrentKeyRingCore(now);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
backgroundGetKeyRingTask.Wait(testTimeout);
var backgroundRetVal = backgroundGetKeyRingTask.GetAwaiter().GetResult();
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
// Assert - underlying provider only should have been called once
Assert.Same(expectedKeyRing, foregroundRetVal);
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/XmlKeyManagerTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/XmlKeyManagerTests.cs
index 998088277438..f624199f6eae 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/XmlKeyManagerTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/XmlKeyManagerTests.cs
@@ -328,7 +328,7 @@ public void GetAllKeys_Empty()
var keys = RunGetAllKeysCore(xml, activator);
// Assert
- Assert.Equal(0, keys.Count);
+ Assert.Empty(keys);
}
[Fact]
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/EphemeralXmlRepositoryTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/EphemeralXmlRepositoryTests.cs
index e00b13c5d7bd..ba7dc9fa4c7c 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/EphemeralXmlRepositoryTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/EphemeralXmlRepositoryTests.cs
@@ -99,7 +99,7 @@ public void DeleteElementsWithOutOfBandDeletion()
// Now that the repository has read the element from the registry, delete it out-of-band.
repository.DeleteElements(deletableElements => deletableElements.First().DeletionOrder = 1);
- Assert.Equal(1, deletableElements.Count);
+ Assert.Single(deletableElements);
deletableElements.First().DeletionOrder = 1;
}));
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/FileSystemXmlRepositoryTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/FileSystemXmlRepositoryTests.cs
index 036b1ed4596d..a3ba5bbeeef9 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/FileSystemXmlRepositoryTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/FileSystemXmlRepositoryTests.cs
@@ -55,7 +55,7 @@ public void GetAllElements_EmptyOrNonexistentDirectory_ReturnsEmptyCollection()
var allElements = repository.GetAllElements();
// Assert
- Assert.Equal(0, allElements.Count);
+ Assert.Empty(allElements);
});
}
@@ -264,7 +264,7 @@ public void DeleteElementsWithOutOfBandDeletion()
// Now that the repository has read the element from disk, delete it out-of-band.
File.Delete(filePath);
- Assert.Equal(1, deletableElements.Count);
+ Assert.Single(deletableElements);
deletableElements.First().DeletionOrder = 1;
}));
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/RegistryXmlRepositoryTests.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/RegistryXmlRepositoryTests.cs
index 1835eb4b39a1..c39722dec113 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/RegistryXmlRepositoryTests.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/Repositories/RegistryXmlRepositoryTests.cs
@@ -42,7 +42,7 @@ public void GetAllElements_EmptyOrNonexistentDirectory_ReturnsEmptyCollection()
var allElements = repository.GetAllElements();
// Assert
- Assert.Equal(0, allElements.Count);
+ Assert.Empty(allElements);
});
}
@@ -206,7 +206,7 @@ public void DeleteElementsWithOutOfBandDeletion()
// Now that the repository has read the element from the registry, delete it out-of-band.
regKey.DeleteValue("friendly1");
- Assert.Equal(1, deletableElements.Count);
+ Assert.Single(deletableElements);
deletableElements.First().DeletionOrder = 1;
}));
diff --git a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlAssert.cs b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlAssert.cs
index acc527b8a961..e08afec11ca8 100644
--- a/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlAssert.cs
+++ b/src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/XmlAssert.cs
@@ -33,7 +33,7 @@ public static void Equal(XElement expected, XElement actual)
if (!Core.AreEqual(expected, actual))
{
- Assert.True(false,
+ Assert.Fail(
"Expected element:" + Environment.NewLine
+ expected.ToString() + Environment.NewLine
+ "Actual element:" + Environment.NewLine
diff --git a/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/WebHostFunctionalTests.cs b/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/WebHostFunctionalTests.cs
index cd11d5448522..3c236faad156 100644
--- a/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/WebHostFunctionalTests.cs
+++ b/src/DefaultBuilder/test/Microsoft.AspNetCore.FunctionalTests/WebHostFunctionalTests.cs
@@ -126,7 +126,7 @@ public void LoggingConfigurationSectionPassedToLoggerByDefault()
logger.Log(LogLevel.Information, 0, "Message", null, (s, e) =>
{
- Assert.True(false, "Information log when log level set to warning in config");
+ Assert.Fail("Information log when log level set to warning in config");
return string.Empty;
});
diff --git a/src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/WebApplicationTests.cs b/src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/WebApplicationTests.cs
index 43a3573cee89..7c5bc1aebe16 100644
--- a/src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/WebApplicationTests.cs
+++ b/src/DefaultBuilder/test/Microsoft.AspNetCore.Tests/WebApplicationTests.cs
@@ -1770,10 +1770,10 @@ public void EmptyWebApplicationBuilder_OnlyContainsMinimalServices()
{
var builder = WebApplication.CreateEmptyBuilder(new());
- Assert.Empty(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IConfigureOptions)));
- Assert.Empty(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IOptionsChangeTokenSource)));
- Assert.Empty(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IServer)));
- Assert.Empty(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(EndpointDataSource)));
+ Assert.DoesNotContain(builder.Services, descriptor => descriptor.ServiceType == typeof(IConfigureOptions));
+ Assert.DoesNotContain(builder.Services, descriptor => descriptor.ServiceType == typeof(IOptionsChangeTokenSource));
+ Assert.DoesNotContain(builder.Services, descriptor => descriptor.ServiceType == typeof(IServer));
+ Assert.DoesNotContain(builder.Services, descriptor => descriptor.ServiceType == typeof(EndpointDataSource));
// These services are still necessary
Assert.Single(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IWebHostEnvironment)));
@@ -1932,7 +1932,7 @@ public async Task WebApplication_CallsUseRoutingAndUseEndpoints(CreateBuilderFun
await app.StartAsync();
var ds = app.Services.GetRequiredService();
- Assert.Equal(1, ds.Endpoints.Count);
+ Assert.Single(ds.Endpoints);
Assert.Equal("One", ds.Endpoints[0].DisplayName);
var client = app.GetTestClient();
diff --git a/src/Features/JsonPatch/test/IntegrationTests/DictionaryIntegrationTest.cs b/src/Features/JsonPatch/test/IntegrationTests/DictionaryIntegrationTest.cs
index 7343e04fb29e..bd63306fb8bd 100644
--- a/src/Features/JsonPatch/test/IntegrationTests/DictionaryIntegrationTest.cs
+++ b/src/Features/JsonPatch/test/IntegrationTests/DictionaryIntegrationTest.cs
@@ -57,7 +57,7 @@ public void RemoveIntegerValue_Succeeds()
patchDocument.ApplyTo(model);
// Assert
- Assert.Equal(1, model.DictionaryOfStringToInteger.Count);
+ Assert.Single(model.DictionaryOfStringToInteger);
Assert.Equal(1, model.DictionaryOfStringToInteger["one"]);
}
@@ -75,7 +75,7 @@ public void MoveIntegerValue_Succeeds()
patchDocument.ApplyTo(model);
// Assert
- Assert.Equal(1, model.DictionaryOfStringToInteger.Count);
+ Assert.Single(model.DictionaryOfStringToInteger);
Assert.Equal(1, model.DictionaryOfStringToInteger["two"]);
}
diff --git a/src/FileProviders/Embedded/test/EmbeddedFileProviderTests.cs b/src/FileProviders/Embedded/test/EmbeddedFileProviderTests.cs
index 5ae31794fb53..0b68036f47b2 100644
--- a/src/FileProviders/Embedded/test/EmbeddedFileProviderTests.cs
+++ b/src/FileProviders/Embedded/test/EmbeddedFileProviderTests.cs
@@ -83,7 +83,7 @@ public void GetFileInfo_ReturnsNotFoundIfPathStartsWithBackSlash()
Assert.False(fileInfo.Exists);
}
- public static TheoryData GetFileInfo_LocatesFilesUnderSpecifiedNamespaceData
+ public static TheoryData GetFileInfo_LocatesFilesUnderSpecifiedNamespaceData
{
get
{
@@ -121,7 +121,7 @@ public void GetFileInfo_LocatesFilesUnderSpecifiedNamespace(string path)
Assert.Equal("File3.txt", fileInfo.Name);
}
- public static TheoryData GetFileInfo_LocatesFilesUnderSubDirectoriesData
+ public static TheoryData GetFileInfo_LocatesFilesUnderSubDirectoriesData
{
get
{
@@ -159,7 +159,7 @@ public void GetFileInfo_LocatesFilesUnderSubDirectories(string path)
Assert.Equal("File.txt", fileInfo.Name);
}
- public static TheoryData GetFileInfo_LocatesFilesUnderSubDirectories_IfDirectoriesContainsInvalidEverettCharData
+ public static TheoryData GetFileInfo_LocatesFilesUnderSubDirectories_IfDirectoriesContainsInvalidEverettCharData
{
get
{
diff --git a/src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternParserTests.cs b/src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternParserTests.cs
index 332827e58af6..960100c0461f 100644
--- a/src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternParserTests.cs
+++ b/src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternParserTests.cs
@@ -176,7 +176,7 @@ private void TryParseSubTrees(
// Ensure the diagnostic we emit is the same as the .NET one. Note: we can only
// do this in en as that's the only culture where we control the text exactly
- // and can ensure it exactly matches RoutePattern. We depend on localization to do a
+ // and can ensure it exactly matches RoutePattern. We depend on localization to do a
// good enough job here for other languages.
if (Thread.CurrentThread.CurrentCulture.Parent.Name == "en")
{
@@ -195,7 +195,7 @@ private void TryParseSubTrees(
if (!tree.Diagnostics.IsEmpty && !allowDiagnosticsMismatch)
{
var expectedDiagnostics = CreateDiagnosticsElement(sourceText, tree);
- Assert.False(true, $"Parsing '{token.ValueText}' didn't throw an error for expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(@"""", @""""""));
+ Assert.Fail($"Parsing '{token.ValueText}' didn't throw an error for expected diagnostics: \r\n" + expectedDiagnostics.ToString().Replace(@"""", @""""""));
}
if (parsedRoutePatterns != null)
diff --git a/src/Framework/test/TargetingPackTests.cs b/src/Framework/test/TargetingPackTests.cs
index fbd159b3a045..84e711c23cbb 100644
--- a/src/Framework/test/TargetingPackTests.cs
+++ b/src/Framework/test/TargetingPackTests.cs
@@ -183,7 +183,7 @@ public void PackageOverridesContainsCorrectEntries()
}
else
{
- Assert.True(false, $"{packageName} is not a recognized aspNetCore or runtime dependency");
+ Assert.Fail($"{packageName} is not a recognized aspNetCore or runtime dependency");
}
});
}
diff --git a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/JsonTranscodingServiceMethodProviderTests.cs b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/JsonTranscodingServiceMethodProviderTests.cs
index a59540d67c9a..b20e026176e1 100644
--- a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/JsonTranscodingServiceMethodProviderTests.cs
+++ b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/JsonTranscodingServiceMethodProviderTests.cs
@@ -29,7 +29,7 @@ public void AddMethod_OptionGet_ResolveMethod()
Assert.Equal("GET", endpoint.Metadata.GetMetadata()?.HttpMethods.Single());
Assert.Equal("/v1/greeter/{name}", endpoint.RoutePattern.RawText);
- Assert.Equal(1, endpoint.RoutePattern.Parameters.Count);
+ Assert.Single(endpoint.RoutePattern.Parameters);
Assert.Equal("name", endpoint.RoutePattern.Parameters[0].Name);
}
diff --git a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/UnaryServerCallHandlerTests.cs b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/UnaryServerCallHandlerTests.cs
index 1c5b03d79483..1d6ad6ba4c38 100644
--- a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/UnaryServerCallHandlerTests.cs
+++ b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.JsonTranscoding.Tests/UnaryServerCallHandlerTests.cs
@@ -791,7 +791,7 @@ public async Task HandleCallAsync_MalformedRequestBody_RepeatedBody_BadRequestRe
[Theory]
[InlineData(null)]
[InlineData("text/html")]
- public async Task HandleCallAsync_BadContentType_BadRequestReturned(string contentType)
+ public async Task HandleCallAsync_BadContentType_BadRequestReturned(string? contentType)
{
// Arrange
UnaryServerMethod invoker = (s, r, c) =>
diff --git a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/Binding/ParametersTests.cs b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/Binding/ParametersTests.cs
index 8a4db851175f..4a27f8d945e7 100644
--- a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/Binding/ParametersTests.cs
+++ b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/Binding/ParametersTests.cs
@@ -67,7 +67,7 @@ public void RouteAndBodyFields_FilterRouteAndBodyQueryFields()
Assert.Equal("parameterThree", operation.Parameters[2].Name);
// body with one parameter
Assert.NotNull(operation.RequestBody);
- Assert.Equal(1, swagger.Components.Schemas["RequestBody"].Properties.Count);
+ Assert.Single(swagger.Components.Schemas["RequestBody"].Properties);
}
[Fact]
@@ -79,7 +79,7 @@ public void CatchAllBody_NoQueryFields()
// Assert
var path = swagger.Paths["/v1/parameters4/{parameterTwo}"];
Assert.True(path.Operations.TryGetValue(OperationType.Post, out var operation));
- Assert.Equal(1, operation.Parameters.Count);
+ Assert.Single(operation.Parameters);
Assert.Equal(ParameterLocation.Path, operation.Parameters[0].In);
Assert.Equal("parameterTwo", operation.Parameters[0].Name);
// body with four parameters
@@ -110,7 +110,7 @@ public void RepeatedStringField_ArrayQueryField()
// Assert
var path = swagger.Paths["/v1/parameters6"];
Assert.True(path.Operations.TryGetValue(OperationType.Get, out var operation));
- Assert.Equal(1, operation.Parameters.Count);
+ Assert.Single(operation.Parameters);
Assert.Equal(ParameterLocation.Query, operation.Parameters[0].In);
Assert.Equal("parameterOne", operation.Parameters[0].Name);
Assert.Equal("array", operation.Parameters[0].Schema.Type);
diff --git a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/SchemaGeneratorIntegrationTests.cs b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/SchemaGeneratorIntegrationTests.cs
index cafa080ac619..771a8e5c006c 100644
--- a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/SchemaGeneratorIntegrationTests.cs
+++ b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/SchemaGeneratorIntegrationTests.cs
@@ -38,7 +38,7 @@ public void GenerateSchema_EnumValue_ReturnSchema()
// Assert
schema = repository.Schemas[schema.Reference.Id];
Assert.Equal("object", schema.Type);
- Assert.Equal(1, schema.Properties.Count);
+ Assert.Single(schema.Properties);
var enumSchema = repository.Schemas[schema.Properties["enumValue"].Reference.Id];
Assert.Equal("string", enumSchema.Type);
@@ -99,7 +99,7 @@ public void GenerateSchema_RecursiveMessage_ReturnSchema()
// Assert
schema = repository.Schemas[schema.Reference.Id];
Assert.Equal("object", schema.Type);
- Assert.Equal(1, schema.Properties.Count);
+ Assert.Single(schema.Properties);
Assert.Equal("RecursiveMessage", schema.Properties["child"].Reference.Id);
}
@@ -143,7 +143,7 @@ public void GenerateSchema_Struct_ReturnSchema()
var resolvedSchema = repository.Schemas[schema.Reference.Id];
Assert.Equal("object", resolvedSchema.Type);
- Assert.Equal(0, resolvedSchema.Properties.Count);
+ Assert.Empty(resolvedSchema.Properties);
Assert.NotNull(resolvedSchema.AdditionalProperties);
Assert.Null(resolvedSchema.AdditionalProperties.Type);
}
@@ -159,7 +159,7 @@ public void GenerateSchema_Any_ReturnSchema()
Assert.Equal("object", schema.Type);
Assert.NotNull(schema.AdditionalProperties);
Assert.Null(schema.AdditionalProperties.Type);
- Assert.Equal(1, schema.Properties.Count);
+ Assert.Single(schema.Properties);
Assert.Equal("string", schema.Properties["@type"].Type);
}
@@ -189,7 +189,7 @@ public void GenerateSchema_Map_ReturnSchema()
// Assert
schema = repository.Schemas[schema.Reference.Id];
Assert.Equal("object", schema.Type);
- Assert.Equal(1, schema.Properties.Count);
+ Assert.Single(schema.Properties);
Assert.Equal("object", schema.Properties["mapValue"].Type);
Assert.Equal("number", schema.Properties["mapValue"].AdditionalProperties.Type);
Assert.Equal("double", schema.Properties["mapValue"].AdditionalProperties.Format);
@@ -204,7 +204,7 @@ public void GenerateSchema_FieldMask_ReturnSchema()
// Assert
schema = repository.Schemas[schema.Reference.Id];
Assert.Equal("object", schema.Type);
- Assert.Equal(1, schema.Properties.Count);
+ Assert.Single(schema.Properties);
Assert.Equal("string", schema.Properties["fieldMaskValue"].Type);
}
}
diff --git a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/XmlComments/XmlCommentsDocumentFilterTests.cs b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/XmlComments/XmlCommentsDocumentFilterTests.cs
index 6d9e0c3cc0d6..ed3bf26ab7dd 100644
--- a/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/XmlComments/XmlCommentsDocumentFilterTests.cs
+++ b/src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/XmlComments/XmlCommentsDocumentFilterTests.cs
@@ -40,7 +40,7 @@ public void Apply_SetsTagDescription_FromControllerSummaryTags(Type serviceType,
Subject().Apply(document, filterContext);
- Assert.Equal(1, document.Tags.Count);
+ Assert.Single(document.Tags);
Assert.Equal(expectedDescription, document.Tags[0].Description);
static ApiDescription CreateApiDescription(Type serviceType)
diff --git a/src/HealthChecks/HealthChecks/test/DefaultHealthCheckServiceTest.cs b/src/HealthChecks/HealthChecks/test/DefaultHealthCheckServiceTest.cs
index 386439cb89c5..c78290fd5dd4 100644
--- a/src/HealthChecks/HealthChecks/test/DefaultHealthCheckServiceTest.cs
+++ b/src/HealthChecks/HealthChecks/test/DefaultHealthCheckServiceTest.cs
@@ -517,7 +517,7 @@ public async Task CheckHealthAsync_ChecksAreRunInParallel()
await checkHealthTask;
// Assert
- Assert.Collection(checkHealthTask.Result.Entries,
+ Assert.Collection((await checkHealthTask).Entries,
entry =>
{
Assert.Equal("test1", entry.Key);
diff --git a/src/Hosting/Hosting/test/WebHostTests.cs b/src/Hosting/Hosting/test/WebHostTests.cs
index a89352b61da6..a6114d47f027 100644
--- a/src/Hosting/Hosting/test/WebHostTests.cs
+++ b/src/Hosting/Hosting/test/WebHostTests.cs
@@ -143,7 +143,7 @@ public void WebHostCanBeStarted()
{
var server = (FakeServer)host.Services.GetRequiredService();
Assert.NotNull(host);
- Assert.Equal(1, server.StartInstances.Count);
+ Assert.Single(server.StartInstances);
Assert.Equal(0, server.StartInstances[0].DisposeCalls);
host.Dispose();
@@ -174,7 +174,7 @@ public async Task WebHostShutsDownWhenTokenTriggers()
lifetime.ApplicationStarted.WaitHandle.WaitOne();
Assert.True(lifetime2.ApplicationStarted.IsCancellationRequested);
- Assert.Equal(1, server.StartInstances.Count);
+ Assert.Single(server.StartInstances);
Assert.Equal(0, server.StartInstances[0].DisposeCalls);
cts.Cancel();
diff --git a/src/Hosting/TestHost/test/ClientHandlerTests.cs b/src/Hosting/TestHost/test/ClientHandlerTests.cs
index fa8f23543be6..503408f0df05 100644
--- a/src/Hosting/TestHost/test/ClientHandlerTests.cs
+++ b/src/Hosting/TestHost/test/ClientHandlerTests.cs
@@ -392,7 +392,9 @@ public async Task BlockingMiddlewareShouldNotBlockClient()
var httpClient = new HttpClient(handler);
Task task = httpClient.GetAsync("https://example.com/");
Assert.False(task.IsCompleted);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(task.Wait(50));
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
block.Set();
HttpResponseMessage response = await task;
}
diff --git a/src/Hosting/TestHost/test/HttpContextBuilderTests.cs b/src/Hosting/TestHost/test/HttpContextBuilderTests.cs
index e524bbe7007b..30ebbf3f18f3 100644
--- a/src/Hosting/TestHost/test/HttpContextBuilderTests.cs
+++ b/src/Hosting/TestHost/test/HttpContextBuilderTests.cs
@@ -107,7 +107,9 @@ public async Task BlockingMiddlewareShouldNotBlockClient()
var task = server.SendAsync(c => { });
Assert.False(task.IsCompleted);
+#pragma warning disable xUnit1031 // Do not use blocking task operations in test method
Assert.False(task.Wait(50));
+#pragma warning restore xUnit1031 // Do not use blocking task operations in test method
block.Set();
var context = await task;
}
diff --git a/src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs b/src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs
index 2629dd7ceb05..2469ec7a7fa2 100644
--- a/src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs
+++ b/src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs
@@ -77,17 +77,17 @@ public void GetSetString()
{
var props = new AuthenticationProperties();
Assert.Null(props.GetString("foo"));
- Assert.Equal(0, props.Items.Count);
+ Assert.Empty(props.Items);
props.SetString("foo", "foo bar");
Assert.Equal("foo bar", props.GetString("foo"));
Assert.Equal("foo bar", props.Items["foo"]);
- Assert.Equal(1, props.Items.Count);
+ Assert.Single(props.Items);
props.SetString("foo", "foo baz");
Assert.Equal("foo baz", props.GetString("foo"));
Assert.Equal("foo baz", props.Items["foo"]);
- Assert.Equal(1, props.Items.Count);
+ Assert.Single(props.Items);
props.SetString("bar", "xy");
Assert.Equal("xy", props.GetString("bar"));
@@ -100,11 +100,11 @@ public void GetSetString()
props.SetString("foo", null);
Assert.Null(props.GetString("foo"));
- Assert.Equal(1, props.Items.Count);
+ Assert.Single(props.Items);
props.SetString("doesntexist", null);
Assert.False(props.Items.ContainsKey("doesntexist"));
- Assert.Equal(1, props.Items.Count);
+ Assert.Single(props.Items);
}
[Fact]
@@ -112,17 +112,17 @@ public void GetSetParameter_String()
{
var props = new AuthenticationProperties();
Assert.Null(props.GetParameter("foo"));
- Assert.Equal(0, props.Parameters.Count);
+ Assert.Empty(props.Parameters);
props.SetParameter("foo", "foo bar");
Assert.Equal("foo bar", props.GetParameter("foo"));
Assert.Equal("foo bar", props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
props.SetParameter("foo", null);
Assert.Null(props.GetParameter("foo"));
Assert.Null(props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
}
[Fact]
@@ -130,17 +130,17 @@ public void GetSetParameter_Int()
{
var props = new AuthenticationProperties();
Assert.Null(props.GetParameter("foo"));
- Assert.Equal(0, props.Parameters.Count);
+ Assert.Empty(props.Parameters);
props.SetParameter("foo", 123);
Assert.Equal(123, props.GetParameter("foo"));
Assert.Equal(123, props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
props.SetParameter("foo", null);
Assert.Null(props.GetParameter("foo"));
Assert.Null(props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
}
[Fact]
@@ -148,18 +148,18 @@ public void GetSetParameter_Collection()
{
var props = new AuthenticationProperties();
Assert.Null(props.GetParameter("foo"));
- Assert.Equal(0, props.Parameters.Count);
+ Assert.Empty(props.Parameters);
var list = new string[] { "a", "b", "c" };
props.SetParameter>("foo", list);
Assert.Equal(new string[] { "a", "b", "c" }, props.GetParameter>("foo"));
Assert.Same(list, props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
props.SetParameter?>("foo", null);
Assert.Null(props.GetParameter>("foo"));
Assert.Null(props.Parameters["foo"]);
- Assert.Equal(1, props.Parameters.Count);
+ Assert.Single(props.Parameters);
}
[Fact]
@@ -341,7 +341,7 @@ public void Roundtrip_Serializes_With_SystemTextJson()
// Ensure that parameters are not round-tripped
Assert.NotNull(deserialized.Parameters);
- Assert.Equal(0, deserialized.Parameters.Count);
+ Assert.Empty(deserialized.Parameters);
}
[Fact]
@@ -355,7 +355,7 @@ public void Parameters_Is_Not_Deserialized_With_SystemTextJson()
// Ensure that parameters is not deserialized from a raw payload
Assert.NotNull(deserialized!.Parameters);
- Assert.Equal(0, deserialized.Parameters.Count);
+ Assert.Empty(deserialized.Parameters);
}
[Fact]
diff --git a/src/Http/Headers/test/CacheControlHeaderValueTest.cs b/src/Http/Headers/test/CacheControlHeaderValueTest.cs
index 12a5e209398c..a081d5b6a2c6 100644
--- a/src/Http/Headers/test/CacheControlHeaderValueTest.cs
+++ b/src/Http/Headers/test/CacheControlHeaderValueTest.cs
@@ -46,21 +46,21 @@ public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter()
Assert.Throws(() => cacheControl.NoCacheHeaders.Add(null));
Assert.Throws(() => cacheControl.NoCacheHeaders.Add("invalid PLACEHOLDER"));
cacheControl.NoCacheHeaders.Add("PLACEHOLDER");
- Assert.Equal(1, cacheControl.NoCacheHeaders.Count);
+ Assert.Single(cacheControl.NoCacheHeaders);
Assert.Equal("PLACEHOLDER", cacheControl.NoCacheHeaders.First());
Assert.NotNull(cacheControl.PrivateHeaders);
Assert.Throws(() => cacheControl.PrivateHeaders.Add(null));
Assert.Throws(() => cacheControl.PrivateHeaders.Add("invalid PLACEHOLDER"));
cacheControl.PrivateHeaders.Add("PLACEHOLDER");
- Assert.Equal(1, cacheControl.PrivateHeaders.Count);
+ Assert.Single(cacheControl.PrivateHeaders);
Assert.Equal("PLACEHOLDER", cacheControl.PrivateHeaders.First());
// NameValueHeaderValue collection property
Assert.NotNull(cacheControl.Extensions);
Assert.Throws(() => cacheControl.Extensions.Add(null!));
cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value"));
- Assert.Equal(1, cacheControl.Extensions.Count);
+ Assert.Single(cacheControl.Extensions);
Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First());
}
@@ -468,7 +468,7 @@ public void TryParse_DifferentValidScenarios_AllReturnTrue()
[InlineData("s-maxage=1.5")]
// Invalid Extension values
[InlineData("custom value")]
- public void TryParse_DifferentInvalidScenarios_ReturnsFalse(string input)
+ public void TryParse_DifferentInvalidScenarios_ReturnsFalse(string? input)
{
CheckInvalidTryParse(input);
}
diff --git a/src/Http/Headers/test/ContentDispositionHeaderValueTest.cs b/src/Http/Headers/test/ContentDispositionHeaderValueTest.cs
index 38f7cfb4b7ca..405d693f9cc0 100644
--- a/src/Http/Headers/test/ContentDispositionHeaderValueTest.cs
+++ b/src/Http/Headers/test/ContentDispositionHeaderValueTest.cs
@@ -43,7 +43,7 @@ public void Ctor_ContentDispositionValidFormat_SuccessfullyCreated()
{
var contentDisposition = new ContentDispositionHeaderValue("inline");
Assert.Equal("inline", contentDisposition.DispositionType);
- Assert.Equal(0, contentDisposition.Parameters.Count);
+ Assert.Empty(contentDisposition.Parameters);
Assert.Null(contentDisposition.Name.Value);
Assert.Null(contentDisposition.FileName.Value);
Assert.Null(contentDisposition.CreationDate);
@@ -75,12 +75,12 @@ public void Name_SetNameAndValidateObject_ParametersEntryForNameAdded()
var contentDisposition = new ContentDispositionHeaderValue("inline");
contentDisposition.Name = "myname";
Assert.Equal("myname", contentDisposition.Name);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("name", contentDisposition.Parameters.First().Name);
contentDisposition.Name = null;
Assert.Null(contentDisposition.Name.Value);
- Assert.Equal(0, contentDisposition.Parameters.Count);
+ Assert.Empty(contentDisposition.Parameters);
contentDisposition.Name = null; // It's OK to set it again to null; no exception.
}
@@ -92,12 +92,12 @@ public void Name_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
NameValueHeaderValue name = new NameValueHeaderValue("NAME", "old_name");
contentDisposition.Parameters.Add(name);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("NAME", contentDisposition.Parameters.First().Name);
contentDisposition.Name = "new_name";
Assert.Equal("new_name", contentDisposition.Name);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("NAME", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(name);
@@ -112,12 +112,12 @@ public void FileName_AddNameParameterThenUseProperty_ParametersEntryIsOverwritte
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var fileName = new NameValueHeaderValue("FILENAME", "old_name");
contentDisposition.Parameters.Add(fileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);
contentDisposition.FileName = "new_name";
Assert.Equal("new_name", contentDisposition.FileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(fileName);
@@ -131,7 +131,7 @@ public void FileName_NeedsEncoding_EncodedAndDecodedCorrectly()
contentDisposition.FileName = "FileÃName.bat";
Assert.Equal("FileÃName.bat", contentDisposition.FileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("filename", contentDisposition.Parameters.First().Name);
Assert.Equal("\"=?utf-8?B?RmlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value);
@@ -146,7 +146,7 @@ public void FileName_NeedsEncodingBecauseOfNewLine_EncodedAndDecodedCorrectly()
contentDisposition.FileName = "File\nName.bat";
Assert.Equal("File\nName.bat", contentDisposition.FileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("filename", contentDisposition.Parameters.First().Name);
Assert.Equal("\"=?utf-8?B?RmlsZQpOYW1lLmJhdA==?=\"", contentDisposition.Parameters.First().Value);
@@ -162,14 +162,14 @@ public void FileName_UnknownOrBadEncoding_PropertyFails()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var fileName = new NameValueHeaderValue("FILENAME", "\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"");
contentDisposition.Parameters.Add(fileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);
Assert.Equal("\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value);
Assert.Equal("=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=", contentDisposition.FileName);
contentDisposition.FileName = "new_name";
Assert.Equal("new_name", contentDisposition.FileName);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(fileName);
@@ -184,13 +184,13 @@ public void FileNameStar_AddNameParameterThenUseProperty_ParametersEntryIsOverwr
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var fileNameStar = new NameValueHeaderValue("FILENAME*", "old_name");
contentDisposition.Parameters.Add(fileNameStar);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
Assert.Null(contentDisposition.FileNameStar.Value); // Decode failure
contentDisposition.FileNameStar = "new_name";
Assert.Equal("new_name", contentDisposition.FileNameStar);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
Assert.Equal("UTF-8\'\'new_name", contentDisposition.Parameters.First().Value);
@@ -205,7 +205,7 @@ public void FileNameStar_NeedsEncoding_EncodedAndDecodedCorrectly()
contentDisposition.FileNameStar = "FileÃName.bat";
Assert.Equal("FileÃName.bat", contentDisposition.FileNameStar);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("filename*", contentDisposition.Parameters.First().Name);
Assert.Equal("UTF-8\'\'File%C3%83Name.bat", contentDisposition.Parameters.First().Value);
@@ -268,14 +268,14 @@ public void FileNameStar_UnknownOrBadEncoding_PropertyFails()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var fileNameStar = new NameValueHeaderValue("FILENAME*", "utf-99'lang'File%CZName.bat");
contentDisposition.Parameters.Add(fileNameStar);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
Assert.Equal("utf-99'lang'File%CZName.bat", contentDisposition.Parameters.First().Value);
Assert.Null(contentDisposition.FileNameStar.Value); // Decode failure
contentDisposition.FileNameStar = "new_name";
Assert.Equal("new_name", contentDisposition.FileNameStar);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(fileNameStar);
@@ -309,7 +309,7 @@ public void Dates_AddDateParameterThenUseProperty_ParametersEntryIsOverwritten()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var dateParameter = new NameValueHeaderValue("Creation-DATE", validDateString);
contentDisposition.Parameters.Add(dateParameter);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name);
Assert.Equal(validDate, contentDisposition.CreationDate);
@@ -317,7 +317,7 @@ public void Dates_AddDateParameterThenUseProperty_ParametersEntryIsOverwritten()
var newDate = validDate.AddSeconds(1);
contentDisposition.CreationDate = newDate;
Assert.Equal(newDate, contentDisposition.CreationDate);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name);
Assert.Equal("\"Tue, 15 Nov 1994 08:12:32 GMT\"", contentDisposition.Parameters.First().Value);
@@ -335,14 +335,14 @@ public void Dates_InvalidDates_PropertyFails()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var dateParameter = new NameValueHeaderValue("read-DATE", invalidDateString);
contentDisposition.Parameters.Add(dateParameter);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("read-DATE", contentDisposition.Parameters.First().Name);
Assert.Null(contentDisposition.ReadDate);
contentDisposition.ReadDate = null;
Assert.Null(contentDisposition.ReadDate);
- Assert.Equal(0, contentDisposition.Parameters.Count);
+ Assert.Empty(contentDisposition.Parameters);
}
[Fact]
@@ -353,13 +353,13 @@ public void Size_AddSizeParameterThenUseProperty_ParametersEntryIsOverwritten()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var sizeParameter = new NameValueHeaderValue("SIZE", "279172874239");
contentDisposition.Parameters.Add(sizeParameter);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
Assert.Equal(279172874239, contentDisposition.Size);
contentDisposition.Size = 279172874240;
Assert.Equal(279172874240, contentDisposition.Size);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(sizeParameter);
@@ -374,14 +374,14 @@ public void Size_InvalidSizes_PropertyFails()
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var sizeParameter = new NameValueHeaderValue("SIZE", "-279172874239");
contentDisposition.Parameters.Add(sizeParameter);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
Assert.Null(contentDisposition.Size);
// Negatives not allowed
Assert.Throws(() => contentDisposition.Size = -279172874240);
Assert.Null(contentDisposition.Size);
- Assert.Equal(1, contentDisposition.Parameters.Count);
+ Assert.Single(contentDisposition.Parameters);
Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
contentDisposition.Parameters.Remove(sizeParameter);
diff --git a/src/Http/Headers/test/CookieHeaderValueTest.cs b/src/Http/Headers/test/CookieHeaderValueTest.cs
index 6623a8ed13dd..02e00068f878 100644
--- a/src/Http/Headers/test/CookieHeaderValueTest.cs
+++ b/src/Http/Headers/test/CookieHeaderValueTest.cs
@@ -278,7 +278,7 @@ public void CookieHeaderValue_TryParseStrictList_AcceptsValidValues(IList cookies, string[] input)
+ public void CookieHeaderValue_ParseList_ExcludesInvalidValues(IList? cookies, string[] input)
{
var results = CookieHeaderValue.ParseList(input);
// ParseList always returns a list, even if empty. TryParseList may return null (via out).
@@ -287,7 +287,7 @@ public void CookieHeaderValue_ParseList_ExcludesInvalidValues(IList cookies, string[] input)
+ public void CookieHeaderValue_TryParseList_ExcludesInvalidValues(IList? cookies, string[] input)
{
var result = CookieHeaderValue.TryParseList(input, out var results);
Assert.Equal(cookies, results);
@@ -298,7 +298,7 @@ public void CookieHeaderValue_TryParseList_ExcludesInvalidValues(IList cookies,
+ IList? cookies,
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
string[] input)
{
@@ -309,7 +309,7 @@ public void CookieHeaderValue_ParseStrictList_ThrowsForAnyInvalidValues(
[MemberData(nameof(ListWithInvalidCookieHeaderDataSet))]
public void CookieHeaderValue_TryParseStrictList_FailsForAnyInvalidValues(
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
- IList cookies,
+ IList? cookies,
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
string[] input)
{
diff --git a/src/Http/Headers/test/EntityTagHeaderValueTest.cs b/src/Http/Headers/test/EntityTagHeaderValueTest.cs
index 21bd9a52b6ed..48086ab29613 100644
--- a/src/Http/Headers/test/EntityTagHeaderValueTest.cs
+++ b/src/Http/Headers/test/EntityTagHeaderValueTest.cs
@@ -245,15 +245,15 @@ public void ParseList_NullOrEmptyArray_ReturnsEmptyList()
{
var result = EntityTagHeaderValue.ParseList(null);
Assert.NotNull(result);
- Assert.Equal(0, result.Count);
+ Assert.Empty(result);
result = EntityTagHeaderValue.ParseList(new string[0]);
Assert.NotNull(result);
- Assert.Equal(0, result.Count);
+ Assert.Empty(result);
result = EntityTagHeaderValue.ParseList(new string[] { "" });
Assert.NotNull(result);
- Assert.Equal(0, result.Count);
+ Assert.Empty(result);
}
[Fact]
diff --git a/src/Http/Headers/test/HeaderUtilitiesTest.cs b/src/Http/Headers/test/HeaderUtilitiesTest.cs
index 77d46369c5b0..9ce61faec7f9 100644
--- a/src/Http/Headers/test/HeaderUtilitiesTest.cs
+++ b/src/Http/Headers/test/HeaderUtilitiesTest.cs
@@ -90,10 +90,10 @@ public void TryParseSeconds_Succeeds(string headerValues, string targetValue, in
[InlineData("directive1, directive2=80", "directive")]
[InlineData("directive1=;, directive2=10", "directive1")]
[InlineData("directive1;directive2=10", "directive2")]
- public void TryParseSeconds_Fails(string headerValues, string targetValue)
+ public void TryParseSeconds_Fails(string? headerValues, string? targetValue)
{
TimeSpan? value;
- Assert.False(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue, out value));
+ Assert.False(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue!, out value));
}
[Theory]
@@ -168,9 +168,9 @@ public void FormatInt64_MatchesToString(long value)
[InlineData("directive1, directive2=80", "directive", false)]
[InlineData("directive1;, directive2=80", "directive", false)]
[InlineData("directive1=value;q=0.6;directive2 = 42 ", "directive2", false)]
- public void ContainsCacheDirective_MatchesExactValue(string headerValues, string targetValue, bool contains)
+ public void ContainsCacheDirective_MatchesExactValue(string? headerValues, string? targetValue, bool contains)
{
- Assert.Equal(contains, HeaderUtilities.ContainsCacheDirective(new StringValues(headerValues), targetValue));
+ Assert.Equal(contains, HeaderUtilities.ContainsCacheDirective(new StringValues(headerValues), targetValue!));
}
[Theory]
@@ -180,7 +180,7 @@ public void ContainsCacheDirective_MatchesExactValue(string headerValues, string
[InlineData("a")]
[InlineData("1.1")]
[InlineData("9223372036854775808")] // long.MaxValue + 1
- public void TryParseNonNegativeInt64_Fails(string valueString)
+ public void TryParseNonNegativeInt64_Fails(string? valueString)
{
long value = 1;
Assert.False(HeaderUtilities.TryParseNonNegativeInt64(valueString, out value));
@@ -205,7 +205,7 @@ public void TryParseNonNegativeInt64_Succeeds(string valueString, long expected)
[InlineData("1.1")]
[InlineData("1,000")]
[InlineData("2147483648")] // int.MaxValue + 1
- public void TryParseNonNegativeInt32_Fails(string valueString)
+ public void TryParseNonNegativeInt32_Fails(string? valueString)
{
int value = 1;
Assert.False(HeaderUtilities.TryParseNonNegativeInt32(valueString, out value));
diff --git a/src/Http/Headers/test/MediaTypeHeaderValueTest.cs b/src/Http/Headers/test/MediaTypeHeaderValueTest.cs
index 624cb1638b6e..5af91d202643 100644
--- a/src/Http/Headers/test/MediaTypeHeaderValueTest.cs
+++ b/src/Http/Headers/test/MediaTypeHeaderValueTest.cs
@@ -49,7 +49,7 @@ public void Ctor_MediaTypeInvalidFormat_ThrowFormatException()
[Theory]
[MemberData(nameof(MediaTypesWithSuffixes))]
- public void Ctor_CanParseSuffixedMediaTypes(string mediaType, string expectedSubTypeWithoutSuffix, string expectedSubTypeSuffix)
+ public void Ctor_CanParseSuffixedMediaTypes(string mediaType, string expectedSubTypeWithoutSuffix, string? expectedSubTypeSuffix)
{
var result = new MediaTypeHeaderValue(mediaType);
@@ -103,7 +103,7 @@ public void Ctor_MediaTypeValidFormat_SuccessfullyCreated()
{
var mediaType = new MediaTypeHeaderValue("text/plain");
Assert.Equal("text/plain", mediaType.MediaType);
- Assert.Equal(0, mediaType.Parameters.Count);
+ Assert.Empty(mediaType.Parameters);
Assert.Null(mediaType.Charset.Value);
}
@@ -113,7 +113,7 @@ public void Ctor_AddNameAndQuality_QualityParameterAdded()
var mediaType = new MediaTypeHeaderValue("application/xml", 0.08);
Assert.Equal(0.08, mediaType.Quality);
Assert.Equal("application/xml", mediaType.MediaType);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
}
[Fact]
@@ -233,12 +233,12 @@ public void Charset_SetCharsetAndValidateObject_ParametersEntryForCharsetAdded()
var mediaType = new MediaTypeHeaderValue("text/plain");
mediaType.Charset = "mycharset";
Assert.Equal("mycharset", mediaType.Charset);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("charset", mediaType.Parameters.First().Name);
mediaType.Charset = null;
Assert.Null(mediaType.Charset.Value);
- Assert.Equal(0, mediaType.Parameters.Count);
+ Assert.Empty(mediaType.Parameters);
mediaType.Charset = null; // It's OK to set it again to null; no exception.
}
@@ -250,12 +250,12 @@ public void Charset_AddCharsetParameterThenUseProperty_ParametersEntryIsOverwrit
// Note that uppercase letters are used. Comparison should happen case-insensitive.
var charset = new NameValueHeaderValue("CHARSET", "old_charset");
mediaType.Parameters.Add(charset);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("CHARSET", mediaType.Parameters.First().Name);
mediaType.Charset = "new_charset";
Assert.Equal("new_charset", mediaType.Charset);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("CHARSET", mediaType.Parameters.First().Name);
mediaType.Parameters.Remove(charset);
@@ -268,13 +268,13 @@ public void Quality_SetCharsetAndValidateObject_ParametersEntryForCharsetAdded()
var mediaType = new MediaTypeHeaderValue("text/plain");
mediaType.Quality = 0.563156454;
Assert.Equal(0.563, mediaType.Quality);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("q", mediaType.Parameters.First().Name);
Assert.Equal("0.563", mediaType.Parameters.First().Value);
mediaType.Quality = null;
Assert.Null(mediaType.Quality);
- Assert.Equal(0, mediaType.Parameters.Count);
+ Assert.Empty(mediaType.Parameters);
mediaType.Quality = null; // It's OK to set it again to null; no exception.
}
@@ -285,13 +285,13 @@ public void Quality_AddQualityParameterThenUseProperty_ParametersEntryIsOverwrit
var quality = new NameValueHeaderValue("q", "0.132");
mediaType.Parameters.Add(quality);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("q", mediaType.Parameters.First().Name);
Assert.Equal(0.132, mediaType.Quality);
mediaType.Quality = 0.9;
Assert.Equal(0.9, mediaType.Quality);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("q", mediaType.Parameters.First().Name);
mediaType.Parameters.Remove(quality);
@@ -305,7 +305,7 @@ public void Quality_AddQualityParameterUpperCase_CaseInsensitiveComparison()
var quality = new NameValueHeaderValue("Q", "0.132");
mediaType.Parameters.Add(quality);
- Assert.Equal(1, mediaType.Parameters.Count);
+ Assert.Single(mediaType.Parameters);
Assert.Equal("Q", mediaType.Parameters.First().Name);
Assert.Equal(0.132, mediaType.Quality);
}
@@ -518,15 +518,15 @@ public void ParseList_NullOrEmptyArray_ReturnsEmptyList()
{
var results = MediaTypeHeaderValue.ParseList(null);
Assert.NotNull(results);
- Assert.Equal(0, results.Count);
+ Assert.Empty(results);
results = MediaTypeHeaderValue.ParseList(new string[0]);
Assert.NotNull(results);
- Assert.Equal(0, results.Count);
+ Assert.Empty(results);
results = MediaTypeHeaderValue.ParseList(new string[] { "" });
Assert.NotNull(results);
- Assert.Equal(0, results.Count);
+ Assert.Empty(results);
}
[Fact]
diff --git a/src/Http/Headers/test/RangeConditionHeaderValueTest.cs b/src/Http/Headers/test/RangeConditionHeaderValueTest.cs
index b055ea0f67c0..e63f62e17516 100644
--- a/src/Http/Headers/test/RangeConditionHeaderValueTest.cs
+++ b/src/Http/Headers/test/RangeConditionHeaderValueTest.cs
@@ -115,7 +115,7 @@ public void Parse_SetOfValidValueStrings_ParsedCorrectly()
[InlineData("W/Wed 09 Nov 1994 08:49:37 GMT")]
[InlineData("\"x\",")]
[InlineData("Wed 09 Nov 1994 08:49:37 GMT,")]
- public void Parse_SetOfInvalidValueStrings_Throws(string input)
+ public void Parse_SetOfInvalidValueStrings_Throws(string? input)
{
Assert.Throws(() => RangeConditionHeaderValue.Parse(input));
}
@@ -144,7 +144,7 @@ public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
[InlineData("W/Wed 09 Nov 1994 08:49:37 GMT")]
[InlineData("\"x\",")]
[InlineData("Wed 09 Nov 1994 08:49:37 GMT,")]
- public void TryParse_SetOfInvalidValueStrings_ReturnsFalse(string input)
+ public void TryParse_SetOfInvalidValueStrings_ReturnsFalse(string? input)
{
Assert.False(RangeConditionHeaderValue.TryParse(input, out var result));
Assert.Null(result);
diff --git a/src/Http/Headers/test/RangeItemHeaderValueTest.cs b/src/Http/Headers/test/RangeItemHeaderValueTest.cs
index d9fb8bd33616..0d7e54ad4f81 100644
--- a/src/Http/Headers/test/RangeItemHeaderValueTest.cs
+++ b/src/Http/Headers/test/RangeItemHeaderValueTest.cs
@@ -119,7 +119,7 @@ public void TryParse_DifferentValidScenarios_AllReturnNonZero()
[InlineData("-12345678901234567890123")] // >>Int64.MaxValue
[InlineData("9999999999999999999-")] // 19-digit numbers outside the Int64 range.
[InlineData("-9999999999999999999")] // 19-digit numbers outside the Int64 range.
- public void TryParse_DifferentInvalidScenarios_AllReturnFalse(string input)
+ public void TryParse_DifferentInvalidScenarios_AllReturnFalse(string? input)
{
RangeHeaderValue? result;
Assert.False(RangeHeaderValue.TryParse("byte=" + input, out result));
diff --git a/src/Http/Headers/test/SetCookieHeaderValueTest.cs b/src/Http/Headers/test/SetCookieHeaderValueTest.cs
index caa09b8925ff..05c6684feef9 100644
--- a/src/Http/Headers/test/SetCookieHeaderValueTest.cs
+++ b/src/Http/Headers/test/SetCookieHeaderValueTest.cs
@@ -447,7 +447,7 @@ public void SetCookieHeaderValue_TryParseStrictList_AcceptsValidValues(IList cookies, string[] input)
+ public void SetCookieHeaderValue_ParseList_ExcludesInvalidValues(IList? cookies, string[] input)
{
var results = SetCookieHeaderValue.ParseList(input);
// ParseList always returns a list, even if empty. TryParseList may return null (via out).
@@ -456,7 +456,7 @@ public void SetCookieHeaderValue_ParseList_ExcludesInvalidValues(IList cookies, string[] input)
+ public void SetCookieHeaderValue_TryParseList_ExcludesInvalidValues(IList? cookies, string[] input)
{
bool result = SetCookieHeaderValue.TryParseList(input, out var results);
Assert.Equal(cookies, results);
@@ -467,7 +467,7 @@ public void SetCookieHeaderValue_TryParseList_ExcludesInvalidValues(IList cookies,
+ IList? cookies,
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
string[] input)
{
@@ -478,7 +478,7 @@ public void SetCookieHeaderValue_ParseStrictList_ThrowsForAnyInvalidValues(
[MemberData(nameof(ListWithInvalidSetCookieHeaderDataSet))]
public void SetCookieHeaderValue_TryParseStrictList_FailsForAnyInvalidValues(
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
- IList cookies,
+ IList? cookies,
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
string[] input)
{
diff --git a/src/Http/Headers/test/StringWithQualityHeaderValueTest.cs b/src/Http/Headers/test/StringWithQualityHeaderValueTest.cs
index 6eb58feb965f..661114afbcfa 100644
--- a/src/Http/Headers/test/StringWithQualityHeaderValueTest.cs
+++ b/src/Http/Headers/test/StringWithQualityHeaderValueTest.cs
@@ -156,7 +156,7 @@ public void Parse_SetOfValidValueStrings_ParsedCorrectly()
[InlineData("decimal_part_too_long;q=0.123456789")]
[InlineData("decimal_part_too_long;q=0.123456789 ")]
[InlineData("no_integer_part;q=.1")]
- public void Parse_SetOfInvalidValueStrings_Throws(string input)
+ public void Parse_SetOfInvalidValueStrings_Throws(string? input)
{
Assert.Throws(() => StringWithQualityHeaderValue.Parse(input));
}
diff --git a/src/Http/Http.Abstractions/test/HostStringTest.cs b/src/Http/Http.Abstractions/test/HostStringTest.cs
index 070636aaa8c7..466842824a70 100644
--- a/src/Http/Http.Abstractions/test/HostStringTest.cs
+++ b/src/Http/Http.Abstractions/test/HostStringTest.cs
@@ -27,7 +27,7 @@ public void CtorThrows_IfPortIsNotGreaterThanZero(int port)
[InlineData("1.2.3.4:5000", "1.2.3.4")]
[InlineData("[2001:db8:a0b:12f0::1]:5000", "[2001:db8:a0b:12f0::1]")]
[InlineData("本地主機:5000", "本地主機")]
- public void Domain_ExtractsHostFromValue(string sourceValue, string expectedDomain)
+ public void Domain_ExtractsHostFromValue(string? sourceValue, string expectedDomain)
{
// Arrange
var hostString = new HostString(sourceValue);
diff --git a/src/Http/Http.Abstractions/test/PathStringTests.cs b/src/Http/Http.Abstractions/test/PathStringTests.cs
index 7b1ec3782e97..30aa989ed92a 100644
--- a/src/Http/Http.Abstractions/test/PathStringTests.cs
+++ b/src/Http/Http.Abstractions/test/PathStringTests.cs
@@ -57,7 +57,7 @@ public void HashCode_CheckNullAndEmptyHaveSameHashcodes()
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
- public void AddPathString_HandlesNullAndEmptyStrings(string appString, string concatString)
+ public void AddPathString_HandlesNullAndEmptyStrings(string? appString, string? concatString)
{
// Arrange
var appPath = new PathString(appString);
@@ -77,7 +77,7 @@ public void AddPathString_HandlesNullAndEmptyStrings(string appString, string co
[InlineData("/", "/test", "/test")]
[InlineData("/myapp/", "/test/bar", "/myapp/test/bar")]
[InlineData("/myapp/", "/test/bar/", "/myapp/test/bar/")]
- public void AddPathString_HandlesLeadingAndTrailingSlashes(string appString, string concatString, string expected)
+ public void AddPathString_HandlesLeadingAndTrailingSlashes(string appString, string? concatString, string expected)
{
// Arrange
var appPath = new PathString(appString);
diff --git a/src/Http/Http.Abstractions/test/QueryStringTests.cs b/src/Http/Http.Abstractions/test/QueryStringTests.cs
index cc92e97773c9..9faea85a7bff 100644
--- a/src/Http/Http.Abstractions/test/QueryStringTests.cs
+++ b/src/Http/Http.Abstractions/test/QueryStringTests.cs
@@ -54,9 +54,9 @@ public void ToString_EncodesHash()
[InlineData("", "value", "?=value")]
[InlineData("", "", "?=")]
[InlineData("", null, "?=")]
- public void CreateNameValue_Success(string name, string value, string expected)
+ public void CreateNameValue_Success(string name, string? value, string expected)
{
- var query = QueryString.Create(name, value);
+ var query = QueryString.Create(name, value!);
Assert.Equal(expected, query.Value);
}
@@ -98,7 +98,7 @@ public void CreateFromListStringValues_Success()
[InlineData("?name1=value1", "", "?name1=value1")]
[InlineData("?name1=value1", "?", "?name1=value1")]
[InlineData("?name1=value1", "?name2=value2", "?name1=value1&name2=value2")]
- public void AddQueryString_Success(string query1, string query2, string expected)
+ public void AddQueryString_Success(string? query1, string? query2, string? expected)
{
var q1 = new QueryString(query1);
var q2 = new QueryString(query2);
@@ -120,10 +120,10 @@ public void AddQueryString_Success(string query1, string query2, string expected
[InlineData("?name1=value1", "", null, "?name1=value1&=")]
[InlineData("?name1=value1", "name2", "", "?name1=value1&name2=")]
[InlineData("?name1=value1", "name2", null, "?name1=value1&name2=")]
- public void AddNameValue_Success(string query1, string name2, string value2, string expected)
+ public void AddNameValue_Success(string query1, string name2, string? value2, string expected)
{
var q1 = new QueryString(query1);
- var q2 = q1.Add(name2, value2);
+ var q2 = q1.Add(name2, value2!);
Assert.Equal(expected, q2.Value);
}
diff --git a/src/Http/Http.Abstractions/test/UsePathBaseExtensionsTests.cs b/src/Http/Http.Abstractions/test/UsePathBaseExtensionsTests.cs
index c5c3b86f312c..21a918335ee2 100644
--- a/src/Http/Http.Abstractions/test/UsePathBaseExtensionsTests.cs
+++ b/src/Http/Http.Abstractions/test/UsePathBaseExtensionsTests.cs
@@ -13,7 +13,7 @@ public class UsePathBaseExtensionsTests
[InlineData(null)]
[InlineData("")]
[InlineData("/")]
- public void EmptyOrNullPathBase_DoNotAddMiddleware(string pathBase)
+ public void EmptyOrNullPathBase_DoNotAddMiddleware(string? pathBase)
{
// Arrange
var useCalled = false;
diff --git a/src/Http/Http.Extensions/test/HttpRequestJsonExtensionsTests.cs b/src/Http/Http.Extensions/test/HttpRequestJsonExtensionsTests.cs
index 4d63107214e9..2e65e8845201 100644
--- a/src/Http/Http.Extensions/test/HttpRequestJsonExtensionsTests.cs
+++ b/src/Http/Http.Extensions/test/HttpRequestJsonExtensionsTests.cs
@@ -23,7 +23,7 @@ public class HttpRequestJsonExtensionsTests
[InlineData("APPLICATION/JSON", true)]
[InlineData("APPLICATION/JSON; CHARSET=UTF-8", true)]
[InlineData("APPLICATION/LD+JSON", true)]
- public void HasJsonContentType(string contentType, bool hasJsonContentType)
+ public void HasJsonContentType(string? contentType, bool hasJsonContentType)
{
var request = new DefaultHttpContext().Request;
request.ContentType = contentType;
diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs b/src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs
index fcbae8ef9d27..56601f5f866c 100644
--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs
+++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs
@@ -786,6 +786,6 @@ public async Task RequestDelegatePopulatesFromOptionalFormParameterStringArray()
await endpoint.RequestDelegate(httpContext);
- Assert.Equal(["hello", "bye"], (string[])httpContext.Items["message"]);
+ Assert.Equal(["hello", "bye"], (string[])httpContext.Items["message"]);
}
}
diff --git a/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs b/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs
index 27b23fc290be..47b1569390d4 100644
--- a/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs
+++ b/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs
@@ -137,14 +137,14 @@ public void PopulateMetadata_AddsResponseTypeMetadata()
}
[Fact]
- public void ExecuteAsync_ThrowsArgumentNullException_WhenHttpContextIsNull()
+ public async Task ExecuteAsync_ThrowsArgumentNullException_WhenHttpContextIsNull()
{
// Arrange
var result = new AcceptedAtRoute