diff --git a/src/Servers/HttpSys/test/FunctionalTests/AuthenticationTests.cs b/src/Servers/HttpSys/test/FunctionalTests/AuthenticationTests.cs index 93aea43e2820..a35f8d9ee396 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/AuthenticationTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/AuthenticationTests.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class AuthenticationTests +public class AuthenticationTests : LoggedTest { private static bool AllowAnoymous = true; private static bool DenyAnoymous = false; @@ -33,7 +33,7 @@ public async Task AuthTypes_AllowAnonymous_NoChallenge(AuthenticationSchemes aut Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -51,7 +51,7 @@ public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes aut using (var server = Utilities.CreateDynamicHost(authType, DenyAnoymous, out var address, httpContext => { throw new NotImplementedException(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -73,7 +73,7 @@ public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(Authentic Assert.False(httpContext.User.Identity.IsAuthenticated); httpContext.Response.StatusCode = 401; return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -99,7 +99,7 @@ public async Task MultipleAuthTypes_AllowAnonymousButSpecify401_ChallengesAdded( Assert.False(httpContext.User.Identity.IsAuthenticated); httpContext.Response.StatusCode = 401; return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -135,7 +135,7 @@ public async Task AuthTypes_AllowAnonymousButSpecify401_Success(AuthenticationSc } requestId++; return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -156,7 +156,7 @@ public async Task AuthTypes_RequireAuth_Success(AuthenticationSchemes authType) Assert.NotNull(httpContext.User.Identity); Assert.True(httpContext.User.Identity.IsAuthenticated); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -182,7 +182,7 @@ public async Task AuthTypes_AccessUserInOnCompleted_Success() return Task.CompletedTask; }); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -208,7 +208,7 @@ public async Task AuthTypes_AuthenticateWithNoUser_NoResults(AuthenticationSchem var authResults = await httpContext.AuthenticateAsync(HttpSysDefaults.AuthenticationScheme); Assert.False(authResults.Succeeded); Assert.True(authResults.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -231,7 +231,7 @@ public async Task AuthTypes_AuthenticateWithUser_OneResult(AuthenticationSchemes Assert.True(httpContext.User.Identity.IsAuthenticated); var authResults = await httpContext.AuthenticateAsync(HttpSysDefaults.AuthenticationScheme); Assert.True(authResults.Succeeded); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -253,7 +253,7 @@ public async Task AuthTypes_ChallengeWithoutAuthTypes_AllChallengesSent(Authenti Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); return httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -276,7 +276,7 @@ public async Task AuthTypes_ChallengeWithAllAuthTypes_AllChallengesSent(Authenti Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); await httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -294,7 +294,7 @@ public async Task AuthTypes_OneChallengeSent() Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); return httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -320,7 +320,7 @@ public async Task AuthTypes_ChallengeWillAskForAllEnabledSchemes(AuthenticationS Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); return httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -338,7 +338,7 @@ public async Task AuthTypes_Forbid_Forbidden() Assert.NotNull(httpContext.User.Identity); Assert.False(httpContext.User.Identity.IsAuthenticated); return httpContext.ForbidAsync(HttpSysDefaults.AuthenticationScheme); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); @@ -359,7 +359,7 @@ public async Task AuthTypes_UnathorizedAuthenticatedAuthType_Unauthorized(Authen Assert.NotNull(httpContext.User.Identity); Assert.True(httpContext.User.Identity.IsAuthenticated); return httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme, null); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -393,7 +393,7 @@ public async Task AuthTypes_DisableAutomaticAuthentication(AuthenticationSchemes Assert.NotNull(authenticateResult.Principal); Assert.NotNull(authenticateResult.Principal.Identity); Assert.True(authenticateResult.Principal.Identity.IsAuthenticated); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, useDefaultCredentials: true); Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/src/Servers/HttpSys/test/FunctionalTests/DelegateTests.cs b/src/Servers/HttpSys/test/FunctionalTests/DelegateTests.cs index 420a1f0e1157..9b26dbe5ad7d 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/DelegateTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/DelegateTests.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests; -public class DelegateTests +public class DelegateTests : LoggedTest { private static readonly string _expectedResponseString = "Hello from delegatee"; @@ -44,7 +44,7 @@ public async Task DelegateRequestTest() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; @@ -53,7 +53,7 @@ public async Task DelegateRequestTest() var delegateFeature = httpContext.Features.Get(); delegateFeature.DelegateRequest(destination); return Task.CompletedTask; - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -76,7 +76,7 @@ public async Task DelegateAfterWriteToResponseBodyShouldThrowTest() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; @@ -86,7 +86,7 @@ public async Task DelegateAfterWriteToResponseBodyShouldThrowTest() var delegateFeature = httpContext.Features.Get(); Assert.False(delegateFeature.CanDelegate); Assert.Throws(() => delegateFeature.DelegateRequest(destination)); - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -108,7 +108,7 @@ public async Task WriteToBodyAfterDelegateShouldNoOp() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; @@ -119,7 +119,7 @@ public async Task WriteToBodyAfterDelegateShouldNoOp() Assert.False(delegateFeature.CanDelegate); httpContext.Response.WriteAsync(_expectedResponseString); return Task.CompletedTask; - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -142,7 +142,7 @@ public async Task DelegateAfterRequestBodyReadShouldThrow() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; @@ -152,7 +152,7 @@ public async Task DelegateAfterRequestBodyReadShouldThrow() await httpContext.Request.Body.CopyToAsync(memoryStream); var delegateFeature = httpContext.Features.Get(); Assert.Throws(() => delegateFeature.DelegateRequest(destination)); - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -173,7 +173,7 @@ public async Task DelegationFeaturesAreNull() var delegateFeature = httpContext.Features.Get(); Assert.Null(delegateFeature); return Task.CompletedTask; - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); Assert.Null(delegationProperty); @@ -193,7 +193,7 @@ public async Task UpdateDelegationRuleTest() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; @@ -202,7 +202,7 @@ public async Task UpdateDelegationRuleTest() var delegateFeature = httpContext.Features.Get(); delegateFeature.DelegateRequest(destination); return Task.CompletedTask; - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -227,7 +227,7 @@ public async Task DelegateAfterReceiverRestart() options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); DelegationRule destination = default; using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext => @@ -235,7 +235,7 @@ public async Task DelegateAfterReceiverRestart() var delegateFeature = httpContext.Features.Get(); delegateFeature.DelegateRequest(destination); return Task.CompletedTask; - }); + }, LoggerFactory); var delegationProperty = delegator.Features.Get(); destination = delegationProperty.CreateDelegationRule(queueName, receiverAddress); @@ -257,7 +257,7 @@ public async Task DelegateAfterReceiverRestart() options.RequestQueueMode = RequestQueueMode.CreateOrAttach; options.UrlPrefixes.Clear(); options.UrlPrefixes.Add(receiverAddress); - }); + }, LoggerFactory); responseString = await SendRequestAsync(delegatorAddress); Assert.Equal(_expectedResponseString, responseString); diff --git a/src/Servers/HttpSys/test/FunctionalTests/Http2Tests.cs b/src/Servers/HttpSys/test/FunctionalTests/Http2Tests.cs index 0a6a1c71d12f..5c094ca6a543 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/Http2Tests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/Http2Tests.cs @@ -37,7 +37,7 @@ public async Task EmptyResponse_200() Assert.False(httpContext.Request.CanHaveBody()); // Default 200 return Task.CompletedTask; - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -70,7 +70,7 @@ public async Task RequestWithoutData_LengthRequired_Rejected(string method) using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { throw new NotImplementedException(); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -120,7 +120,7 @@ public async Task RequestWithoutData_Success(string method) Assert.Null(httpContext.Request.ContentLength); Assert.False(httpContext.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)); return Task.CompletedTask; - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -170,7 +170,7 @@ public async Task RequestWithDataAndContentLength_Success(string method) Assert.Equal(11, httpContext.Request.ContentLength); Assert.False(httpContext.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)); return httpContext.Request.Body.CopyToAsync(httpContext.Response.Body); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -235,7 +235,7 @@ public async Task RequestWithDataAndNoContentLength_Success(string method) // The client didn't send this header, Http.Sys added it for back compat with HTTP/1.1. Assert.Equal("chunked", httpContext.Request.Headers.TransferEncoding); return httpContext.Request.Body.CopyToAsync(httpContext.Response.Body); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -287,7 +287,7 @@ public async Task ResponseWithData_Success() using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { return httpContext.Response.WriteAsync("Hello World"); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -323,7 +323,7 @@ public async Task ConnectionClose_NoOSSupport_NoGoAway() { httpContext.Response.Headers.Connection = "close"; return Task.FromResult(0); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -367,7 +367,7 @@ public async Task ConnectionHeaderClose_OSSupport_SendsGoAway() { httpContext.Response.Headers.Connection = "close"; return Task.FromResult(0); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -406,7 +406,7 @@ public async Task ConnectionRequestClose_OSSupport_SendsGoAway() { httpContext.Connection.RequestClose(); return Task.FromResult(0); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -445,7 +445,7 @@ public async Task ConnectionClose_AdditionalRequests_ReceivesSecondGoAway() { httpContext.Response.Headers.Connection = "close"; return Task.FromResult(0); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -518,7 +518,7 @@ public async Task AppException_BeforeResponseHeaders_500() using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { throw new Exception("Application exception"); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -551,7 +551,7 @@ public async Task AppException_AfterHeaders_PriorOSVersions_ResetCancel() { await httpContext.Response.Body.FlushAsync(); throw new Exception("Application exception"); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -583,7 +583,7 @@ public async Task AppException_AfterHeaders_ResetInternalError() { await httpContext.Response.Body.FlushAsync(); throw new Exception("Application exception"); - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -637,7 +637,7 @@ public async Task Reset_PriorOSVersions_NotSupported() var feature = httpContext.Features.Get(); Assert.Null(feature); return httpContext.Response.WriteAsync("Hello World"); - }); + }, LoggerFactory); var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -709,7 +709,7 @@ public async Task Reset_AfterResponseHeaders_Resets() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -756,7 +756,7 @@ public async Task Reset_DurringResponseBody_Resets() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -808,7 +808,7 @@ public async Task Reset_AfterCompleteAsync_NoReset() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -862,7 +862,7 @@ public async Task Reset_BeforeRequestBody_Resets() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -910,7 +910,7 @@ public async Task Reset_DurringRequestBody_Resets() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => @@ -960,7 +960,7 @@ public async Task Reset_CompleteAsyncDurringRequestBody_Resets() { appResult.SetException(ex); } - }); + }, LoggerFactory); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => diff --git a/src/Servers/HttpSys/test/FunctionalTests/Http3Tests.cs b/src/Servers/HttpSys/test/FunctionalTests/Http3Tests.cs index e97a59ecdc72..ad5ce389bb01 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/Http3Tests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/Http3Tests.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; [MsQuicSupported] // Required by HttpClient [HttpSysHttp3Supported] -public class Http3Tests +public class Http3Tests : LoggedTest { [ConditionalFact] public async Task Http3_Direct() @@ -34,7 +34,7 @@ public async Task Http3_Direct() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -62,7 +62,7 @@ public async Task Http3_AltSvcHeader_UpgradeFromHttp1() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); altsvc = $@"h3="":{new Uri(address).Port}"""; var handler = new HttpClientHandler(); @@ -102,7 +102,7 @@ public async Task Http3_AltSvcHeader_UpgradeFromHttp2() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); altsvc = $@"h3="":{new Uri(address).Port}"""; var handler = new HttpClientHandler(); @@ -138,7 +138,7 @@ public async Task Http3_ResponseTrailers() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -166,7 +166,7 @@ public async Task Http3_ResetBeforeHeaders() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -196,7 +196,7 @@ public async Task Http3_ResetAfterHeaders() { await httpContext.Response.WriteAsync(ex.ToString()); } - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -221,7 +221,7 @@ public async Task Http3_AppExceptionAfterHeaders_InternalError() await httpContext.Response.Body.FlushAsync(); await headersReceived.Task.DefaultTimeout(); throw new Exception("App Exception"); - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; @@ -245,7 +245,7 @@ public async Task Http3_Abort_Cancel() { httpContext.Abort(); return Task.CompletedTask; - }); + }, LoggerFactory); var handler = new HttpClientHandler(); // Needed on CI, the IIS Express cert we use isn't trusted there. handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; diff --git a/src/Servers/HttpSys/test/FunctionalTests/HttpsTests.cs b/src/Servers/HttpSys/test/FunctionalTests/HttpsTests.cs index ea6a62c5f112..0ccb71964b74 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/HttpsTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/HttpsTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class HttpsTests +public class HttpsTests : LoggedTest { private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate("eku.client.pfx"); @@ -30,7 +30,7 @@ public async Task Https_200OK_Success() using (Utilities.CreateDynamicHttpsServer(out var address, httpContext => { return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -45,7 +45,7 @@ public async Task Https_SendHelloWorld_Success() byte[] body = Encoding.UTF8.GetBytes("Hello World"); httpContext.Response.ContentLength = body.Length; return httpContext.Response.Body.WriteAsync(body, 0, body.Length); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal("Hello World", response); @@ -62,7 +62,7 @@ public async Task Https_EchoHelloWorld_Success() var body = Encoding.UTF8.GetBytes("Hello World"); httpContext.Response.ContentLength = body.Length; await httpContext.Response.Body.WriteAsync(body, 0, body.Length); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -143,7 +143,7 @@ public async Task Https_SkipsITlsHandshakeFeatureOnWin7() { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -159,7 +159,7 @@ public async Task Https_SetsITlsHandshakeFeature() var tlsFeature = httpContext.Features.Get(); Assert.NotNull(tlsFeature); return httpContext.Response.WriteAsJsonAsync(tlsFeature); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); var result = System.Text.Json.JsonDocument.Parse(response).RootElement; @@ -227,7 +227,7 @@ public async Task Https_ITlsHandshakeFeature_MatchesIHttpSysExtensionInfoFeature { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -257,7 +257,7 @@ public async Task Https_SetsIHttpSysRequestTimingFeature() { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); diff --git a/src/Servers/HttpSys/test/FunctionalTests/MessagePumpTests.cs b/src/Servers/HttpSys/test/FunctionalTests/MessagePumpTests.cs index bcd05d912a79..cff11e60e9c3 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/MessagePumpTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/MessagePumpTests.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class MessagePumpTests +public class MessagePumpTests : LoggedTest { [ConditionalFact] public void OverridingDirectConfigurationWithIServerAddressesFeatureSucceeds() @@ -21,7 +21,7 @@ public void OverridingDirectConfigurationWithIServerAddressesFeatureSucceeds() var serverAddress = "http://localhost:11001/"; var overrideAddress = "http://localhost:11002/"; - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { var serverAddressesFeature = server.Features.Get(); serverAddressesFeature.Addresses.Add(overrideAddress); @@ -43,7 +43,7 @@ public void DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfPref { var serverAddress = "http://localhost:11002/"; - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { var serverAddressesFeature = server.Features.Get(); serverAddressesFeature.Addresses.Add(overrideAddress); @@ -60,7 +60,7 @@ public void DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfAddr { var serverAddress = "http://localhost:11002/"; - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { var serverAddressesFeature = server.Features.Get(); serverAddressesFeature.PreferHostingUrls = true; @@ -81,7 +81,7 @@ public void OverridingIServerAddressesFeatureWithDirectConfiguration_WarnsOnStar { var overrideAddress = "http://localhost:11002/"; - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { var serverAddressesFeature = server.Features.Get(); serverAddressesFeature.Addresses.Add(serverAddress); @@ -98,7 +98,7 @@ public void UseIServerAddressesFeature_WhenNoDirectConfiguration() { var serverAddress = "http://localhost:11001/"; - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { var serverAddressesFeature = server.Features.Get(); serverAddressesFeature.Addresses.Add(serverAddress); @@ -112,7 +112,7 @@ public void UseIServerAddressesFeature_WhenNoDirectConfiguration() [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/28993")] public void UseDefaultAddress_WhenNoServerAddressAndNoDirectConfiguration() { - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { server.StartAsync(new DummyApplication(), CancellationToken.None).Wait(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/OpaqueUpgradeTests.cs b/src/Servers/HttpSys/test/FunctionalTests/OpaqueUpgradeTests.cs index 79041a7d241a..b81e3168cedd 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/OpaqueUpgradeTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/OpaqueUpgradeTests.cs @@ -11,11 +11,12 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys; -public class OpaqueUpgradeTests +public class OpaqueUpgradeTests : LoggedTest { [ConditionalFact] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)] @@ -33,7 +34,7 @@ public async Task OpaqueUpgrade_DownLevel_FeatureIsAbsent() return httpContext.Response.WriteAsync(ex.ToString()); } return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -61,7 +62,7 @@ public async Task OpaqueUpgrade_SupportKeys_Present() return httpContext.Response.WriteAsync(ex.ToString()); } return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -92,7 +93,7 @@ public async Task OpaqueUpgrade_AfterHeadersSent_Throws() { upgradeThrew = true; } - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -114,7 +115,7 @@ public async Task OpaqueUpgrade_GetUpgrade_Success() Assert.True(opaqueFeature.IsUpgradableRequest); await opaqueFeature.UpgradeAsync(); upgraded.SetResult(true); - })) + }, LoggerFactory)) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { @@ -145,7 +146,7 @@ public async Task OpaqueUpgrade_GetUpgrade_NotAffectedByMaxRequestBodyLimit() Assert.Throws(() => feature.MaxRequestBodySize = 12); Assert.Equal(15, await stream.ReadAsync(new byte[15], 0, 15)); upgraded.SetResult(true); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { @@ -174,7 +175,7 @@ public async Task OpaqueUpgrade_WithOnStarting_CallbackCalled() Assert.True(opaqueFeature.IsUpgradableRequest); await opaqueFeature.UpgradeAsync(); upgraded.SetResult(true); - })) + }, LoggerFactory)) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { @@ -230,7 +231,7 @@ public async Task OpaqueUpgrade_VariousMethodsUpgradeSendAndReceive_Success(stri { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { using (Stream stream = await SendOpaqueRequestAsync(method, address, extraHeader)) { @@ -266,7 +267,7 @@ public async Task OpaqueUpgrade_InvalidMethodUpgrade_Disconnected(string method, { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { var ex = await Assert.ThrowsAsync(async () => await SendOpaqueRequestAsync(method, address, extraHeader)); Assert.Equal("The response status code was incorrect: HTTP/1.1 200 OK", ex.Message); @@ -289,7 +290,7 @@ public async Task OpaqueUpgrade_PostWithBodyAndUpgradeHeaders_Accepted() { await httpContext.Response.WriteAsync(ex.ToString()); } - })) + }, LoggerFactory)) { using var client = new HttpClient(); @@ -321,7 +322,7 @@ public async Task OpaqueUpgrade_Http10_ThrowsIfUpgraded() throw; } upgrade.TrySetResult(); - })) + }, LoggerFactory)) { // Connect with a socket Uri uri = new Uri(address); diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs index cea69fb111b3..e90ac3996d98 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyLimitTests.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class RequestBodyLimitTests +public class RequestBodyLimitTests : LoggedTest { [ConditionalFact] public async Task ContentLengthEqualsLimit_ReadSync_Success() @@ -32,7 +32,7 @@ public async Task ContentLengthEqualsLimit_ReadSync_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.Write(input, 0, read); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -54,7 +54,7 @@ public async Task ContentLengthEqualsLimit_ReadAsync_Success() int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -76,7 +76,7 @@ public async Task ContentLengthEqualsLimit_ReadBeginEnd_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null)); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -99,7 +99,7 @@ public async Task ChunkedEqualsLimit_ReadSync_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.Write(input, 0, read); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal("Hello World", response); @@ -121,7 +121,7 @@ public async Task ChunkedEqualsLimit_ReadAsync_Success() int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal("Hello World", response); @@ -143,7 +143,7 @@ public async Task ChunkedEqualsLimit_ReadBeginEnd_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null)); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal("Hello World", response); @@ -169,7 +169,7 @@ public async Task ContentLengthExceedsLimit_ReadSync_ThrowsImmediately() Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal(string.Empty, response); @@ -194,7 +194,7 @@ public async Task ContentLengthExceedsLimit_ReadAsync_ThrowsImmediately() Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal(string.Empty, response); @@ -219,7 +219,7 @@ public async Task ContentLengthExceedsLimit_ReadBeginEnd_ThrowsImmediately() Assert.Equal("The request's Content-Length 11 is larger than the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World"); Assert.Equal(string.Empty, response); @@ -245,7 +245,7 @@ public async Task ChunkedExceedsLimit_ReadSync_ThrowsAtLimit() Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal(string.Empty, response); @@ -269,7 +269,7 @@ public async Task ChunkedExceedsLimit_ReadAsync_ThrowsAtLimit() ex = await Assert.ThrowsAsync(() => httpContext.Request.Body.ReadAsync(input, 0, input.Length)); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal(string.Empty, response); @@ -295,7 +295,7 @@ public async Task ChunkedExceedsLimit_ReadBeginEnd_ThrowsAtLimit() Assert.Equal("The total number of bytes read 11 has exceeded the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World", chunked: true); Assert.Equal(string.Empty, response); @@ -322,7 +322,7 @@ public async Task Chunked_ReadSyncPartialBodyUnderLimit_ThrowsAfterLimit() Assert.Equal("The total number of bytes read 20 has exceeded the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); return Task.FromResult(0); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { string response = await SendRequestAsync(address, content, chunked: true); Assert.Equal(string.Empty, response); @@ -347,7 +347,7 @@ public async Task Chunked_ReadAsyncPartialBodyUnderLimit_ThrowsAfterLimit() var ex = await Assert.ThrowsAsync(() => httpContext.Request.Body.ReadAsync(input, 0, input.Length)); Assert.Equal("The total number of bytes read 20 has exceeded the request body size limit 10.", ex.Message); Assert.Equal(StatusCodes.Status413PayloadTooLarge, ex.StatusCode); - }, options => options.MaxRequestBodySize = 10)) + }, options => options.MaxRequestBodySize = 10, LoggerFactory)) { string response = await SendRequestAsync(address, content, chunked: true); Assert.Equal(string.Empty, response); @@ -371,7 +371,7 @@ public async Task AdjustLimitPerRequest_ContentLength_ReadAsync_Success() Assert.True(feature.IsReadOnly); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World!"); Assert.Equal("Hello World!", response); @@ -395,7 +395,7 @@ public async Task AdjustLimitPerRequest_Chunked_ReadAsync_Success() Assert.True(feature.IsReadOnly); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - }, options => options.MaxRequestBodySize = 11)) + }, options => options.MaxRequestBodySize = 11, LoggerFactory)) { var response = await SendRequestAsync(address, "Hello World!", chunked: true); Assert.Equal("Hello World!", response); diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs index 6ba1a58424e1..a598706407b5 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestBodyTests.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class RequestBodyTests +public class RequestBodyTests : LoggedTest { [ConditionalFact] public async Task RequestBody_ReadSync_Success() @@ -33,7 +33,7 @@ public async Task RequestBody_ReadSync_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.Write(input, 0, read); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -55,7 +55,7 @@ public async Task RequestBody_Read0ByteSync_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.Write(input, 0, read); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -73,7 +73,7 @@ public async Task RequestBody_ReadAsync_Success() int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -93,7 +93,7 @@ public async Task RequestBody_Read0ByteAsync_Success() read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -111,7 +111,7 @@ public async Task RequestBody_ReadBeginEnd_Success() httpContext.Response.ContentLength = read; httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(input, 0, read, null, null)); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -133,7 +133,7 @@ public async Task RequestBody_InvalidBuffer_ArgumentException() Assert.Throws("count", () => httpContext.Request.Body.Read(input, 1, input.Length)); Assert.Throws("count", () => httpContext.Request.Body.Read(input, 0, input.Length + 1)); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal(string.Empty, response); @@ -155,7 +155,7 @@ public async Task RequestBody_ReadSyncPartialBody_Success() read = httpContext.Request.Body.Read(input, 0, input.Length); Assert.Equal(5, read); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, content); Assert.Equal(string.Empty, response); @@ -175,7 +175,7 @@ public async Task RequestBody_ReadAsyncPartialBody_Success() content.Block.Release(); read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); Assert.Equal(5, read); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, content); Assert.Equal(string.Empty, response); @@ -195,7 +195,7 @@ public async Task RequestBody_PostWithImidateBody_Success() Assert.Equal(0, read); httpContext.Response.ContentLength = 10; await httpContext.Response.Body.WriteAsync(input, 0, 10); - })) + }, LoggerFactory)) { string response = await SendSocketRequestAsync(address); string[] lines = response.Split('\r', '\n'); @@ -229,7 +229,7 @@ public async Task RequestBody_ChangeContentLength_Success() int read = await httpContext.Request.Body.ReadAsync(input, 0, input.Length); httpContext.Response.ContentLength = read; await httpContext.Response.Body.WriteAsync(input, 0, read); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -284,7 +284,7 @@ static void CheckHeadersCount(string headerName, int expectedCount, HttpRequest httpContext.Response.StatusCode = 200; requestWasProcessed = true; return Task.CompletedTask; - })) + }, LoggerFactory)) { await SendRequestAsync(address, "Hello World"); Assert.True(requestWasProcessed); diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestHeaderTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestHeaderTests.cs index 2d47f9bd78b7..081a03688274 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestHeaderTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestHeaderTests.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class RequestHeaderTests +public class RequestHeaderTests : LoggedTest { [ConditionalFact] public async Task RequestHeaders_ClientSendsDefaultHeaders_Success() @@ -28,7 +28,7 @@ public async Task RequestHeaders_ClientSendsDefaultHeaders_Success() Assert.False(StringValues.IsNullOrEmpty(requestHeaders["Host"])); Assert.True(StringValues.IsNullOrEmpty(requestHeaders["Accept"])); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -50,7 +50,7 @@ public async Task RequestHeaders_ClientSendsCustomHeaders_Success() Assert.Single(requestHeaders["Spacer-Header"]); Assert.Equal("spacervalue, spacervalue", requestHeaders["Spacer-Header"]); return Task.FromResult(0); - }); + }, LoggerFactory); var customValues = new string[] { "custom1, and custom2", "custom3" }; @@ -92,7 +92,7 @@ public async Task RequestHeaders_ServerAddsCustomHeaders_Success() Assert.True(requestHeaders.Contains(header)); return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -111,7 +111,7 @@ public async Task RequestHeaders_ClientSendTransferEncodingHeaders() Assert.Equal("chunked", requestHeaders.TransferEncoding); Assert.True(request.HasEntityBody); return Task.FromResult(0); - })) + }, LoggerFactory)) { var headerDictionary = new HeaderDictionary(new Dictionary { { "Transfer-Encoding", "chunked" } @@ -134,7 +134,7 @@ public async Task RequestHeaders_ClientSendTransferEncodingHeadersWithMultipleVa Assert.Equal("gzip, chunked", requestHeaders.TransferEncoding); Assert.True(request.HasEntityBody); return Task.FromResult(0); - })) + }, LoggerFactory)) { var headerDictionary = new HeaderDictionary(new Dictionary { { "Transfer-Encoding", new string[] { "gzip", "chunked" } } @@ -165,7 +165,7 @@ public async Task RequestHeaders_ClientSendTransferEncodingAndContentLength_Cont Assert.Single(requestHeaders["X-Content-Length"]); Assert.Equal("1", requestHeaders["X-Content-Length"]); return Task.FromResult(0); - })) + }, LoggerFactory)) { var headerDictionary = new HeaderDictionary(new Dictionary { { "Transfer-Encoding", new string[] { "gzip", "chunked" } }, @@ -191,7 +191,7 @@ public async Task RequestHeaders_AllKnownHeadersKeys_Received() Assert.Contains(requestHeaders[customHeader].First(), requestHeaders.Keys); Assert.Contains(HeaderNames.Host, requestHeaders.Keys); return Task.FromResult(0); - }); + }, LoggerFactory); foreach ((HttpSysRequestHeader Key, string Value) testRow in HeaderTestData()) { @@ -219,7 +219,7 @@ public async Task RequestHeaders_AllUnknownHeadersKeys_Received() Assert.Contains("X-UnknownHeader-2", requestHeaders.Keys); Assert.Contains(HeaderNames.Host, requestHeaders.Keys); return Task.FromResult(0); - }); + }, LoggerFactory); var headerDictionary = new Dictionary { diff --git a/src/Servers/HttpSys/test/FunctionalTests/RequestTests.cs b/src/Servers/HttpSys/test/FunctionalTests/RequestTests.cs index defbee588b18..51eed9b46948 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/RequestTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/RequestTests.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class RequestTests +public class RequestTests : LoggedTest { [ConditionalFact] public async Task Request_SimpleGet_ExpectedFieldsSet() @@ -66,7 +66,7 @@ public async Task Request_SimpleGet_ExpectedFieldsSet() httpContext.Response.Body.Write(body, 0, body.Length); } return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(root + "/basepath/SomePath?SomeQuery"); Assert.Equal(string.Empty, response); @@ -130,7 +130,7 @@ public async Task Request_FieldsCanBeSet_Set() httpContext.Response.Body.Write(body, 0, body.Length); } return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(root + "/basepath/SomePath?SomeQuery"); Assert.Equal(string.Empty, response); @@ -193,7 +193,7 @@ public async Task Request_FieldsCanBeSetToNull_Set() httpContext.Response.Body.Write(body, 0, body.Length); } return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(root + "/basepath/SomePath?SomeQuery"); Assert.Equal(string.Empty, response); @@ -237,7 +237,7 @@ public async Task Request_PathSplitting(string pathBase, string requestPath, str httpContext.Response.Body.Write(body, 0, body.Length); } return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(root + requestPath); Assert.Equal(string.Empty, response); @@ -254,7 +254,7 @@ public async Task Request_DoubleEscapingAllowed() Assert.Equal("/%2F", requestInfo.Path); Assert.Equal("/%252F", requestInfo.RawTarget); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendSocketRequestAsync(root, "/%252F"); var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " @@ -271,7 +271,7 @@ public async Task Request_FullUriInRequestLine_ParsesPath() Assert.Equal("/", requestInfo.Path); Assert.Equal("", requestInfo.PathBase); return Task.CompletedTask; - })) + }, LoggerFactory)) { // Send a HTTP request with the request line: // GET http://localhost:5001 HTTP/1.1 @@ -287,7 +287,7 @@ public async Task Request_FullUriInRequestLineWithSlashesInQuery_BlockedByHttpSy using (var server = Utilities.CreateHttpServerReturnRoot("/", out var root, httpContext => { return Task.CompletedTask; - })) + }, LoggerFactory)) { // Send a HTTP request with the request line: // GET http://localhost:5001?query=value/1/2 HTTP/1.1 @@ -360,7 +360,7 @@ public async Task Request_UrlUnescaping() // '/' %2F is an exception, un-escaping it would change the structure of the path Assert.Equal("/ !\"#$%&'()*+,-.%2F0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", requestInfo.Path); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendSocketRequestAsync(root, rawPath); var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " @@ -379,7 +379,7 @@ public async Task Request_WithDoubleSlashes_LeftAlone() Assert.Equal(rawPath, requestInfo.RawTarget); Assert.Equal(rawPath, requestInfo.Path); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendSocketRequestAsync(root, rawPath); var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " @@ -404,7 +404,7 @@ public async Task Request_WithNavigation_Removed(string basePath, string input, Assert.Equal(expectedPathBase, requestInfo.PathBase); Assert.Equal(expectedPath, requestInfo.Path); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendSocketRequestAsync(root, input); var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " @@ -424,7 +424,7 @@ public async Task Request_WithEscapedNavigation_Removed(string input, string exp Assert.Equal(input, requestInfo.RawTarget); Assert.Equal(expected, requestInfo.Path); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendSocketRequestAsync(root, input); var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " @@ -439,7 +439,7 @@ public async Task Request_ControlCharacters_400() using (var server = Utilities.CreateHttpServerReturnRoot("/", out root, httpContext => { throw new NotImplementedException(); - })) + }, LoggerFactory)) { for (var i = 0; i < 32; i++) { @@ -461,7 +461,7 @@ public async Task Request_EscapedControlCharacters_400() using (var server = Utilities.CreateHttpServerReturnRoot("/", out root, httpContext => { throw new NotImplementedException(); - })) + }, LoggerFactory)) { for (var i = 0; i < 32; i++) { @@ -493,7 +493,7 @@ public async Task RequestAborted_AfterAccessingProperty_Notified() // Don't exit until it fires or else it could be disposed. await result.Task.DefaultTimeout(); - }); + }, LoggerFactory); // Send a request and then abort. @@ -540,7 +540,7 @@ public async Task RequestAbortedDurringRead_BeforeAccessingProperty_TokenAlready } result.SetResult(httpContext.RequestAborted.IsCancellationRequested); - }); + }, LoggerFactory); // Send a request and then abort. @@ -570,10 +570,10 @@ public async Task RequestAbortedDurringRead_BeforeAccessingProperty_TokenAlready private IServer CreateServer(out string root, RequestDelegate app) { // TODO: We're just doing this to get a dynamic port. This can be removed later when we add support for hot-adding prefixes. - var dynamicServer = Utilities.CreateHttpServerReturnRoot("/", out root, app); + var dynamicServer = Utilities.CreateHttpServerReturnRoot("/", out root, app, LoggerFactory); dynamicServer.Dispose(); var rootUri = new Uri(root); - var server = Utilities.CreatePump(); + var server = Utilities.CreatePump(LoggerFactory); foreach (string path in new[] { "/", "/11", "/2/3", "/2", "/11/2" }) { diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseBodyTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseBodyTests.cs index 43fe220588d1..0f442b7fd36d 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseBodyTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseBodyTests.cs @@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class ResponseBodyTests +public class ResponseBodyTests : LoggedTest { [ConditionalFact] public async Task ResponseBody_StartAsync_LocksHeadersAndTriggersOnStarting() @@ -27,7 +27,7 @@ public async Task ResponseBody_StartAsync_LocksHeadersAndTriggersOnStarting() Assert.True(httpContext.Response.Headers.IsReadOnly); await startingTcs.Task.DefaultTimeout(); await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -56,7 +56,7 @@ public async Task ResponseBody_CompleteAsync_TriggersOnStartingAndLocksHeaders() Assert.True(httpContext.Response.Headers.IsReadOnly); await startingTcs.Task.DefaultTimeout(); await responseReceived.Task.DefaultTimeout(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -77,7 +77,7 @@ public async Task ResponseBody_CompleteAsync_FlushesThePipe() writer.Advance(memory.Length); await httpContext.Response.CompleteAsync(); await responseReceived.Task.DefaultTimeout(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -96,7 +96,7 @@ public async Task ResponseBody_PipeAdapter_AutomaticallyFlushed() var memory = writer.GetMemory(); writer.Advance(memory.Length); return Task.CompletedTask; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -114,7 +114,7 @@ public async Task ResponseBody_WriteNoHeaders_SetsChunked() httpContext.Features.Get().AllowSynchronousIO = true; httpContext.Response.Body.Write(new byte[10], 0, 10); return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -146,7 +146,7 @@ public async Task ResponseBody_WriteNoHeaders_SetsChunked_LargeBody(bool enableK httpContext.Response.Body.Write(new byte[WriteSize], 0, WriteSize); } await httpContext.Response.Body.WriteAsync(new byte[WriteSize], 0, WriteSize); - })) + }, loggerFactory: LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -171,7 +171,7 @@ public async Task ResponseBody_WriteNoHeadersAndFlush_DefaultsToChunked() httpContext.Response.Body.Write(new byte[10], 0, 10); await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); await httpContext.Response.Body.FlushAsync(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -193,7 +193,7 @@ public async Task ResponseBody_WriteChunked_ManuallyChunked() Stream stream = httpContext.Response.Body; var responseBytes = Encoding.ASCII.GetBytes("10\r\nManually Chunked\r\n0\r\n\r\n"); await stream.WriteAsync(responseBytes, 0, responseBytes.Length); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -217,7 +217,7 @@ public async Task ResponseBody_WriteContentLength_PassedThrough() stream.EndWrite(stream.BeginWrite(new byte[10], 0, 10, null, null)); stream.Write(new byte[10], 0, 10); await stream.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -238,7 +238,7 @@ public async Task ResponseBody_WriteContentLengthNoneWritten_Throws() { httpContext.Response.Headers["Content-lenGth"] = " 20 "; return Task.FromResult(0); - })) + }, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); } @@ -252,7 +252,7 @@ public async Task ResponseBody_WriteContentLengthNotEnoughWritten_Throws() { httpContext.Response.Headers["Content-lenGth"] = " 20 "; return httpContext.Response.Body.WriteAsync(new byte[5], 0, 5); - })) + }, LoggerFactory)) { await Assert.ThrowsAsync(async () => await SendRequestAsync(address)); } @@ -270,7 +270,7 @@ public async Task ResponseBody_WriteContentLengthTooMuchWritten_Throws() await Assert.ThrowsAsync(() => httpContext.Response.Body.WriteAsync(new byte[6], 0, 6)); completed = true; - })) + }, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); Assert.True(completed); @@ -296,7 +296,7 @@ public async Task ResponseBody_WriteContentLengthExtraWritten_Throws() requestThrew.SetResult(true); } return Task.FromResult(0); - })) + }, LoggerFactory)) { // The full response is received. HttpResponseMessage response = await SendRequestAsync(address); @@ -328,7 +328,7 @@ public async Task ResponseBody_Write_TriggersOnStarting() }, httpContext); httpContext.Response.Body.Write(new byte[10], 0, 10); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -356,7 +356,7 @@ public async Task ResponseBody_BeginWrite_TriggersOnStarting() }, httpContext); httpContext.Response.Body.EndWrite(httpContext.Response.Body.BeginWrite(new byte[10], 0, 10, null, null)); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -383,7 +383,7 @@ public async Task ResponseBody_WriteAsync_TriggersOnStarting() return Task.FromResult(0); }, httpContext); return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -424,7 +424,7 @@ public async Task ResponseBody_ZeroLengthTrailingWrite_Success(bool setContentLe // the payload would not be observed completion.TrySetException(ex); } - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); var payload = await response.Content.ReadAsByteArrayAsync(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseCachingTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseCachingTests.cs index 153820b51a04..e0947d2099e6 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseCachingTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseCachingTests.cs @@ -10,11 +10,12 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests; -public class ResponseCachingTests +public class ResponseCachingTests : LoggedTest { private readonly string _absoluteFilePath; private readonly long _fileLength; @@ -36,7 +37,7 @@ public async Task Caching_NoCacheControl_NotCached() httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture); httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -56,7 +57,7 @@ public async Task Caching_JustPublic_NotCached() httpContext.Response.Headers["Cache-Control"] = "public"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -77,7 +78,7 @@ public async Task Caching_WithoutContentType_NotCached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -98,7 +99,7 @@ public async Task Caching_304_NotCached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address, StatusCodes.Status304NotModified)); @@ -123,7 +124,7 @@ public async Task Caching_WithoutContentType_Cached_OnWin7AndWin2008R2() httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -143,7 +144,7 @@ public async Task Caching_MaxAge_Cached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -163,7 +164,7 @@ public async Task Caching_MaxAgeHuge_Cached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=" + int.MaxValue.ToString(CultureInfo.InvariantCulture); httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -183,7 +184,7 @@ public async Task Caching_SMaxAge_Cached() httpContext.Response.Headers["Cache-Control"] = "public, s-maxage=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -203,7 +204,7 @@ public async Task Caching_SMaxAgeAndMaxAge_SMaxAgePreferredCached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=0, s-maxage=10"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -224,7 +225,7 @@ public async Task Caching_Expires_Cached() httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r"); httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -248,7 +249,7 @@ public async Task Caching_DisallowedResponseHeaders_NotCached(string headerName) httpContext.Response.Headers[headerName] = "headerValue"; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -271,7 +272,7 @@ public async Task Caching_InvalidExpires_NotCached(string expiresValue) httpContext.Response.Headers["Expires"] = expiresValue; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -291,7 +292,7 @@ public async Task Caching_ExpiresWithoutPublic_NotCached() httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r"); httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -312,7 +313,7 @@ public async Task Caching_MaxAgeAndExpires_MaxAgePreferred() httpContext.Response.Headers["Expires"] = (DateTime.UtcNow - TimeSpan.FromSeconds(10)).ToString("r"); // In the past httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -333,7 +334,7 @@ public async Task Caching_Flush_NotCached() httpContext.Response.ContentLength = 10; httpContext.Response.Body.FlushAsync(); return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -355,7 +356,7 @@ public async Task Caching_WriteFullContentLength_Cached() await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); // Http.Sys will add this for us Assert.Null(httpContext.Response.ContentLength); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await SendRequestAsync(address)); @@ -374,7 +375,7 @@ public async Task Caching_SendFileNoContentLength_NotCached() httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture); httpContext.Response.Headers["Cache-Control"] = "public, max-age=10"; await httpContext.Response.SendFileAsync(_absoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await GetFileAsync(address)); @@ -394,7 +395,7 @@ public async Task Caching_SendFileWithFullContentLength_Cached() httpContext.Response.Headers["Cache-Control"] = "public, max-age=30"; httpContext.Response.ContentLength = _fileLength; await httpContext.Response.SendFileAsync(_absoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests. Assert.Equal("1", await GetFileAsync(address)); @@ -416,7 +417,7 @@ public async Task Caching_VariousStatusCodes_Cached() httpContext.Response.StatusCode = status; httpContext.Response.ContentLength = 10; return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10); - })) + }, LoggerFactory)) { // Http.Sys will cache almost any status code. for (int status = 200; status < 600; status++) diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseHeaderTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseHeaderTests.cs index ab399e48db60..f9a8fc728642 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseHeaderTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseHeaderTests.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class ResponseHeaderTests +public class ResponseHeaderTests : LoggedTest { [ConditionalFact] public async Task ResponseHeaders_ServerSendsDefaultHeaders_Success() @@ -24,7 +24,7 @@ public async Task ResponseHeaders_ServerSendsDefaultHeaders_Success() using (Utilities.CreateHttpServer(out address, httpContext => { return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -47,7 +47,7 @@ public async Task ResponseHeaders_ServerSendsSingleValueKnownHeaders_Success() var responseHeaders = responseInfo.Headers; responseHeaders["WWW-Authenticate"] = new string[] { "custom1" }; return Task.FromResult(0); - })) + }, LoggerFactory)) { #pragma warning disable SYSLIB0014 // HttpClient would merge the headers no matter what @@ -73,7 +73,7 @@ public async Task ResponseHeaders_ServerSendsMultiValueKnownHeaders_Success() var responseHeaders = responseInfo.Headers; responseHeaders["WWW-Authenticate"] = new string[] { "custom1, and custom2", "custom3" }; return Task.FromResult(0); - })) + }, LoggerFactory)) { #pragma warning disable SYSLIB0014 // HttpClient would merge the headers no matter what WebRequest request = WebRequest.Create(address); @@ -98,7 +98,7 @@ public async Task ResponseHeaders_ServerSendsCustomHeaders_Success() var responseHeaders = responseInfo.Headers; responseHeaders["Custom-Header1"] = new string[] { "custom1, and custom2", "custom3" }; return Task.FromResult(0); - })) + }, LoggerFactory)) { #pragma warning disable SYSLIB0014 // HttpClient would merge the headers no matter what WebRequest request = WebRequest.Create(address); @@ -121,16 +121,16 @@ public async Task ResponseHeaders_ServerSendsNonAsciiHeaders_Success() { var responseInfo = httpContext.Features.Get(); var responseHeaders = responseInfo.Headers; - responseHeaders["Custom-Header1"] = new string[] { "Dašta" }; + responseHeaders["Custom-Header1"] = new string[] { "Dašta" }; return Task.FromResult(0); - })) + }, LoggerFactory)) { var socketsHttpHandler = new SocketsHttpHandler() { ResponseHeaderEncodingSelector = (_, _) => Encoding.UTF8 }; var httpClient = new HttpClient(socketsHttpHandler); var response = await httpClient.GetAsync(address); response.EnsureSuccessStatusCode(); Assert.True(response.Headers.TryGetValues("Custom-Header1", out var header)); - Assert.Equal("Dašta", header.Single()); + Assert.Equal("Dašta", header.Single()); } } @@ -144,7 +144,7 @@ public async Task ResponseHeaders_ServerSendsConnectionClose_Closed() var responseHeaders = responseInfo.Headers; responseHeaders["Connection"] = new string[] { "Close" }; return httpContext.Response.Body.FlushAsync(); // Http.Sys adds the Content-Length: header for us if we don't flush - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -165,7 +165,7 @@ public async Task ResponseHeaders_HTTP10Request_Gets11Close() using (Utilities.CreateHttpServer(out address, httpContext => { return Task.FromResult(0); - })) + }, LoggerFactory)) { using (HttpClient client = new HttpClient()) { @@ -192,7 +192,7 @@ public async Task ResponseHeaders_HTTP10RequestWithChunkedHeader_ManualChunking( responseHeaders["Transfer-Encoding"] = new string[] { "chunked" }; var responseBytes = Encoding.ASCII.GetBytes("10\r\nManually Chunked\r\n0\r\n\r\n"); return response.Body.WriteAsync(responseBytes, 0, responseBytes.Length); - })) + }, LoggerFactory)) { using (HttpClient client = new HttpClient()) { @@ -228,7 +228,7 @@ public async Task Headers_FlushSendsHeaders_Success() Assert.Throws(() => response.StatusCode = 404); Assert.Throws(() => responseHeaders.Add("Custom3", new string[] { "value3a, value3b", "value3c" })); return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -258,7 +258,7 @@ public async Task Headers_FlushAsyncSendsHeaders_Success() Assert.True(response.HasStarted); Assert.Throws(() => response.StatusCode = 404); Assert.Throws(() => responseHeaders.Add("Custom3", new string[] { "value3a, value3b", "value3c" })); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -281,7 +281,7 @@ public async Task Headers_IgnoreNullHeaders(string headerName, StringValues head var responseHeaders = httpContext.Response.Headers; responseHeaders.Add(headerName, headerValue); return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseSendFileTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseSendFileTests.cs index 4d6422e0158d..7e0c03f9c37f 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseSendFileTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseSendFileTests.cs @@ -14,11 +14,12 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys; -public class ResponseSendFileTests +public class ResponseSendFileTests : LoggedTest { private readonly string AbsoluteFilePath; private readonly string RelativeFilePath; @@ -48,7 +49,7 @@ public async Task ResponseSendFile_MissingFile_Throws() appThrew.SetResult(true); throw; } - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -64,7 +65,7 @@ public async Task ResponseSendFile_NoHeaders_DefaultsToChunked() { var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -83,7 +84,7 @@ public async Task ResponseSendFile_RelativeFile_Success() { var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(RelativeFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -102,7 +103,7 @@ public async Task ResponseSendFile_Unspecified_Chunked() { var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -122,7 +123,7 @@ public async Task ResponseSendFile_MultipleWrites_Chunked() var sendFile = httpContext.Features.Get(); sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None).Wait(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -141,7 +142,7 @@ public async Task ResponseSendFile_HalfOfFile_Chunked() { var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, FileLength / 2, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -163,7 +164,7 @@ public async Task ResponseSendFile_OffsetOutOfRange_Throws() await Assert.ThrowsAsync(() => sendFile.SendFileAsync(AbsoluteFilePath, 1234567, null, CancellationToken.None)); completed = true; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -182,7 +183,7 @@ public async Task ResponseSendFile_CountOutOfRange_Throws() await Assert.ThrowsAsync(() => sendFile.SendFileAsync(AbsoluteFilePath, 0, 1234567, CancellationToken.None)); completed = true; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -198,7 +199,7 @@ public async Task ResponseSendFile_Count0_Chunked() { var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -218,7 +219,7 @@ public async Task ResponseSendFile_ContentLength_PassedThrough() var sendFile = httpContext.Features.Get(); httpContext.Response.Headers["Content-lenGth"] = FileLength.ToString(CultureInfo.InvariantCulture); return sendFile.SendFileAsync(AbsoluteFilePath, 0, null, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -239,7 +240,7 @@ public async Task ResponseSendFile_ContentLengthSpecific_PassedThrough() var sendFile = httpContext.Features.Get(); httpContext.Response.Headers["Content-lenGth"] = "10"; return sendFile.SendFileAsync(AbsoluteFilePath, 0, 10, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -260,7 +261,7 @@ public async Task ResponseSendFile_ContentLength0_PassedThrough() var sendFile = httpContext.Features.Get(); httpContext.Response.Headers["Content-lenGth"] = "0"; return sendFile.SendFileAsync(AbsoluteFilePath, 0, 0, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -287,7 +288,7 @@ public async Task ResponseSendFile_TriggersOnStarting() }, httpContext); var sendFile = httpContext.Features.Get(); return sendFile.SendFileAsync(AbsoluteFilePath, 0, 10, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -313,7 +314,7 @@ public async Task ResponseSendFile_EmptyFileCountUnspecified_SetsChunkedAndFlush await httpContext.Response.SendFileAsync(emptyFilePath, 0, null, CancellationToken.None); Assert.True(httpContext.Response.HasStarted); await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10, CancellationToken.None); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -337,7 +338,7 @@ public async Task ResponseSendFile_WithActiveCancellationToken_Success() // First write sends headers await httpContext.Response.SendFileAsync(AbsoluteFilePath, 0, null, cts.Token); await httpContext.Response.SendFileAsync(AbsoluteFilePath, 0, null, cts.Token); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -355,7 +356,7 @@ public async Task ResponseSendFile_WithTimerCancellationToken_Success() // First write sends headers await httpContext.Response.SendFileAsync(AbsoluteFilePath, 0, null, cts.Token); await httpContext.Response.SendFileAsync(AbsoluteFilePath, 0, null, cts.Token); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -384,7 +385,7 @@ public async Task ResponseSendFileWriteExceptions_FirstCallWithCanceledCancellat } return Task.CompletedTask; - }, options => options.ThrowWriteExceptions = true)) + }, options => options.ThrowWriteExceptions = true, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); await testComplete.Task.DefaultTimeout(); @@ -412,7 +413,7 @@ public async Task ResponseSendFile_FirstSendWithCanceledCancellationToken_Cancel } return Task.CompletedTask; - })) + }, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); await testComplete.Task.DefaultTimeout(); @@ -439,7 +440,7 @@ public async Task ResponseSendFileExceptions_SecondSendWithCanceledCancellationT { testComplete.SetException(ex); } - }, options => options.ThrowWriteExceptions = true)) + }, options => options.ThrowWriteExceptions = true, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); await testComplete.Task.DefaultTimeout(); @@ -466,7 +467,7 @@ public async Task ResponseSendFile_SecondSendWithCanceledCancellationToken_Cance { testComplete.SetException(ex); } - })) + }, LoggerFactory)) { await Assert.ThrowsAsync(() => SendRequestAsync(address)); await testComplete.Task.DefaultTimeout(); @@ -511,7 +512,7 @@ await Assert.ThrowsAsync(() => testComplete.SetException(ex); } - }, options => options.ThrowWriteExceptions = true)) + }, options => options.ThrowWriteExceptions = true, LoggerFactory)) { var cts = new CancellationTokenSource(); var responseTask = SendRequestAsync(address, cts.Token); @@ -554,7 +555,7 @@ public async Task ResponseSendFile_ClientDisconnectsBeforeFirstSend_SendComplete testComplete.SetException(ex); } - })) + }, LoggerFactory)) { var cts = new CancellationTokenSource(); var responseTask = SendRequestAsync(address, cts.Token); @@ -605,7 +606,7 @@ await Assert.ThrowsAsync(async () => { testComplete.SetException(ex); } - }, options => options.ThrowWriteExceptions = true)) + }, options => options.ThrowWriteExceptions = true, LoggerFactory)) { using (var client = new HttpClient()) { @@ -654,7 +655,7 @@ public async Task ResponseSendFile_ClientDisconnectsBeforeSecondSend_SendComplet { testComplete.SetException(ex); } - })) + }, LoggerFactory)) { using (var client = new HttpClient()) { diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseTests.cs index 7085b56298bd..12322f06be68 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseTests.cs @@ -12,11 +12,12 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys; -public class ResponseTests +public class ResponseTests : LoggedTest { [ConditionalFact] public async Task Response_ServerSendsDefaultResponse_ServerProvidesStatusCodeAndReasonPhrase() @@ -27,7 +28,7 @@ public async Task Response_ServerSendsDefaultResponse_ServerProvidesStatusCodeAn Assert.Equal(200, httpContext.Response.StatusCode); Assert.False(httpContext.Response.HasStarted); return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); @@ -46,7 +47,7 @@ public async Task Response_ServerSendsSpecificStatus_ServerProvidesReasonPhrase( httpContext.Response.StatusCode = 201; // TODO: httpContext["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(201, (int)response.StatusCode); @@ -66,7 +67,7 @@ public async Task Response_ServerSendsSpecificStatusAndReasonPhrase_PassedThroug httpContext.Features.Get().ReasonPhrase = "CustomReasonPhrase"; // TODO? // TODO: httpContext["owin.ResponseProtocol"] = "HTTP/1.0"; // Http.Sys ignores this value return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(201, (int)response.StatusCode); @@ -84,7 +85,7 @@ public async Task Response_ServerSendsCustomStatus_NoReasonPhrase() { httpContext.Response.StatusCode = 901; return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(901, (int)response.StatusCode); @@ -101,7 +102,7 @@ public async Task Response_StatusCode100_Throws() { httpContext.Response.StatusCode = 100; return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(500, (int)response.StatusCode); @@ -116,7 +117,7 @@ public async Task Response_StatusCode0_Throws() { httpContext.Response.StatusCode = 0; return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -144,7 +145,7 @@ public async Task Response_Empty_CallsOnStartingAndOnCompleted() return Task.CompletedTask; }, httpContext); return Task.CompletedTask; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -173,7 +174,7 @@ public async Task Response_OnStartingThrows_StillCallsOnCompleted() return Task.CompletedTask; }, httpContext); return Task.CompletedTask; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -203,7 +204,7 @@ public async Task Response_OnStartingThrowsAfterWrite_WriteThrowsAndStillCallsOn }, httpContext); Assert.Throws(() => httpContext.Response.Body.Write(new byte[10], 0, 10)); return Task.CompletedTask; - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -248,7 +249,7 @@ public async Task ClientDisconnectsBeforeResponse_ResponseCanStillBeModified() } readCompleted.SetResult(); - }); + }, LoggerFactory); // Send a request without the body. var uri = new Uri(address); diff --git a/src/Servers/HttpSys/test/FunctionalTests/ResponseTrailersTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ResponseTrailersTests.cs index d48dcc3c060e..de458a3e652d 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ResponseTrailersTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ResponseTrailersTests.cs @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class ResponseTrailersTests +public class ResponseTrailersTests : LoggedTest { [ConditionalFact] public async Task ResponseTrailers_HTTP11_TrailersNotAvailable() @@ -27,7 +27,7 @@ public async Task ResponseTrailers_HTTP11_TrailersNotAvailable() Assert.Equal("HTTP/1.1", httpContext.Request.Protocol); Assert.False(httpContext.Response.SupportsTrailers()); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address, http2: false); response.EnsureSuccessStatusCode(); @@ -45,7 +45,7 @@ public async Task ResponseTrailers_HTTP2_TrailersAvailable() Assert.Equal("HTTP/2", httpContext.Request.Protocol); Assert.True(httpContext.Response.SupportsTrailers()); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -66,7 +66,7 @@ public async Task ResponseTrailers_ProhibitedTrailers_Blocked() Assert.Throws(() => httpContext.Response.AppendTrailer(header, "value")); } return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -84,7 +84,7 @@ public async Task ResponseTrailers_NoBody_TrailersSent() httpContext.Response.DeclareTrailer("trailername"); httpContext.Response.AppendTrailer("trailername", "TrailerValue"); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -102,7 +102,7 @@ public async Task ResponseTrailers_WithBody_TrailersSent() { await httpContext.Response.WriteAsync("Hello World"); httpContext.Response.AppendTrailer("TrailerName", "Trailer Value"); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -132,7 +132,7 @@ public async Task ResponseTrailers_WithContentLengthBody_TrailersNotSent() { responseFinished.SetException(ex); } - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -155,7 +155,7 @@ public async Task ResponseTrailers_WithTrailersBeforeContentLengthBody_TrailersS await httpContext.Response.WriteAsync(body); httpContext.Response.AppendTrailer("TrailerName", "Trailer Value"); await httpContext.Response.WriteAsync(body); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -180,7 +180,7 @@ public async Task ResponseTrailers_WithContentLengthBodyAndDeclared_TrailersSent httpContext.Response.DeclareTrailer("TrailerName"); await httpContext.Response.WriteAsync(body); httpContext.Response.AppendTrailer("TrailerName", "Trailer Value"); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -206,7 +206,7 @@ public async Task ResponseTrailers_WithContentLengthBodyAndDeclaredButMissingTra httpContext.Response.DeclareTrailer("TrailerName"); await httpContext.Response.WriteAsync(body); // If we declare trailers but don't send any make sure it completes anyways. - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -230,7 +230,7 @@ public async Task ResponseTrailers_CompleteAsyncNoBody_TrailersSent() httpContext.Response.AppendTrailer("trailername", "TrailerValue"); await httpContext.Response.CompleteAsync(); await trailersReceived.Task.DefaultTimeout(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -252,7 +252,7 @@ public async Task ResponseTrailers_CompleteAsyncWithBody_TrailersSent() httpContext.Response.AppendTrailer("TrailerName", "Trailer Value"); await httpContext.Response.CompleteAsync(); await trailersReceived.Task.DefaultTimeout(); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -272,7 +272,7 @@ public async Task ResponseTrailers_MultipleValues_SentAsSeparateHeaders() { httpContext.Response.AppendTrailer("trailername", new StringValues(new[] { "TrailerValue0", "TrailerValue1" })); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -300,7 +300,7 @@ public async Task ResponseTrailers_LargeTrailers_Success() { httpContext.Response.AppendTrailer("ThisIsALongerHeaderNameThatStillWorksForReals", new StringValues(values)); return Task.FromResult(0); - })) + }, LoggerFactory)) { var response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); @@ -320,7 +320,7 @@ public async Task ResponseTrailers_NullValues_Ignored(string headerName, StringV { httpContext.Response.AppendTrailer(headerName, headerValue); return Task.FromResult(0); - })) + }, LoggerFactory)) { HttpResponseMessage response = await SendRequestAsync(address); response.EnsureSuccessStatusCode(); diff --git a/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs index 2731b109e35b..91dc5a76bede 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -public class ServerTests +public class ServerTests : LoggedTest { [ConditionalFact] public async Task Server_200OK_Success() @@ -29,7 +29,7 @@ public async Task Server_200OK_Success() using (Utilities.CreateHttpServer(out address, httpContext => { return Task.FromResult(0); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); @@ -63,7 +63,7 @@ public async Task Server_ConnectExistingQueueName_Success(RequestQueueMode queue { options.RequestQueueName = queueName; options.RequestQueueMode = queueMode; - })) + }, LoggerFactory)) { var psi = new ProcessStartInfo("netsh", "http show servicestate view=requestq") { @@ -101,7 +101,7 @@ public async Task Server_SetQueueName_Success() }, options => { options.RequestQueueName = queueName; - })) + }, LoggerFactory)) { var psi = new ProcessStartInfo("netsh", "http show servicestate view=requestq") { @@ -122,7 +122,7 @@ public async Task Server_SendHelloWorld_Success() { httpContext.Response.ContentLength = 11; return httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address); Assert.Equal("Hello World", response); @@ -139,7 +139,7 @@ public async Task Server_EchoHelloWorld_Success() Assert.Equal("Hello World", input); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { string response = await SendRequestAsync(address, "Hello World"); Assert.Equal("Hello World", response); @@ -156,7 +156,7 @@ public async Task Server_ShutdownDuringRequest_Success() received.SetResult(); httpContext.Response.ContentLength = 11; return httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -178,7 +178,7 @@ public async Task Server_DisposeWithoutStopDuringRequest_Aborts() await stopped.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -199,7 +199,7 @@ public async Task Server_ShutdownDuringLongRunningRequest_TimesOut() await shutdown.Task.TimeoutAfter(TimeSpan.FromSeconds(15)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -216,7 +216,7 @@ public async Task Server_AppException_ClientReset() using (Utilities.CreateHttpServer(out address, httpContext => { throw new InvalidOperationException(); - })) + }, LoggerFactory)) { Task requestTask = SendRequestAsync(address); var ex = await Assert.ThrowsAsync(async () => await requestTask); @@ -236,7 +236,7 @@ public async Task Server_BadHttpRequestException_SetStatusCode() using (Utilities.CreateHttpServer(out address, httpContext => { throw new BadHttpRequestException("Something happened", StatusCodes.Status418ImATeapot); - })) + }, LoggerFactory)) { Task requestTask = SendRequestAsync(address); var ex = await Assert.ThrowsAsync(async () => await requestTask); @@ -267,7 +267,7 @@ public void Server_MultipleOutstandingAsyncRequests_Success() { await tcs.Task; } - })) + }, LoggerFactory)) { List requestTasks = new List(); for (int i = 0; i < requestLimit; i++) @@ -297,7 +297,7 @@ public async Task Server_ClientDisconnects_CallCanceled() await aborted.Task.TimeoutAfter(interval); await canceled.Task.TimeoutAfter(interval); Assert.True(ct.IsCancellationRequested, "IsCancellationRequested"); - })) + }, LoggerFactory)) { // Note: System.Net.Sockets does not RST the connection by default, it just FINs. // Http.Sys's disconnect notice requires a RST. @@ -330,7 +330,7 @@ public async Task Server_Abort_CallCanceled() httpContext.Abort(); await canceled.Task.TimeoutAfter(interval); Assert.True(ct.IsCancellationRequested, "IsCancellationRequested"); - })) + }, LoggerFactory)) { using (var client = await SendHungRequestAsync("GET", address)) { @@ -345,9 +345,9 @@ public async Task Server_SetQueueLimit_Success() { // This is just to get a dynamic port string address; - using (Utilities.CreateHttpServer(out address, httpContext => Task.FromResult(0))) { } + using (Utilities.CreateHttpServer(out address, httpContext => Task.FromResult(0), LoggerFactory)) { } - var server = Utilities.CreatePump(); + var server = Utilities.CreatePump(LoggerFactory); server.Listener.Options.UrlPrefixes.Add(UrlPrefix.Create(address)); server.Listener.Options.RequestQueueLimit = 1001; @@ -367,7 +367,7 @@ public async Task Server_SetHttp503VebosityHittingThrottle_Success() Assert.Null(options.MaxConnections); options.MaxConnections = 3; options.Http503Verbosity = Http503VerbosityLevel.Limited; - }, httpContext => Task.FromResult(0))) + }, httpContext => Task.FromResult(0), LoggerFactory)) { using (var client1 = await SendHungRequestAsync("GET", address)) using (var client2 = await SendHungRequestAsync("GET", address)) @@ -389,7 +389,7 @@ public async Task Server_SetHttp503VebosityHittingThrottle_Success() [ConditionalFact] public void Server_SetConnectionLimitArgumentValidation_Success() { - using (var server = Utilities.CreatePump()) + using (var server = Utilities.CreatePump(LoggerFactory)) { Assert.Null(server.Listener.Options.MaxConnections); Assert.Throws(() => server.Listener.Options.MaxConnections = -2); @@ -406,7 +406,7 @@ public async Task Server_SetConnectionLimitInfinite_Success() { Assert.Null(options.MaxConnections); options.MaxConnections = -1; // infinite - }, httpContext => Task.FromResult(0))) + }, httpContext => Task.FromResult(0), LoggerFactory)) { using (var client1 = await SendHungRequestAsync("GET", address)) using (var client2 = await SendHungRequestAsync("GET", address)) @@ -431,7 +431,7 @@ public async Task Server_MultipleStopAsyncCallsWaitForRequestsToDrain_Success() await run.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -465,7 +465,7 @@ public async Task Server_MultipleStopAsyncCallsCompleteOnCancellation_SameToken_ await run.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -502,7 +502,7 @@ public async Task Server_MultipleStopAsyncCallsCompleteOnSingleCancellation_Firs await run.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -539,7 +539,7 @@ public async Task Server_MultipleStopAsyncCallsCompleteOnSingleCancellation_Subs await run.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -578,7 +578,7 @@ public async Task Server_DisposeContinuesPendingStopAsyncCalls() await run.Task.TimeoutAfter(TimeSpan.FromSeconds(15)); httpContext.Response.ContentLength = 11; await httpContext.Response.WriteAsync("Hello World"); - })) + }, LoggerFactory)) { responseTask = SendRequestAsync(address); await received.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); @@ -597,7 +597,7 @@ public async Task Server_DisposeContinuesPendingStopAsyncCalls() [ConditionalFact] public async Task Server_StopAsyncCalledWithNoRequests_Success() { - using (var server = Utilities.CreateHttpServer(out _, httpContext => Task.CompletedTask)) + using (var server = Utilities.CreateHttpServer(out _, httpContext => Task.CompletedTask, LoggerFactory)) { await server.StopAsync(default(CancellationToken)).TimeoutAfter(TimeSpan.FromSeconds(10)); } @@ -612,12 +612,12 @@ public async Task Server_AttachToExistingQueue_NoIServerAddresses_NoDefaultAdded using var server = Utilities.CreateHttpServer(out var address, httpContext => Task.CompletedTask, options => { options.RequestQueueName = queueName; - }); + }, LoggerFactory); using var attachedServer = Utilities.CreatePump(options => { options.RequestQueueName = queueName; options.RequestQueueMode = queueMode; - }); + }, LoggerFactory); await attachedServer.StartAsync(new DummyApplication(context => Task.CompletedTask), default); var addressesFeature = attachedServer.Features.Get(); Assert.Empty(addressesFeature.Addresses); @@ -636,7 +636,7 @@ public async Task Server_UnsafePreferInlineScheduling() options => { options.UnsafePreferInlineScheduling = true; - }); + }, LoggerFactory); string response = await SendRequestAsync(address); Assert.Equal("Hello World", response); diff --git a/src/Servers/HttpSys/test/FunctionalTests/Utilities.cs b/src/Servers/HttpSys/test/FunctionalTests/Utilities.cs index 7c1264aa4477..49beca0fb34a 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/Utilities.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/Utilities.cs @@ -40,49 +40,49 @@ static Utilities() IsWin8orLater = (Environment.OSVersion.Version >= win8Version); } - internal static IServer CreateHttpServer(out string baseAddress, RequestDelegate app) + internal static IServer CreateHttpServer(out string baseAddress, RequestDelegate app, ILoggerFactory loggerFactory) { string root; - return CreateDynamicHttpServer(string.Empty, out root, out baseAddress, options => { }, app); + return CreateDynamicHttpServer(string.Empty, out root, out baseAddress, options => { }, app, loggerFactory); } - internal static IServer CreateHttpServer(out string baseAddress, RequestDelegate app, Action configureOptions) + internal static IServer CreateHttpServer(out string baseAddress, RequestDelegate app, Action configureOptions, ILoggerFactory loggerFactory) { string root; - return CreateDynamicHttpServer(string.Empty, out root, out baseAddress, configureOptions, app); + return CreateDynamicHttpServer(string.Empty, out root, out baseAddress, configureOptions, app, loggerFactory); } - internal static IServer CreateHttpServerReturnRoot(string path, out string root, RequestDelegate app) + internal static IServer CreateHttpServerReturnRoot(string path, out string root, RequestDelegate app, ILoggerFactory loggerFactory) { string baseAddress; - return CreateDynamicHttpServer(path, out root, out baseAddress, options => { }, app); + return CreateDynamicHttpServer(path, out root, out baseAddress, options => { }, app, loggerFactory); } - internal static IServer CreateHttpAuthServer(AuthenticationSchemes authType, bool allowAnonymous, out string baseAddress, RequestDelegate app) + internal static IServer CreateHttpAuthServer(AuthenticationSchemes authType, bool allowAnonymous, out string baseAddress, RequestDelegate app, ILoggerFactory loggerFactory) { string root; return CreateDynamicHttpServer(string.Empty, out root, out baseAddress, options => { options.Authentication.Schemes = authType; options.Authentication.AllowAnonymous = allowAnonymous; - }, app); + }, app, loggerFactory); } - internal static IHost CreateDynamicHost(AuthenticationSchemes authType, bool allowAnonymous, out string root, RequestDelegate app) + internal static IHost CreateDynamicHost(AuthenticationSchemes authType, bool allowAnonymous, out string root, RequestDelegate app, ILoggerFactory loggerFactory) { return CreateDynamicHost(string.Empty, out root, out var baseAddress, options => { options.Authentication.Schemes = authType; options.Authentication.AllowAnonymous = allowAnonymous; - }, app); + }, app, loggerFactory); } - internal static IHost CreateDynamicHost(out string baseAddress, Action configureOptions, RequestDelegate app) + internal static IHost CreateDynamicHost(out string baseAddress, Action configureOptions, RequestDelegate app, ILoggerFactory loggerFactory) { - return CreateDynamicHost(string.Empty, out var root, out baseAddress, configureOptions, app); + return CreateDynamicHost(string.Empty, out var root, out baseAddress, configureOptions, app, loggerFactory); } - internal static IHost CreateDynamicHost(string basePath, out string root, out string baseAddress, Action configureOptions, RequestDelegate app) + internal static IHost CreateDynamicHost(string basePath, out string root, out string baseAddress, Action configureOptions, RequestDelegate app, ILoggerFactory loggerFactory) { var prefix = UrlPrefix.Create("http", "localhost", "0", basePath); @@ -95,6 +95,7 @@ internal static IHost CreateDynamicHost(string basePath, out string root, out st options.UrlPrefixes.Add(prefix); configureOptions(options); }) + .ConfigureLogging(builder => builder.AddProvider(new ForwardingLoggerProvider(loggerFactory))) .Configure(appBuilder => appBuilder.Run(app)); }); @@ -110,21 +111,21 @@ internal static IHost CreateDynamicHost(string basePath, out string root, out st return host; } - internal static MessagePump CreatePump(ILoggerFactory loggerFactory = null) + internal static MessagePump CreatePump(ILoggerFactory loggerFactory) => new MessagePump(Options.Create(new HttpSysOptions()), loggerFactory ?? new LoggerFactory(), new AuthenticationSchemeProvider(Options.Create(new AuthenticationOptions()))); - internal static MessagePump CreatePump(Action configureOptions, ILoggerFactory loggerFactory = null) + internal static MessagePump CreatePump(Action configureOptions, ILoggerFactory loggerFactory) { var options = new HttpSysOptions(); configureOptions(options); return new MessagePump(Options.Create(options), loggerFactory ?? new LoggerFactory(), new AuthenticationSchemeProvider(Options.Create(new AuthenticationOptions()))); } - internal static IServer CreateDynamicHttpServer(string basePath, out string root, out string baseAddress, Action configureOptions, RequestDelegate app) + internal static IServer CreateDynamicHttpServer(string basePath, out string root, out string baseAddress, Action configureOptions, RequestDelegate app, ILoggerFactory loggerFactory) { var prefix = UrlPrefix.Create("http", "localhost", "0", basePath); - var server = CreatePump(configureOptions); + var server = CreatePump(configureOptions, loggerFactory); server.Features.Get().Addresses.Add(prefix.ToString()); server.StartAsync(new DummyApplication(app), CancellationToken.None).Wait(); @@ -135,7 +136,7 @@ internal static IServer CreateDynamicHttpServer(string basePath, out string root return server; } - internal static IServer CreateDynamicHttpsServer(out string baseAddress, RequestDelegate app, ILoggerFactory loggerFactory = null) + internal static IServer CreateDynamicHttpsServer(out string baseAddress, RequestDelegate app, ILoggerFactory loggerFactory) { return CreateDynamicHttpsServer("/", out var root, out baseAddress, options => { }, app, loggerFactory); } @@ -172,4 +173,23 @@ internal static IServer CreateDynamicHttpsServer(string basePath, out string roo { return request.HttpContext.Features.Get()?.CanHaveBody; } + + private sealed class ForwardingLoggerProvider : ILoggerProvider + { + private readonly ILoggerFactory _loggerFactory; + + public ForwardingLoggerProvider(ILoggerFactory loggerFactory) + { + _loggerFactory = loggerFactory; + } + + public void Dispose() + { + } + + public ILogger CreateLogger(string categoryName) + { + return _loggerFactory.CreateLogger(categoryName); + } + } }