Przeglądaj źródła

Revert Dispose in IIS tests (#43199)

Hao Kung 3 lat temu
rodzic
commit
4b3f57e576

+ 1 - 3
src/Hosting/Server.IntegrationTesting/src/Common/DeploymentResult.cs

@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting;
 /// <summary>
 /// Result of a deployment.
 /// </summary>
-public class DeploymentResult : IDisposable
+public class DeploymentResult
 {
     private readonly ILoggerFactory _loggerFactory;
 
@@ -67,6 +67,4 @@ public class DeploymentResult : IDisposable
             BaseAddress = new Uri(ApplicationBaseUri),
             Timeout = TimeSpan.FromSeconds(200),
         };
-
-    public void Dispose() => HttpClient.Dispose();
 }

+ 50 - 47
src/Servers/IIS/IIS/test/Common.FunctionalTests/AspNetCorePortTests.cs

@@ -1,9 +1,14 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.Collections.Generic;
 using System.Globalization;
+using System.Linq;
 using System.Net;
 using System.Net.Sockets;
+using System.Threading.Tasks;
+using Xunit;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Testing;
@@ -53,11 +58,11 @@ public class AspNetCorePortTests : IISFunctionalTestBase
         var port = GetUnusedRandomPort();
         deploymentParameters.WebConfigBasedEnvironmentVariables["ASPNETCORE_PORT"] = port.ToString(CultureInfo.InvariantCulture);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var responseText = await deploymentResult.HttpClient.GetStringAsync("/ServerAddresses");
-            Assert.Equal(port, new Uri(responseText).Port);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var responseText = await deploymentResult.HttpClient.GetStringAsync("/ServerAddresses");
+
+        Assert.Equal(port, new Uri(responseText).Port);
     }
 
     [ConditionalTheory]
@@ -68,13 +73,12 @@ public class AspNetCorePortTests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
         deploymentParameters.WebConfigBasedEnvironmentVariables["ASPNETCORE_PORT"] = string.Empty;
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var responseText = await deploymentResult.HttpClient.GetStringAsync("/ServerAddresses");
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var responseText = await deploymentResult.HttpClient.GetStringAsync("/ServerAddresses");
 
-            // If env var is empty, ANCM should assign a random port (same as no env var)
-            Assert.InRange(new Uri(responseText).Port, _minPort, _maxPort);
-        });
+        // If env var is empty, ANCM should assign a random port (same as no env var)
+        Assert.InRange(new Uri(responseText).Port, _minPort, _maxPort);
     }
 
     [ConditionalTheory]
@@ -85,11 +89,11 @@ public class AspNetCorePortTests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
         deploymentParameters.WebConfigBasedEnvironmentVariables["ASPNETCORE_PORT"] = port;
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("/ServerAddresses");
-            Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("/ServerAddresses");
+
+        Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
     }
 
     [ConditionalTheory]
@@ -100,46 +104,45 @@ public class AspNetCorePortTests : IISFunctionalTestBase
         // Must publish to set env vars in web.config
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            // Shutdown once
-            var response = await deploymentResult.HttpClient.GetAsync("/Shutdown");
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // Wait for server to start again.
-            int i;
-            for (i = 0; i < 10; i++)
-            {
-                // ANCM should eventually recover from being shutdown multiple times.
-                response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-                if (response.IsSuccessStatusCode)
-                {
-                    break;
-                }
-            }
+        // Shutdown once
+        var response = await deploymentResult.HttpClient.GetAsync("/Shutdown");
 
-            if (i == 10)
+        // Wait for server to start again.
+        int i;
+        for (i = 0; i < 10; i++)
+        {
+            // ANCM should eventually recover from being shutdown multiple times.
+            response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+            if (response.IsSuccessStatusCode)
             {
-                // Didn't restart after 10 retries
-                Assert.False(true);
+                break;
             }
+        }
+
+        if (i == 10)
+        {
+            // Didn't restart after 10 retries
+            Assert.False(true);
+        }
 
-            // Shutdown again
-            response = await deploymentResult.HttpClient.GetAsync("/Shutdown");
+        // Shutdown again
+        response = await deploymentResult.HttpClient.GetAsync("/Shutdown");
 
-            // return if server starts again.
-            for (i = 0; i < 10; i++)
+        // return if server starts again.
+        for (i = 0; i < 10; i++)
+        {
+            // ANCM should eventually recover from being shutdown multiple times.
+            response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+            if (response.IsSuccessStatusCode)
             {
-                // ANCM should eventually recover from being shutdown multiple times.
-                response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-                if (response.IsSuccessStatusCode)
-                {
-                    return;
-                }
+                return;
             }
+        }
 
-            // Test failure if this happens.
-            Assert.False(true);
-        });
+        // Test failure if this happens.
+        Assert.False(true);
     }
 
     private static int GetUnusedRandomPort()

+ 75 - 75
src/Servers/IIS/IIS/test/Common.FunctionalTests/GlobalVersionTests.cs

@@ -1,12 +1,17 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.IO;
+using System.Linq;
 using System.Net;
+using System.Threading.Tasks;
 using System.Xml.Linq;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -41,12 +46,11 @@ public class GlobalVersionTests : IISFunctionalTestBase
 
         deploymentParameters.HandlerSettings["handlerVersion"] = _handlerVersion20;
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
-            var responseText = await response.Content.ReadAsStringAsync();
-            Assert.Equal(_helloWorldResponse, responseText);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
+        var responseText = await response.Content.ReadAsStringAsync();
+        Assert.Equal(_helloWorldResponse, responseText);
     }
 
     [ConditionalFact]
@@ -62,18 +66,16 @@ public class GlobalVersionTests : IISFunctionalTestBase
             deploymentParameters.PublishApplicationBeforeDeployment = true;
             deploymentParameters.EnvironmentVariables["ASPNETCORE_MODULE_OUTOFPROCESS_HANDLER"] = temporaryFile;
 
-            await RunTest(deploymentParameters, async deploymentResult =>
-            {
-                var requestHandlerPath = Path.Combine(GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20), "aspnetcorev2_outofprocess.dll");
+            var deploymentResult = await DeployAsync(deploymentParameters);
+            var requestHandlerPath = Path.Combine(GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20), "aspnetcorev2_outofprocess.dll");
 
-                File.Delete(temporaryFile);
-                File.Move(requestHandlerPath, temporaryFile);
+            File.Delete(temporaryFile);
+            File.Move(requestHandlerPath, temporaryFile);
 
-                var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
-                var responseText = await response.Content.ReadAsStringAsync();
-                Assert.Equal(_helloWorldResponse, responseText);
-                StopServer();
-            });
+            var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
+            var responseText = await response.Content.ReadAsStringAsync();
+            Assert.Equal(_helloWorldResponse, responseText);
+            StopServer();
         }
         finally
         {
@@ -91,13 +93,12 @@ public class GlobalVersionTests : IISFunctionalTestBase
         var deploymentParameters = GetGlobalVersionBaseDeploymentParameters();
         deploymentParameters.HandlerSettings["handlerVersion"] = version;
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
-            Assert.False(response.IsSuccessStatusCode);
-            var responseString = await response.Content.ReadAsStringAsync();
-            Assert.Contains("500.0", responseString);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
+        Assert.False(response.IsSuccessStatusCode);
+        var responseString = await response.Content.ReadAsStringAsync();
+        Assert.Contains("500.0", responseString);
     }
 
     [ConditionalTheory]
@@ -111,17 +112,16 @@ public class GlobalVersionTests : IISFunctionalTestBase
         CopyShimToOutput(deploymentParameters);
         deploymentParameters.HandlerSettings["handlerVersion"] = version;
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
-            var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
-            Directory.Move(originalANCMPath, newANCMPath);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
-            var responseText = await response.Content.ReadAsStringAsync();
-            Assert.Equal(_helloWorldResponse, responseText);
-            AssertLoadedVersion(version);
-        });
+        var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
+        var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
+        Directory.Move(originalANCMPath, newANCMPath);
+
+        var response = await deploymentResult.HttpClient.GetAsync(_helloWorldRequest);
+        var responseText = await response.Content.ReadAsStringAsync();
+        Assert.Equal(_helloWorldResponse, responseText);
+        AssertLoadedVersion(version);
     }
 
     [ConditionalTheory]
@@ -133,21 +133,20 @@ public class GlobalVersionTests : IISFunctionalTestBase
     {
         var deploymentParameters = GetGlobalVersionBaseDeploymentParameters();
         CopyShimToOutput(deploymentParameters);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
+        var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
 
-            CopyDirectory(originalANCMPath, newANCMPath);
+        var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
 
-            deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", newANCMPath);
-            var response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
-            var responseText = await response.Content.ReadAsStringAsync();
+        CopyDirectory(originalANCMPath, newANCMPath);
 
-            Assert.Equal(_helloWorldResponse, responseText);
-            AssertLoadedVersion(version);
-        });
+        deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", newANCMPath);
+        var response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
+        var responseText = await response.Content.ReadAsStringAsync();
+
+        Assert.Equal(_helloWorldResponse, responseText);
+        AssertLoadedVersion(version);
     }
 
     [ConditionalTheory]
@@ -159,34 +158,32 @@ public class GlobalVersionTests : IISFunctionalTestBase
     {
         var deploymentParameters = GetGlobalVersionBaseDeploymentParameters();
         CopyShimToOutput(deploymentParameters);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", originalANCMPath);
-            var response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
-            var responseText = await response.Content.ReadAsStringAsync();
+        var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
 
-            Assert.Equal(_helloWorldResponse, responseText);
+        deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", originalANCMPath);
+        var response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
+        var responseText = await response.Content.ReadAsStringAsync();
 
-            StopServer();
-        });
+        Assert.Equal(_helloWorldResponse, responseText);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
+        StopServer();
 
-            var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
+        deploymentResult = await DeployAsync(deploymentParameters);
 
-            CopyDirectory(originalANCMPath, newANCMPath);
+        originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
 
-            deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", newANCMPath);
-            var response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
-            var responseText = await response.Content.ReadAsStringAsync();
+        var newANCMPath = GetANCMRequestHandlerPath(deploymentResult, version);
 
-            Assert.Equal(_helloWorldResponse, responseText);
-            AssertLoadedVersion(version);
-        });
+        CopyDirectory(originalANCMPath, newANCMPath);
+
+        deploymentResult.HttpClient.DefaultRequestHeaders.Add("ANCMRHPath", newANCMPath);
+        response = await deploymentResult.HttpClient.GetAsync("CheckRequestHandlerVersion");
+        responseText = await response.Content.ReadAsStringAsync();
+
+        Assert.Equal(_helloWorldResponse, responseText);
+        AssertLoadedVersion(version);
     }
 
     [ConditionalFact]
@@ -194,18 +191,19 @@ public class GlobalVersionTests : IISFunctionalTestBase
     {
         var deploymentParameters = GetGlobalVersionBaseDeploymentParameters();
         CopyShimToOutput(deploymentParameters);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
-            Directory.Delete(originalANCMPath, true);
-            var response = await deploymentResult.HttpClient.GetAsync("HelloWorld");
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
-        });
+        var originalANCMPath = GetANCMRequestHandlerPath(deploymentResult, _handlerVersion20);
+        Directory.Delete(originalANCMPath, true);
+        var response = await deploymentResult.HttpClient.GetAsync("HelloWorld");
+
+        Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
     }
 
     private IISDeploymentParameters GetGlobalVersionBaseDeploymentParameters()
-        => Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
+    {
+        return Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
+    }
 
     private void CopyDirectory(string from, string to)
     {
@@ -219,9 +217,11 @@ public class GlobalVersionTests : IISFunctionalTestBase
     }
 
     private string GetANCMRequestHandlerPath(IISDeploymentResult deploymentResult, string version)
-        => Path.Combine(deploymentResult.ContentRoot,
+    {
+        return Path.Combine(deploymentResult.ContentRoot,
             deploymentResult.DeploymentParameters.RuntimeArchitecture.ToString(),
             version);
+    }
 
     private void AssertLoadedVersion(string version)
     {
@@ -255,12 +255,12 @@ public class GlobalVersionTests : IISFunctionalTestBase
 
     private static void CopyFiles(DirectoryInfo source, DirectoryInfo target)
     {
-        foreach (var directoryInfo in source.GetDirectories())
+        foreach (DirectoryInfo directoryInfo in source.GetDirectories())
         {
             CopyFiles(directoryInfo, target.CreateSubdirectory(directoryInfo.Name));
         }
 
-        foreach (var fileInfo in source.GetFiles())
+        foreach (FileInfo fileInfo in source.GetFiles())
         {
             var destFileName = Path.Combine(target.FullName, fileInfo.Name);
             fileInfo.CopyTo(destFileName, overwrite: true);

+ 0 - 8
src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/FunctionalTestsBase.cs

@@ -29,14 +29,6 @@ public class FunctionalTestsBase : LoggedTest
         return IISApplicationDeployerFactory.Create(parameters, LoggerFactory);
     }
 
-    protected virtual async Task RunTest(IISDeploymentParameters deploymentParameters, Action<IISDeploymentResult> testCode)
-    {
-        using (var deploymentResult = await DeployAsync(deploymentParameters))
-        {
-            testCode(deploymentResult);
-        }
-    }
-
     protected virtual async Task<IISDeploymentResult> DeployAsync(IISDeploymentParameters parameters)
     {
         _deployer = (IISDeployerBase)CreateDeployer(parameters);

+ 5 - 3
src/Servers/IIS/IIS/test/Common.FunctionalTests/Infrastructure/IISFunctionalTestBase.cs

@@ -1,10 +1,15 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.IO;
 using System.Net;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.Extensions.Logging;
+using Xunit;
 using Xunit.Abstractions;
 
 namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
@@ -29,9 +34,6 @@ public class IISFunctionalTestBase : FunctionalTestsBase
         return await DeployAsync(deploymentParameters);
     }
 
-    public Task RunTest(HostingModel hostingModel, Action<IISDeploymentResult> testCode)
-        => RunTest(Fixture.GetBaseDeploymentParameters(hostingModel: hostingModel), testCode);
-
     public void AddAppOffline(string appPath, string content = "The app is offline.")
     {
         File.WriteAllText(Path.Combine(appPath, "app_offline.htm"), content);

+ 41 - 42
src/Servers/IIS/IIS/test/Common.FunctionalTests/Inprocess/MaxRequestBodySizeTests.cs

@@ -3,10 +3,12 @@
 
 using System.Net;
 using System.Net.Http;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -57,14 +59,13 @@ public class MaxRequestBodySizeTests : IISFunctionalTestBase
                     .GetOrAdd("requestFiltering")
                     .GetOrAdd("requestLimits", "maxAllowedContentLength", "1");
             });
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBody", new StringContent("test"));
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // IIS either returns a 404 or a 413 based on versions of IIS.
-            // Check for both as we don't know which specific patch version.
-            Assert.True(result.StatusCode == HttpStatusCode.NotFound || result.StatusCode == HttpStatusCode.RequestEntityTooLarge);
-        });
+        var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBody", new StringContent("test"));
+
+        // IIS either returns a 404 or a 413 based on versions of IIS.
+        // Check for both as we don't know which specific patch version.
+        Assert.True(result.StatusCode == HttpStatusCode.NotFound || result.StatusCode == HttpStatusCode.RequestEntityTooLarge);
     }
 
     [ConditionalFact]
@@ -81,11 +82,11 @@ public class MaxRequestBodySizeTests : IISFunctionalTestBase
                     .GetOrAdd("requestFiltering")
                     .GetOrAdd("requestLimits", "maxAllowedContentLength", "100000000");
             });
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBodyLarger", new StringContent(new string('a', 100000000)));
-            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBodyLarger", new StringContent(new string('a', 100000000)));
+
+        Assert.Equal(HttpStatusCode.OK, result.StatusCode);
     }
 
     [ConditionalFact]
@@ -102,11 +103,11 @@ public class MaxRequestBodySizeTests : IISFunctionalTestBase
                     .GetOrAdd("requestFiltering")
                     .GetOrAdd("requestLimits", "maxAllowedContentLength", "4294967295");
             });
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBodyLarger", new StringContent(new string('a', 10000)));
-            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var result = await deploymentResult.HttpClient.PostAsync("/ReadRequestBodyLarger", new StringContent(new string('a', 10000)));
+
+        Assert.Equal(HttpStatusCode.OK, result.StatusCode);
     }
 
     [ConditionalFact]
@@ -114,20 +115,19 @@ public class MaxRequestBodySizeTests : IISFunctionalTestBase
     public async Task IISRejectsContentLengthTooLargeByDefault()
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
-        await RunTest(deploymentParameters, async deploymentResult =>
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        using (var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port))
         {
-            using (var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port))
-            {
-                await connection.Send(
-                    "POST /HelloWorld HTTP/1.1",
-                    $"Content-Length: 30000001",
-                    "Host: localhost",
-                    "",
-                    "A");
-                var requestLine = await connection.ReadLineAsync();
-                Assert.True(requestLine.Contains("404") || requestLine.Contains("413"));
-            }
-        });
+            await connection.Send(
+                "POST /HelloWorld HTTP/1.1",
+                $"Content-Length: 30000001",
+                "Host: localhost",
+                "",
+                "A");
+            var requestLine = await connection.ReadLineAsync();
+            Assert.True(requestLine.Contains("404") || requestLine.Contains("413"));
+        }
     }
 
     [ConditionalFact]
@@ -149,19 +149,18 @@ public class MaxRequestBodySizeTests : IISFunctionalTestBase
                     .GetOrAdd("requestFiltering")
                     .GetOrAdd("requestLimits", "maxAllowedContentLength", "1");
             });
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.PostAsync("/IncreaseRequestLimit", new StringContent("1"));
-            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            StopServer();
+        var result = await deploymentResult.HttpClient.PostAsync("/IncreaseRequestLimit", new StringContent("1"));
+        Assert.Equal(HttpStatusCode.OK, result.StatusCode);
 
-            if (deploymentParameters.ServerType == ServerType.IISExpress)
-            {
-                Assert.Single(TestSink.Writes, w => w.Message.Contains("Increasing the MaxRequestBodySize conflicts with the max value for IIS limit maxAllowedContentLength." +
-                    " HTTP requests that have a content length greater than maxAllowedContentLength will still be rejected by IIS." +
-                    " You can disable the limit by either removing or setting the maxAllowedContentLength value to a higher limit."));
-            }
-        });
+        StopServer();
+
+        if (deploymentParameters.ServerType == ServerType.IISExpress)
+        {
+            Assert.Single(TestSink.Writes, w => w.Message.Contains("Increasing the MaxRequestBodySize conflicts with the max value for IIS limit maxAllowedContentLength." +
+                " HTTP requests that have a content length greater than maxAllowedContentLength will still be rejected by IIS." +
+                " You can disable the limit by either removing or setting the maxAllowedContentLength value to a higher limit."));
+        }
     }
 }

+ 31 - 30
src/Servers/IIS/IIS/test/Common.FunctionalTests/Latin1Tests.cs

@@ -1,12 +1,15 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
 using System.Net;
 using System.Net.Http;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -37,16 +40,15 @@ public class Latin1Tests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
         deploymentParameters.TransformArguments((a, _) => $"{a} AddLatin1");
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var client = new HttpClient(new LoggingHandler(new WinHttpHandler() { SendTimeout = TimeSpan.FromMinutes(3) }, deploymentResult.Logger));
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var client = new HttpClient(new LoggingHandler(new WinHttpHandler() { SendTimeout = TimeSpan.FromMinutes(3) }, deploymentResult.Logger));
 
-            var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{deploymentResult.ApplicationBaseUri}Latin1");
-            requestMessage.Headers.Add("foo", "£");
+        var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{deploymentResult.ApplicationBaseUri}Latin1");
+        requestMessage.Headers.Add("foo", "£");
 
-            var result = await client.SendAsync(requestMessage);
-            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
-        });
+        var result = await client.SendAsync(requestMessage);
+        Assert.Equal(HttpStatusCode.OK, result.StatusCode);
     }
 
     [ConditionalFact]
@@ -56,16 +58,15 @@ public class Latin1Tests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
         deploymentParameters.TransformArguments((a, _) => $"{a}");
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var client = new HttpClient(new LoggingHandler(new WinHttpHandler() { SendTimeout = TimeSpan.FromMinutes(3) }, deploymentResult.Logger));
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var client = new HttpClient(new LoggingHandler(new WinHttpHandler() { SendTimeout = TimeSpan.FromMinutes(3) }, deploymentResult.Logger));
 
-            var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{deploymentResult.ApplicationBaseUri}InvalidCharacter");
-            requestMessage.Headers.Add("foo", "£");
+        var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{deploymentResult.ApplicationBaseUri}InvalidCharacter");
+        requestMessage.Headers.Add("foo", "£");
 
-            var result = await client.SendAsync(requestMessage);
-            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
-        });
+        var result = await client.SendAsync(requestMessage);
+        Assert.Equal(HttpStatusCode.OK, result.StatusCode);
     }
 
     [ConditionalFact]
@@ -74,20 +75,20 @@ public class Latin1Tests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
         deploymentParameters.TransformArguments((a, _) => $"{a} AddLatin1");
-        await RunTest(deploymentParameters, async deploymentResult =>
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        using (var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port))
         {
-            using (var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port))
-            {
-                await connection.Send(
-                    "GET /ReadAndFlushEcho HTTP/1.1",
-                    "Host: localhost",
-                    "Connection: close",
-                    "foo: £\0a",
-                    "",
-                    "");
-
-                await connection.ReceiveStartsWith("HTTP/1.1 400 Bad Request");
-            }
-        });
+            await connection.Send(
+                "GET /ReadAndFlushEcho HTTP/1.1",
+                "Host: localhost",
+                "Connection: close",
+                "foo: £\0a",
+                "",
+                "");
+
+            await connection.ReceiveStartsWith("HTTP/1.1 400 Bad Request");
+        }
     }
 }

+ 126 - 104
src/Servers/IIS/IIS/test/Common.FunctionalTests/LoggingTests.cs

@@ -1,12 +1,17 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.Diagnostics;
 using System.Globalization;
+using System.IO;
 using System.Text.RegularExpressions;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -60,15 +65,18 @@ public class LoggingTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
         deploymentParameters.EnableLogging(LogFolderPath);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await Helpers.AssertStarts(deploymentResult, path);
-            StopServer();
-            var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, LogFolderPath), Logger);
-            Assert.Contains("TEST MESSAGE", contents);
-            Assert.DoesNotContain("\r\n\r\n", contents);
-            Assert.Contains("\r\n", contents);
-        });
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await Helpers.AssertStarts(deploymentResult, path);
+
+        StopServer();
+
+        var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, LogFolderPath), Logger);
+
+        Assert.Contains("TEST MESSAGE", contents);
+        Assert.DoesNotContain("\r\n\r\n", contents);
+        Assert.Contains("\r\n", contents);
     }
 
     // Move to separate file
@@ -77,20 +85,22 @@ public class LoggingTests : IISFunctionalTestBase
     public async Task InvalidFilePathForLogs_ServerStillRuns(TestVariant variant)
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
+
         deploymentParameters.WebConfigActionList.Add(
             WebConfigHelpers.AddOrModifyAspNetCoreSection("stdoutLogEnabled", "true"));
         deploymentParameters.WebConfigActionList.Add(
             WebConfigHelpers.AddOrModifyAspNetCoreSection("stdoutLogFile", Path.Combine("Q:", "std")));
-        await RunTest(deploymentParameters, async deploymentResult =>
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await Helpers.AssertStarts(deploymentResult, "HelloWorld");
+
+        StopServer();
+        if (variant.HostingModel == HostingModel.InProcess)
         {
-            await Helpers.AssertStarts(deploymentResult, "HelloWorld");
-            StopServer();
-            if (variant.HostingModel == HostingModel.InProcess)
-            {
-                // Error is getting logged twice, from shim and handler
-                EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.CouldNotStartStdoutFileRedirection("Q:\\std", deploymentResult), Logger, allowMultiple: true);
-            }
-        });
+            // Error is getting logged twice, from shim and handler
+            EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.CouldNotStartStdoutFileRedirection("Q:\\std", deploymentResult), Logger, allowMultiple: true);
+        }
     }
 
     [ConditionalTheory]
@@ -101,11 +111,12 @@ public class LoggingTests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
         deploymentParameters.HandlerSettings["debugLevel"] = "file";
         deploymentParameters.HandlerSettings["debugFile"] = "subdirectory\\debug.txt";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await deploymentResult.HttpClient.GetAsync("/");
-            AssertLogs(Path.Combine(deploymentResult.ContentRoot, "subdirectory", "debug.txt"));
-        });
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await deploymentResult.HttpClient.GetAsync("/");
+
+        AssertLogs(Path.Combine(deploymentResult.ContentRoot, "subdirectory", "debug.txt"));
     }
 
     [ConditionalTheory]
@@ -114,11 +125,12 @@ public class LoggingTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
         deploymentParameters.HandlerSettings["debugLevel"] = "file";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await deploymentResult.HttpClient.GetAsync("/");
-            AssertLogs(Path.Combine(deploymentResult.ContentRoot, "aspnetcore-debug.log"));
-        });
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await deploymentResult.HttpClient.GetAsync("/");
+
+        AssertLogs(Path.Combine(deploymentResult.ContentRoot, "aspnetcore-debug.log"));
     }
 
     [ConditionalTheory]
@@ -130,11 +142,11 @@ public class LoggingTests : IISFunctionalTestBase
         deploymentParameters.EnvironmentVariables["ASPNETCORE_MODULE_DEBUG"] = "file";
         // Add empty debugFile handler setting to prevent IIS deployer from overriding debug settings
         deploymentParameters.HandlerSettings["debugFile"] = "";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await deploymentResult.HttpClient.GetAsync("/");
-            AssertLogs(Path.Combine(deploymentResult.ContentRoot, "aspnetcore-debug.log"));
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await deploymentResult.HttpClient.GetAsync("/");
+
+        AssertLogs(Path.Combine(deploymentResult.ContentRoot, "aspnetcore-debug.log"));
     }
 
     [ConditionalTheory]
@@ -150,17 +162,17 @@ public class LoggingTests : IISFunctionalTestBase
             var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
             deploymentParameters.EnvironmentVariables["ASPNETCORE_MODULE_DEBUG_FILE"] = firstTempFile;
             deploymentParameters.AddDebugLogToWebConfig(secondTempFile);
-            await RunTest(deploymentParameters, async deploymentResult =>
-            {
-                var response = await deploymentResult.HttpClient.GetAsync("/");
 
-                StopServer();
-                var logContents = Helpers.ReadAllTextFromFile(firstTempFile, Logger);
+            var deploymentResult = await DeployAsync(deploymentParameters);
+
+            var response = await deploymentResult.HttpClient.GetAsync("/");
 
-                Assert.Contains("Switching debug log files to", logContents);
+            StopServer();
+            var logContents = Helpers.ReadAllTextFromFile(firstTempFile, Logger);
 
-                AssertLogs(secondTempFile);
-            });
+            Assert.Contains("Switching debug log files to", logContents);
+
+            AssertLogs(secondTempFile);
         }
         finally
         {
@@ -193,15 +205,17 @@ public class LoggingTests : IISFunctionalTestBase
         var logFolderPath = LogFolderPath + "\\彡⾔";
         deploymentParameters.EnableLogging(logFolderPath);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync(path);
-            Assert.False(response.IsSuccessStatusCode);
-            StopServer();
-            var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, logFolderPath), Logger);
-            Assert.Contains("彡⾔", contents);
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessThreadExitStdOut(deploymentResult, "12", "(.*)彡⾔(.*)"), Logger);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync(path);
+
+        Assert.False(response.IsSuccessStatusCode);
+
+        StopServer();
+
+        var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, logFolderPath), Logger);
+        Assert.Contains("彡⾔", contents);
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessThreadExitStdOut(deploymentResult, "12", "(.*)彡⾔(.*)"), Logger);
     }
 
     [ConditionalTheory]
@@ -209,13 +223,15 @@ public class LoggingTests : IISFunctionalTestBase
     public async Task OnlyOneFileCreatedWithProcessStartTime(TestVariant variant)
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(variant);
+
         deploymentParameters.EnableLogging(LogFolderPath);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await Helpers.AssertStarts(deploymentResult, "ConsoleWrite");
-            StopServer();
-            Assert.Single(Directory.GetFiles(LogFolderPath), Helpers.GetExpectedLogName(deploymentResult, LogFolderPath));
-        });
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+        await Helpers.AssertStarts(deploymentResult, "ConsoleWrite");
+
+        StopServer();
+
+        Assert.Single(Directory.GetFiles(LogFolderPath), Helpers.GetExpectedLogName(deploymentResult, LogFolderPath));
     }
 
     [ConditionalFact]
@@ -223,12 +239,13 @@ public class LoggingTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
         deploymentParameters.TransformArguments((a, _) => $"{a} ConsoleWriteSingle");
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("Test");
-            StopServer();
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, "Wow!"), Logger);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("Test");
+
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, "Wow!"), Logger);
     }
 
     [ConditionalFact]
@@ -238,12 +255,13 @@ public class LoggingTests : IISFunctionalTestBase
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
         deploymentParameters.HandlerSettings["enableOutOfProcessConsoleRedirection"] = "false";
         deploymentParameters.TransformArguments((a, _) => $"{a} ConsoleWriteSingle");
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("Test");
-            StopServer();
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, ""), Logger);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("Test");
+
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, ""), Logger);
     }
 
     [ConditionalFact]
@@ -251,12 +269,13 @@ public class LoggingTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
         deploymentParameters.TransformArguments((a, _) => $"{a} ConsoleWrite30Kb");
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("Test");
-            StopServer();
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, new string('a', 30000)), Logger);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("Test");
+
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.OutOfProcessFailedToStart(deploymentResult, new string('a', 30000)), Logger);
     }
 
     [ConditionalTheory]
@@ -265,18 +284,22 @@ public class LoggingTests : IISFunctionalTestBase
     public async Task CheckStdoutLoggingToPipeWithFirstWrite(string path)
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
+
         var firstWriteString = "TEST MESSAGE";
+
         deploymentParameters.TransformArguments((a, _) => $"{a} {path}");
-        await RunTest(deploymentParameters, async deploymentResult =>
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await Helpers.AssertStarts(deploymentResult);
+
+        StopServer();
+
+        if (deploymentParameters.ServerType == ServerType.IISExpress)
         {
-            await Helpers.AssertStarts(deploymentResult);
-            StopServer();
-            if (deploymentParameters.ServerType == ServerType.IISExpress)
-            {
-                // We can't read stdout logs from IIS as they aren't redirected.
-                Assert.Contains(TestSink.Writes, context => context.Message.Contains(firstWriteString));
-            }
-        });
+            // We can't read stdout logs from IIS as they aren't redirected.
+            Assert.Contains(TestSink.Writes, context => context.Message.Contains(firstWriteString));
+        }
     }
 
     [ConditionalFact]
@@ -284,29 +307,28 @@ public class LoggingTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters();
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await Helpers.AssertStarts(deploymentResult);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            StopServer();
+        await Helpers.AssertStarts(deploymentResult);
+
+        StopServer();
+
+        var aspnetcorev2Log = TestSink.Writes.First(w => w.Message.Contains("Description: IIS ASP.NET Core Module V2. Commit:"));
+        var aspnetcoreHandlerLog = TestSink.Writes.First(w => w.Message.Contains("Description: IIS ASP.NET Core Module V2 Request Handler. Commit:"));
 
-            var aspnetcorev2Log = TestSink.Writes.First(w => w.Message.Contains("Description: IIS ASP.NET Core Module V2. Commit:"));
-            var aspnetcoreHandlerLog = TestSink.Writes.First(w => w.Message.Contains("Description: IIS ASP.NET Core Module V2 Request Handler. Commit:"));
-
-            var processIdPattern = new Regex("Process Id: (\\d+)\\.", RegexOptions.Singleline);
-            var processIdMatch = processIdPattern.Match(aspnetcorev2Log.Message);
-            Assert.True(processIdMatch.Success, $"'{processIdPattern}' did not match '{aspnetcorev2Log}'");
-            var processId = int.Parse(processIdMatch.Groups[1].Value, CultureInfo.InvariantCulture);
-
-            if (DeployerSelector.HasNewShim)
-            {
-                AssertTimestampAndPIDPrefix(processId, aspnetcorev2Log.Message);
-            }
-            if (DeployerSelector.HasNewHandler)
-            {
-                AssertTimestampAndPIDPrefix(processId, aspnetcoreHandlerLog.Message);
-            }
-        });
+        var processIdPattern = new Regex("Process Id: (\\d+)\\.", RegexOptions.Singleline);
+        var processIdMatch = processIdPattern.Match(aspnetcorev2Log.Message);
+        Assert.True(processIdMatch.Success, $"'{processIdPattern}' did not match '{aspnetcorev2Log}'");
+        var processId = int.Parse(processIdMatch.Groups[1].Value, CultureInfo.InvariantCulture);
+
+        if (DeployerSelector.HasNewShim)
+        {
+            AssertTimestampAndPIDPrefix(processId, aspnetcorev2Log.Message);
+        }
+        if (DeployerSelector.HasNewHandler)
+        {
+            AssertTimestampAndPIDPrefix(processId, aspnetcoreHandlerLog.Message);
+        }
     }
 
     private static string ReadLogs(string logPath)

+ 26 - 24
src/Servers/IIS/IIS/test/Common.FunctionalTests/MultiApplicationTests.cs

@@ -1,11 +1,16 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
 using System.Xml.Linq;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -37,12 +42,10 @@ public class MultiApplicationTests : IISFunctionalTestBase
     {
         var parameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
         parameters.ServerConfigActionList.Add(DuplicateApplication);
-        await RunTest(parameters, async result =>
-        {
-            var id1 = await result.HttpClient.GetStringAsync("/app1/ProcessId");
-            var id2 = await result.HttpClient.GetStringAsync("/app2/ProcessId");
-            Assert.NotEqual(id2, id1);
-        });
+        var result = await DeployAsync(parameters);
+        var id1 = await result.HttpClient.GetStringAsync("/app1/ProcessId");
+        var id2 = await result.HttpClient.GetStringAsync("/app2/ProcessId");
+        Assert.NotEqual(id2, id1);
     }
 
     [ConditionalFact]
@@ -73,25 +76,24 @@ public class MultiApplicationTests : IISFunctionalTestBase
     {
         var parameters = Fixture.GetBaseDeploymentParameters(firstApp);
         parameters.ServerConfigActionList.Add(DuplicateApplication);
-        await RunTest(parameters, async result =>
+        var result = await DeployAsync(parameters);
+
+        // Modify hosting model of other app to be the opposite
+        var otherApp = firstApp == HostingModel.InProcess ? HostingModel.OutOfProcess : HostingModel.InProcess;
+        SetHostingModel(_publishedApplication.Path, otherApp);
+
+        var result1 = await result.HttpClient.GetAsync("/app1/HelloWorld");
+        var result2 = await result.HttpClient.GetAsync("/app2/HelloWorld");
+        Assert.Equal(200, (int)result1.StatusCode);
+        Assert.Equal(500, (int)result2.StatusCode);
+        StopServer();
+
+        if (DeployerSelector.HasNewShim)
         {
-            // Modify hosting model of other app to be the opposite
-            var otherApp = firstApp == HostingModel.InProcess ? HostingModel.OutOfProcess : HostingModel.InProcess;
-            SetHostingModel(_publishedApplication.Path, otherApp);
-
-            var result1 = await result.HttpClient.GetAsync("/app1/HelloWorld");
-            var result2 = await result.HttpClient.GetAsync("/app2/HelloWorld");
-            Assert.Equal(200, (int)result1.StatusCode);
-            Assert.Equal(500, (int)result2.StatusCode);
-            StopServer();
-
-            if (DeployerSelector.HasNewShim)
-            {
-                Assert.Contains("500.34", await result2.Content.ReadAsStringAsync());
-            }
-
-            EventLogHelpers.VerifyEventLogEvent(result, "Mixed hosting model is not supported.", Logger);
-        });
+            Assert.Contains("500.34", await result2.Content.ReadAsStringAsync());
+        }
+
+        EventLogHelpers.VerifyEventLogEvent(result, "Mixed hosting model is not supported.", Logger);
     }
 
     private void SetHostingModel(string directory, HostingModel model)

+ 11 - 9
src/Servers/IIS/IIS/test/Common.FunctionalTests/WindowsAuthTests.cs

@@ -1,11 +1,14 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
 using System.Net.Http;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -45,14 +48,13 @@ public class WindowsAuthTests : IISFunctionalTestBase
         deploymentParameters.SetWindowsAuth();
 
         // The default in hosting sets windows auth to true.
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var client = deploymentResult.CreateClient(new HttpClientHandler { UseDefaultCredentials = true });
-            var response = await client.GetAsync("/Auth");
-            var responseText = await response.Content.ReadAsStringAsync();
-
-            Assert.StartsWith("Windows:", responseText);
-            Assert.Contains(Environment.UserName, responseText);
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var client = deploymentResult.CreateClient(new HttpClientHandler { UseDefaultCredentials = true });
+        var response = await client.GetAsync("/Auth");
+        var responseText = await response.Content.ReadAsStringAsync();
+
+        Assert.StartsWith("Windows:", responseText);
+        Assert.Contains(Environment.UserName, responseText);
     }
 }

+ 234 - 235
src/Servers/IIS/IIS/test/Common.LongTests/ShutdownTests.cs

@@ -41,14 +41,15 @@ public class ShutdownTests : IISFunctionalTestBase
         deploymentParameters.WebConfigActionList.Add(
             WebConfigHelpers.AddOrModifyAspNetCoreSection("shutdownTimeLimit", "1"));
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            Assert.Equal("Hello World", await deploymentResult.HttpClient.GetStringAsync("/HelloWorld"));
-            StopServer();
-            EventLogHelpers.VerifyEventLogEvents(deploymentResult,
-                EventLogHelpers.InProcessStarted(deploymentResult),
-                EventLogHelpers.InProcessFailedToStop(deploymentResult, ""));
-        });
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        Assert.Equal("Hello World", await deploymentResult.HttpClient.GetStringAsync("/HelloWorld"));
+
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvents(deploymentResult,
+            EventLogHelpers.InProcessStarted(deploymentResult),
+            EventLogHelpers.InProcessFailedToStop(deploymentResult, ""));
     }
 
     [ConditionalTheory]
@@ -59,18 +60,17 @@ public class ShutdownTests : IISFunctionalTestBase
         // Canceled token doesn't affect shutdown, in-proc doesn't handle ungraceful shutdown
         // IIS's ShutdownTimeLimit will handle that.
         var parameters = Fixture.GetBaseDeploymentParameters();
-        await RunTest(parameters, async deploymentResult =>
+        var deploymentResult = await DeployAsync(parameters);
+        try
         {
-            try
-            {
-                await deploymentResult.HttpClient.GetAsync(path);
-            }
-            catch (HttpRequestException ex) when (ex.InnerException is IOException)
-            {
-                // Server might close a connection before request completes
-            }
-            deploymentResult.AssertWorkerProcessStop();
-        });
+            await deploymentResult.HttpClient.GetAsync(path);
+        }
+        catch (HttpRequestException ex) when (ex.InnerException is IOException)
+        {
+            // Server might close a connection before request completes
+        }
+
+        deploymentResult.AssertWorkerProcessStop();
     }
 
     [ConditionalFact]
@@ -88,49 +88,47 @@ public class ShutdownTests : IISFunctionalTestBase
     [RequiresNewShim]
     public async Task AppOfflineDroppedWhileSiteIsDown_SiteReturns503_OutOfProcess()
     {
-        await RunTest(HostingModel.OutOfProcess, async deploymentResult =>
-        {
-            AddAppOffline(deploymentResult.ContentRoot);
-            await AssertAppOffline(deploymentResult);
-            DeletePublishOutput(deploymentResult);
-        });
+        var deploymentResult = await DeployApp(HostingModel.OutOfProcess);
+
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await AssertAppOffline(deploymentResult);
+        DeletePublishOutput(deploymentResult);
     }
 
     [ConditionalFact]
     public async Task LockedAppOfflineDroppedWhileSiteIsDown_SiteReturns503_InProcess()
     {
-        await RunTest(HostingModel.InProcess, async deploymentResult =>
+        var deploymentResult = await DeployApp(HostingModel.InProcess);
+
+        // Add app_offline without shared access
+        using (var stream = File.Open(Path.Combine(deploymentResult.ContentRoot, "app_offline.htm"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
+        using (var writer = new StreamWriter(stream))
         {
-            // Add app_offline without shared access
-            using (var stream = File.Open(Path.Combine(deploymentResult.ContentRoot, "app_offline.htm"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
-            using (var writer = new StreamWriter(stream))
-            {
-                await writer.WriteLineAsync("App if offline but you wouldn't see this message");
-                await writer.FlushAsync();
-                await AssertAppOffline(deploymentResult, "");
-            }
+            await writer.WriteLineAsync("App if offline but you wouldn't see this message");
+            await writer.FlushAsync();
+            await AssertAppOffline(deploymentResult, "");
+        }
 
-            DeletePublishOutput(deploymentResult);
-        });
+        DeletePublishOutput(deploymentResult);
     }
 
     [ConditionalFact]
     [RequiresNewShim]
     public async Task LockedAppOfflineDroppedWhileSiteIsDown_SiteReturns503_OutOfProcess()
     {
-        await RunTest(HostingModel.OutOfProcess, async deploymentResult =>
+        var deploymentResult = await DeployApp(HostingModel.OutOfProcess);
+
+        // Add app_offline without shared access
+        using (var stream = File.Open(Path.Combine(deploymentResult.ContentRoot, "app_offline.htm"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
+        using (var writer = new StreamWriter(stream))
         {
-            // Add app_offline without shared access
-            using (var stream = File.Open(Path.Combine(deploymentResult.ContentRoot, "app_offline.htm"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
-            using (var writer = new StreamWriter(stream))
-            {
-                await writer.WriteLineAsync("App if offline but you wouldn't see this message");
-                await writer.FlushAsync();
-                await AssertAppOffline(deploymentResult, "");
-            }
+            await writer.WriteLineAsync("App if offline but you wouldn't see this message");
+            await writer.FlushAsync();
+            await AssertAppOffline(deploymentResult, "");
+        }
 
-            DeletePublishOutput(deploymentResult);
-        });
+        DeletePublishOutput(deploymentResult);
     }
 
     [ConditionalFact]
@@ -138,17 +136,17 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(hostingModel: HostingModel.InProcess);
         deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", "nonexistent"));
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.GetAsync("/");
-            Assert.Equal(500, (int)result.StatusCode);
-            Assert.Contains("500.0", await result.Content.ReadAsStringAsync());
 
-            AddAppOffline(deploymentResult.ContentRoot);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            await AssertAppOffline(deploymentResult);
-            DeletePublishOutput(deploymentResult);
-        });
+        var result = await deploymentResult.HttpClient.GetAsync("/");
+        Assert.Equal(500, (int)result.StatusCode);
+        Assert.Contains("500.0", await result.Content.ReadAsStringAsync());
+
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await AssertAppOffline(deploymentResult);
+        DeletePublishOutput(deploymentResult);
     }
 
     [ConditionalFact]
@@ -157,35 +155,34 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(hostingModel: HostingModel.OutOfProcess);
         deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("processPath", "nonexistent"));
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.GetAsync("/");
-            Assert.Equal(502, (int)result.StatusCode);
-            Assert.Contains("502.5", await result.Content.ReadAsStringAsync());
 
-            AddAppOffline(deploymentResult.ContentRoot);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            await AssertAppOffline(deploymentResult);
-            DeletePublishOutput(deploymentResult);
-        });
+        var result = await deploymentResult.HttpClient.GetAsync("/");
+        Assert.Equal(502, (int)result.StatusCode);
+        Assert.Contains("502.5", await result.Content.ReadAsStringAsync());
+
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await AssertAppOffline(deploymentResult);
+        DeletePublishOutput(deploymentResult);
     }
 
     [ConditionalFact]
     public async Task AppOfflineDroppedWhileSiteFailedToStartInRequestHandler_SiteStops_InProcess()
     {
-        await RunTest(HostingModel.InProcess, async deploymentResult =>
-        {
-            // Set file content to empty so it fails at runtime
-            File.WriteAllText(Path.Combine(deploymentResult.ContentRoot, "Microsoft.AspNetCore.Server.IIS.dll"), "");
+        var deploymentResult = await DeployApp(HostingModel.InProcess);
 
-            var result = await deploymentResult.HttpClient.GetAsync("/");
-            Assert.Equal(500, (int)result.StatusCode);
-            Assert.Contains("500.30", await result.Content.ReadAsStringAsync());
+        // Set file content to empty so it fails at runtime
+        File.WriteAllText(Path.Combine(deploymentResult.ContentRoot, "Microsoft.AspNetCore.Server.IIS.dll"), "");
 
-            AddAppOffline(deploymentResult.ContentRoot);
+        var result = await deploymentResult.HttpClient.GetAsync("/");
+        Assert.Equal(500, (int)result.StatusCode);
+        Assert.Contains("500.30", await result.Content.ReadAsStringAsync());
 
-            await deploymentResult.AssertRecycledAsync(() => AssertAppOffline(deploymentResult));
-        });
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await deploymentResult.AssertRecycledAsync(() => AssertAppOffline(deploymentResult));
     }
 
     [ConditionalFact]
@@ -196,69 +193,69 @@ public class ShutdownTests : IISFunctionalTestBase
         // and graceful shutdown occurs.
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(Fixture.InProcessTestSite);
         deploymentParameters.TransformArguments((a, _) => $"{a} IncreaseShutdownLimit");
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var result = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
 
-            // Send two requests that will hang until data is sent from the client.
-            var connectionList = new List<TestConnection>();
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            for (var i = 0; i < 2; i++)
-            {
-                var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port);
-                await connection.Send(
-                    "POST /ReadAndCountRequestBody HTTP/1.1",
-                    "Content-Length: 1",
-                    "Host: localhost",
-                    "Connection: close",
-                    "",
-                    "");
-
-                await connection.Receive(
-                    "HTTP/1.1 200 OK", "");
-                await connection.ReceiveHeaders();
-                await connection.Receive("1", $"{i + 1}");
-                connectionList.Add(connection);
-            }
+        var result = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
 
-            // Send a request that will end once app lifetime is triggered (ApplicationStopping cts).
-            var statusConnection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port);
+        // Send two requests that will hang until data is sent from the client.
+        var connectionList = new List<TestConnection>();
 
-            await statusConnection.Send(
-                "GET /WaitForAppToStartShuttingDown HTTP/1.1",
+        for (var i = 0; i < 2; i++)
+        {
+            var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port);
+            await connection.Send(
+                "POST /ReadAndCountRequestBody HTTP/1.1",
+                "Content-Length: 1",
                 "Host: localhost",
                 "Connection: close",
                 "",
                 "");
 
-            await statusConnection.Receive("HTTP/1.1 200 OK",
-                "");
+            await connection.Receive(
+                "HTTP/1.1 200 OK", "");
+            await connection.ReceiveHeaders();
+            await connection.Receive("1", $"{i + 1}");
+            connectionList.Add(connection);
+        }
 
-            await statusConnection.ReceiveHeaders();
+        // Send a request that will end once app lifetime is triggered (ApplicationStopping cts).
+        var statusConnection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port);
 
-            // Receiving some data means we are currently waiting for IHostApplicationLifetime.
-            await statusConnection.Receive("5",
-                "test1",
-                "");
+        await statusConnection.Send(
+            "GET /WaitForAppToStartShuttingDown HTTP/1.1",
+            "Host: localhost",
+            "Connection: close",
+            "",
+            "");
 
-            AddAppOffline(deploymentResult.ContentRoot);
+        await statusConnection.Receive("HTTP/1.1 200 OK",
+            "");
 
-            // Receive the rest of all open connections.
-            await statusConnection.Receive("5", "test2", "");
+        await statusConnection.ReceiveHeaders();
 
-            for (var i = 0; i < 2; i++)
-            {
-                await connectionList[i].Send("a", "");
-                await connectionList[i].Receive("", "4", "done");
-                connectionList[i].Dispose();
-            }
+        // Receiving some data means we are currently waiting for IHostApplicationLifetime.
+        await statusConnection.Receive("5",
+            "test1",
+            "");
 
-            deploymentResult.AssertWorkerProcessStop();
+        AddAppOffline(deploymentResult.ContentRoot);
 
-            // Shutdown should be graceful here!
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult,
-                EventLogHelpers.InProcessShutdown(), Logger);
-        });
+        // Receive the rest of all open connections.
+        await statusConnection.Receive("5", "test2", "");
+
+        for (var i = 0; i < 2; i++)
+        {
+            await connectionList[i].Send("a", "");
+            await connectionList[i].Receive("", "4", "done");
+            connectionList[i].Dispose();
+        }
+
+        deploymentResult.AssertWorkerProcessStop();
+
+        // Shutdown should be graceful here!
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult,
+            EventLogHelpers.InProcessShutdown(), Logger);
     }
 
     [ConditionalFact]
@@ -290,26 +287,30 @@ public class ShutdownTests : IISFunctionalTestBase
     [ConditionalFact]
     public async Task AppOfflineDropped_CanRemoveAppOfflineAfterAddingAndSiteWorks_InProcess()
     {
-        await RunTest(HostingModel.InProcess, async deploymentResult =>
-        {
-            AddAppOffline(deploymentResult.ContentRoot);
-            await AssertAppOffline(deploymentResult);
-            RemoveAppOffline(deploymentResult.ContentRoot);
-            await AssertRunning(deploymentResult);
-        });
+        var deploymentResult = await DeployApp(HostingModel.InProcess);
+
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await AssertAppOffline(deploymentResult);
+
+        RemoveAppOffline(deploymentResult.ContentRoot);
+
+        await AssertRunning(deploymentResult);
     }
 
     [ConditionalFact]
     [RequiresNewShim]
     public async Task AppOfflineDropped_CanRemoveAppOfflineAfterAddingAndSiteWorks_OutOfProcess()
     {
-        await RunTest(HostingModel.OutOfProcess, async deploymentResult =>
-        {
-            AddAppOffline(deploymentResult.ContentRoot);
-            await AssertAppOffline(deploymentResult);
-            RemoveAppOffline(deploymentResult.ContentRoot);
-            await AssertRunning(deploymentResult);
-        });
+        var deploymentResult = await DeployApp(HostingModel.OutOfProcess);
+
+        AddAppOffline(deploymentResult.ContentRoot);
+
+        await AssertAppOffline(deploymentResult);
+
+        RemoveAppOffline(deploymentResult.ContentRoot);
+
+        await AssertRunning(deploymentResult);
     }
 
     [ConditionalFact]
@@ -371,15 +372,15 @@ public class ShutdownTests : IISFunctionalTestBase
     public async Task ConfigurationChangeStopsInProcess()
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.InProcess);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await deploymentResult.AssertStarts();
 
-            // Just "touching" web.config should be enough
-            deploymentResult.ModifyWebConfig(element => { });
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            await deploymentResult.AssertRecycledAsync();
-        });
+        await deploymentResult.AssertStarts();
+
+        // Just "touching" web.config should be enough
+        deploymentResult.ModifyWebConfig(element => { });
+
+        await deploymentResult.AssertRecycledAsync();
     }
 
     [ConditionalFact]
@@ -388,17 +389,16 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // Just "touching" web.config should be enough
-            deploymentResult.ModifyWebConfig(element => { });
+        var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            // Have to retry here to allow ANCM to receive notification and react to it
-            // Verify that worker process gets restarted with new process id
-            await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() != processBefore);
-        });
+        // Just "touching" web.config should be enough
+        deploymentResult.ModifyWebConfig(element => { });
+
+        // Have to retry here to allow ANCM to receive notification and react to it
+        // Verify that worker process gets restarted with new process id
+        await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() != processBefore);
     }
 
     [ConditionalFact]
@@ -406,19 +406,19 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.InProcess);
         deploymentParameters.HandlerSettings["disallowRotationOnConfigChange"] = "true";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            await deploymentResult.AssertStarts();
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // Just "touching" web.config should be enough
-            deploymentResult.ModifyWebConfig(element => { });
+        var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            // Have to retry here to allow ANCM to receive notification and react to it
-            // Verify that worker process does not get restarted with new process id
-            await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
-        });
+        await deploymentResult.AssertStarts();
+
+        // Just "touching" web.config should be enough
+        deploymentResult.ModifyWebConfig(element => { });
+
+        // Have to retry here to allow ANCM to receive notification and react to it
+        // Verify that worker process does not get restarted with new process id
+        await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
     }
 
     [ConditionalFact]
@@ -426,19 +426,19 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.InProcess);
         deploymentParameters.HandlerSettings["disallowRotationOnConfigChange"] = "true";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            await deploymentResult.AssertStarts();
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // Just "touching" applicationHost.config should be enough
-            _deployer.ModifyApplicationHostConfig(element => { });
+        var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            // Have to retry here to allow ANCM to receive notification and react to it
-            // Verify that worker process does not get restarted with new process id
-            await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
-        });
+        await deploymentResult.AssertStarts();
+
+        // Just "touching" applicationHost.config should be enough
+        _deployer.ModifyApplicationHostConfig(element => { });
+
+        // Have to retry here to allow ANCM to receive notification and react to it
+        // Verify that worker process does not get restarted with new process id
+        await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
     }
 
     [ConditionalFact]
@@ -447,38 +447,38 @@ public class ShutdownTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
         deploymentParameters.HandlerSettings["disallowRotationOnConfigChange"] = "true";
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
 
-            // Just "touching" web.config should be enough
-            deploymentResult.ModifyWebConfig(element => { });
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            // Have to retry here to allow ANCM to receive notification and react to it
-            // Verify that worker process does not get restarted with new process id
-            await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
-        });
+        var processBefore = await deploymentResult.HttpClient.GetStringAsync("/ProcessId");
+
+        // Just "touching" web.config should be enough
+        deploymentResult.ModifyWebConfig(element => { });
+
+        // Have to retry here to allow ANCM to receive notification and react to it
+        // Verify that worker process does not get restarted with new process id
+        await deploymentResult.HttpClient.RetryRequestAsync("/ProcessId", async r => await r.Content.ReadAsStringAsync() == processBefore);
     }
 
     [ConditionalFact]
     public async Task OutOfProcessToInProcessHostingModelSwitchWorks()
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            await deploymentResult.AssertStarts();
-
-            deploymentResult.ModifyWebConfig(element => element
-                .Descendants("system.webServer")
-                .Single()
-                .GetOrAdd("aspNetCore")
-                .SetAttributeValue("hostingModel", "inprocess"));
-
-            // Have to retry here to allow ANCM to receive notification and react to it
-            // Verify that inprocess application was created and started, checking the server
-            // header to see that it is running inprocess
-            await deploymentResult.HttpClient.RetryRequestAsync("/HelloWorld", r => r.Headers.Server.ToString().StartsWith("Microsoft", StringComparison.Ordinal));
-        });
+
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        await deploymentResult.AssertStarts();
+
+        deploymentResult.ModifyWebConfig(element => element
+            .Descendants("system.webServer")
+            .Single()
+            .GetOrAdd("aspNetCore")
+            .SetAttributeValue("hostingModel", "inprocess"));
+
+        // Have to retry here to allow ANCM to receive notification and react to it
+        // Verify that inprocess application was created and started, checking the server
+        // header to see that it is running inprocess
+        await deploymentResult.HttpClient.RetryRequestAsync("/HelloWorld", r => r.Headers.Server.ToString().StartsWith("Microsoft", StringComparison.Ordinal));
     }
 
     [ConditionalFact]
@@ -489,38 +489,37 @@ public class ShutdownTests : IISFunctionalTestBase
 
     private async Task ConfigurationTouchedStress(HostingModel hostingModel)
     {
-        await RunTest(Fixture.GetBaseDeploymentParameters(hostingModel), async deploymentResult =>
+        var deploymentResult = await DeployAsync(Fixture.GetBaseDeploymentParameters(hostingModel));
+
+        await deploymentResult.AssertStarts();
+        var load = Helpers.StressLoad(deploymentResult.HttpClient, "/HelloWorld", response =>
         {
-            await deploymentResult.AssertStarts();
-            var load = Helpers.StressLoad(deploymentResult.HttpClient, "/HelloWorld", response =>
-            {
-                var statusCode = (int)response.StatusCode;
-                Assert.True(statusCode == 200 || statusCode == 503, "Status code was " + statusCode);
-            });
+            var statusCode = (int)response.StatusCode;
+            Assert.True(statusCode == 200 || statusCode == 503, "Status code was " + statusCode);
+        });
 
-            for (var i = 0; i < 100; i++)
-            {
-                // ModifyWebConfig might fail if web.config is being read by IIS
-                RetryHelper.RetryOperation(
-                    () => deploymentResult.ModifyWebConfig(element => { }),
-                    e => Logger.LogError($"Failed to touch web.config : {e.Message}"),
-                    retryCount: 3,
-                    retryDelayMilliseconds: RetryDelay.Milliseconds);
-            }
+        for (var i = 0; i < 100; i++)
+        {
+            // ModifyWebConfig might fail if web.config is being read by IIS
+            RetryHelper.RetryOperation(
+                () => deploymentResult.ModifyWebConfig(element => { }),
+                e => Logger.LogError($"Failed to touch web.config : {e.Message}"),
+                retryCount: 3,
+                retryDelayMilliseconds: RetryDelay.Milliseconds);
+        }
 
-            try
-            {
-                await load;
-            }
-            catch (HttpRequestException ex) when (ex.InnerException is IOException | ex.InnerException is SocketException)
+        try
+        {
+            await load;
+        }
+        catch (HttpRequestException ex) when (ex.InnerException is IOException | ex.InnerException is SocketException)
+        {
+            // IOException in InProcess is fine, just means process stopped
+            if (hostingModel != HostingModel.InProcess)
             {
-                // IOException in InProcess is fine, just means process stopped
-                if (hostingModel != HostingModel.InProcess)
-                {
-                    throw;
-                }
+                throw;
             }
-        });
+        }
     }
 
     [ConditionalFact]
@@ -530,14 +529,14 @@ public class ShutdownTests : IISFunctionalTestBase
         try
         {
             var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.OutOfProcess);
-            await RunTest(deploymentParameters, async deploymentResult =>
-            {
-                var response = await deploymentResult.HttpClient.GetAsync("/Abort").TimeoutAfter(TimeoutExtensions.DefaultTimeoutValue);
 
-                Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
-                // 0x80072f78 ERROR_HTTP_INVALID_SERVER_RESPONSE The server returned an invalid or unrecognized response
-                Assert.Contains("0x80072f78", await response.Content.ReadAsStringAsync());
-            });
+            var deploymentResult = await DeployAsync(deploymentParameters);
+
+            var response = await deploymentResult.HttpClient.GetAsync("/Abort").TimeoutAfter(TimeoutExtensions.DefaultTimeoutValue);
+
+            Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
+            // 0x80072f78 ERROR_HTTP_INVALID_SERVER_RESPONSE The server returned an invalid or unrecognized response
+            Assert.Contains("0x80072f78", await response.Content.ReadAsStringAsync());
         }
         catch (HttpRequestException)
         {
@@ -551,11 +550,11 @@ public class ShutdownTests : IISFunctionalTestBase
         try
         {
             var deploymentParameters = Fixture.GetBaseDeploymentParameters(HostingModel.InProcess);
-            await RunTest(deploymentParameters, async deploymentResult =>
-            {
-                var response = await deploymentResult.HttpClient.GetAsync("/Abort").TimeoutAfter(TimeoutExtensions.DefaultTimeoutValue);
-                Assert.True(false, "Should not reach here");
-            });
+
+            var deploymentResult = await DeployAsync(deploymentParameters);
+            var response = await deploymentResult.HttpClient.GetAsync("/Abort").TimeoutAfter(TimeoutExtensions.DefaultTimeoutValue);
+
+            Assert.True(false, "Should not reach here");
         }
         catch (HttpRequestException)
         {

Plik diff jest za duży
+ 350 - 341
src/Servers/IIS/IIS/test/Common.LongTests/StartupTests.cs


+ 16 - 12
src/Servers/IIS/IIS/test/IIS.Shared.FunctionalTests/ApplicationInitializationTests.cs

@@ -1,10 +1,16 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+using System.IO;
+using System.ServiceProcess;
+using System.Threading;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -42,12 +48,11 @@ public class ApplicationInitializationTests : IISFunctionalTestBase
                 (args, contentRoot) => $"{args} CreateFile \"{Path.Combine(contentRoot, "Started.txt")}\"");
             EnablePreload(baseDeploymentParameters);
 
-            await RunTest(baseDeploymentParameters, async result =>
-            {
-                await Helpers.Retry(async () => await File.ReadAllTextAsync(Path.Combine(result.ContentRoot, "Started.txt")), TimeoutExtensions.DefaultTimeoutValue);
-                StopServer();
-                EventLogHelpers.VerifyEventLogEvent(result, EventLogHelpers.Started(result), Logger);
-            });
+            var result = await DeployAsync(baseDeploymentParameters);
+
+            await Helpers.Retry(async () => await File.ReadAllTextAsync(Path.Combine(result.ContentRoot, "Started.txt")), TimeoutExtensions.DefaultTimeoutValue);
+            StopServer();
+            EventLogHelpers.VerifyEventLogEvent(result, EventLogHelpers.Started(result), Logger);
         }
     }
 
@@ -74,12 +79,11 @@ public class ApplicationInitializationTests : IISFunctionalTestBase
                         .GetOrAdd("add", "initializationPage", "/CreateFile");
                 });
 
-            await RunTest(baseDeploymentParameters, async result =>
-            {
-                await Helpers.Retry(async () => await File.ReadAllTextAsync(Path.Combine(result.ContentRoot, "Started.txt")), TimeoutExtensions.DefaultTimeoutValue);
-                StopServer();
-                EventLogHelpers.VerifyEventLogEvent(result, EventLogHelpers.Started(result), Logger);
-            });
+            var result = await DeployAsync(baseDeploymentParameters);
+
+            await Helpers.Retry(async () => await File.ReadAllTextAsync(Path.Combine(result.ContentRoot, "Started.txt")), TimeoutExtensions.DefaultTimeoutValue);
+            StopServer();
+            EventLogHelpers.VerifyEventLogEvent(result, EventLogHelpers.Started(result), Logger);
         }
     }
 

+ 52 - 53
src/Servers/IIS/IIS/test/IIS.Shared.FunctionalTests/StdOutRedirectionTests.cs

@@ -1,9 +1,13 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
 using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
 using Microsoft.AspNetCore.Testing;
+using Xunit;
 
 #if !IIS_FUNCTIONALS
 using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
@@ -33,20 +37,19 @@ public class StdOutRedirectionTests : IISFunctionalTestBase
     {
         var deploymentParameters = Fixture.GetBaseDeploymentParameters(Fixture.InProcessTestSite);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            Helpers.ModifyFrameworkVersionInRuntimeConfig(deploymentResult);
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-            Assert.False(response.IsSuccessStatusCode);
+        Helpers.ModifyFrameworkVersionInRuntimeConfig(deploymentResult);
 
-            StopServer();
+        var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+        Assert.False(response.IsSuccessStatusCode);
 
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult,
-                @"Framework: 'Microsoft.NETCore.App', version '2.9.9' \(x64\)", Logger);
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult,
-                "To install missing framework, download:", Logger);
-        });
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult,
+            @"Framework: 'Microsoft.NETCore.App', version '2.9.9' \(x64\)", Logger);
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult,
+            "To install missing framework, download:", Logger);
     }
 
     [ConditionalFact]
@@ -59,24 +62,23 @@ public class StdOutRedirectionTests : IISFunctionalTestBase
 
         deploymentParameters.EnableLogging(LogFolderPath);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            Helpers.ModifyFrameworkVersionInRuntimeConfig(deploymentResult);
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        Helpers.ModifyFrameworkVersionInRuntimeConfig(deploymentResult);
 
-            var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-            Assert.False(response.IsSuccessStatusCode);
+        var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+        Assert.False(response.IsSuccessStatusCode);
 
-            StopServer();
+        StopServer();
 
-            var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, LogFolderPath), Logger);
-            var missingFrameworkString = "To install missing framework, download:";
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult,
-                @"Framework: 'Microsoft.NETCore.App', version '2.9.9' \(x64\)", Logger);
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult,
-                missingFrameworkString, Logger);
-            Assert.Contains(@"Framework: 'Microsoft.NETCore.App', version '2.9.9' (x64)", contents);
-            Assert.Contains(missingFrameworkString, contents);
-        });
+        var contents = Helpers.ReadAllTextFromFile(Helpers.GetExpectedLogName(deploymentResult, LogFolderPath), Logger);
+        var missingFrameworkString = "To install missing framework, download:";
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult,
+            @"Framework: 'Microsoft.NETCore.App', version '2.9.9' \(x64\)", Logger);
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult,
+            missingFrameworkString, Logger);
+        Assert.Contains(@"Framework: 'Microsoft.NETCore.App', version '2.9.9' (x64)", contents);
+        Assert.Contains(missingFrameworkString, contents);
     }
 
     [ConditionalFact]
@@ -92,18 +94,17 @@ public class StdOutRedirectionTests : IISFunctionalTestBase
 
         deploymentParameters.EnableLogging(LogFolderPath);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-            Assert.False(response.IsSuccessStatusCode);
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+        Assert.False(response.IsSuccessStatusCode);
 
-            StopServer();
+        StopServer();
 
-            var fileInDirectory = Directory.GetFiles(LogFolderPath).Single();
-            var contents = Helpers.ReadAllTextFromFile(fileInDirectory, Logger);
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
-            Assert.Contains("Invoked hostfxr", contents);
-        });
+        var fileInDirectory = Directory.GetFiles(LogFolderPath).Single();
+        var contents = Helpers.ReadAllTextFromFile(fileInDirectory, Logger);
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
+        Assert.Contains("Invoked hostfxr", contents);
     }
 
     [ConditionalTheory]
@@ -120,16 +121,15 @@ public class StdOutRedirectionTests : IISFunctionalTestBase
         deploymentParameters.EnvironmentVariables["COREHOST_TRACE"] = "1";
         deploymentParameters.TransformArguments((a, _) => $"{a} {path}");
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+        var deploymentResult = await DeployAsync(deploymentParameters);
 
-            Assert.False(response.IsSuccessStatusCode);
+        var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
 
-            StopServer();
+        Assert.False(response.IsSuccessStatusCode);
 
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
-        });
+        StopServer();
+
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
     }
 
     [ConditionalTheory]
@@ -149,18 +149,17 @@ public class StdOutRedirectionTests : IISFunctionalTestBase
 
         deploymentParameters.EnableLogging(LogFolderPath);
 
-        await RunTest(deploymentParameters, async deploymentResult =>
-        {
-            var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
-            Assert.False(response.IsSuccessStatusCode);
+        var deploymentResult = await DeployAsync(deploymentParameters);
+
+        var response = await deploymentResult.HttpClient.GetAsync("/HelloWorld");
+        Assert.False(response.IsSuccessStatusCode);
 
-            StopServer();
+        StopServer();
 
-            var fileInDirectory = Directory.GetFiles(LogFolderPath).First();
-            var contents = Helpers.ReadAllTextFromFile(fileInDirectory, Logger);
+        var fileInDirectory = Directory.GetFiles(LogFolderPath).First();
+        var contents = Helpers.ReadAllTextFromFile(fileInDirectory, Logger);
 
-            EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
-            Assert.Contains("Invoked hostfxr", contents);
-        });
+        EventLogHelpers.VerifyEventLogEvent(deploymentResult, "Invoked hostfxr", Logger);
+        Assert.Contains("Invoked hostfxr", contents);
     }
 }

+ 1 - 1
src/Servers/IIS/IntegrationTesting.IIS/src/IISDeployer.cs

@@ -397,7 +397,7 @@ public class IISDeployer : IISDeployerBase
                         Logger.LogInformation($"Stopping pool, state: {state}");
                     }
                 }
-
+                
                 // Make sure all sites are stopped
                 foreach (var site in serverManager.Sites)
                 {

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików