Exemplo n.º 1
0
    /// <summary>
    /// Write <paramref name="content"/> to file that will become <paramref name="resourceName"/> in
    /// <paramref name="assembly"/> the next time the project is built. Does nothing if
    /// <paramref name="previousContent"/> and <paramref name="content"/> already match.
    /// </summary>
    /// <param name="assembly">The <see cref="Assembly"/> containing <paramref name="resourceName"/>.</param>
    /// <param name="resourceName">
    /// Name of the manifest resource in <paramref name="assembly"/>. A path relative to the test project
    /// directory.
    /// </param>
    /// <param name="previousContent">
    /// Current content of <paramref name="resourceName"/>. <c>null</c> if <paramref name="resourceName"/> does
    /// not currently exist in <paramref name="assembly"/>.
    /// </param>
    /// <param name="content">
    /// New content of <paramref name="resourceName"/> in <paramref name="assembly"/>.
    /// </param>
    private static void UpdateFile(Assembly assembly, string resourceName, string previousContent, string content)
    {
        if (!GenerateBaselines)
        {
            throw new NotSupportedException("Calling UpdateFile is not supported when GenerateBaselines=false");
        }

        // Normalize line endings to '\r\n' for comparison. This removes Environment.NewLine from the equation. Not
        // worth updating files just because we generate baselines on a different system.
        var normalizedPreviousContent = previousContent?.Replace("\r", "").Replace("\n", "\r\n");
        var normalizedContent         = content.Replace("\r", "").Replace("\n", "\r\n");

        if (!string.Equals(normalizedPreviousContent, normalizedContent, StringComparison.Ordinal))
        {
            // The build system compiles every file under the resources folder as a resource available at runtime
            // with the same name as the file name. Need to update this file on disc.

            // https://github.com/dotnet/aspnetcore/issues/10423
#pragma warning disable 0618
            var solutionPath = TestPathUtilities.GetSolutionRootDirectory("Mvc");
#pragma warning restore 0618
            var projectPath = Path.Combine(solutionPath, "test", assembly.GetName().Name);
            var fullPath    = Path.Combine(projectPath, resourceName);
            WriteFile(fullPath, content);
        }
    }
Exemplo n.º 2
0
        private static string GetProjectDirectory()
        {
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
            var projectDirectory  = Path.Combine(solutionDirectory, "Mvc.Api.Analyzers", "test");

            return(projectDirectory);
        }
Exemplo n.º 3
0
 static ApplicationTestFixture()
 {
     SolutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
     if (!SolutionDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
     {
         SolutionDirectory += Path.DirectorySeparatorChar;
     }
 }
Exemplo n.º 4
0
        public static string GetApplicationPath()
        {
            // https://github.com/aspnet/AspNetCore/issues/8343
#pragma warning disable 0618
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("MusicStore");
#pragma warning restore 0618
            return(Path.GetFullPath(Path.Combine(solutionDirectory, "samples", "MusicStore")));
        }
Exemplo n.º 5
0
        private static string GetProjectDirectory()
        {
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
            var assemblyName      = typeof(MvcTestSource).Assembly.GetName().Name;
            var projectDirectory  = Path.Combine(solutionDirectory, "test", assemblyName);

            return(projectDirectory);
        }
Exemplo n.º 6
0
        public void CheckMofFile()
        {
            var path    = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "aspnetcoremodulev2", "aspnetcore", "ancm.mof");
            var process = Process.Start("mofcomp.exe", path);

            process.WaitForExit();
            Assert.Equal(0, process.ExitCode);
        }
Exemplo n.º 7
0
        private string GetProjectReferencePublishLocation(DeploymentParameters deploymentParameters)
        {
            var testAssetsBasePath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "IIS", "test", "testassets", _applicationName);
            var configuration      = this.GetType().GetTypeInfo().Assembly.GetCustomAttribute <AssemblyConfigurationAttribute>().Configuration;
            var path = Path.Combine(testAssetsBasePath, "bin", configuration, deploymentParameters.TargetFramework, "publish", GetProfileName(deploymentParameters));

            return(path);
        }
    private string GetProjectReferencePublishLocation(DeploymentParameters deploymentParameters)
    {
        // Deployers do not work in distributed environments
        // see https://github.com/dotnet/aspnetcore/issues/10268 and https://github.com/dotnet/extensions/issues/1697
#pragma warning disable 0618
        var testAssetsBasePath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "IIS", "test", "testassets", _applicationName);
#pragma warning restore 0618
        var configuration = this.GetType().GetTypeInfo().Assembly.GetCustomAttribute <AssemblyConfigurationAttribute>().Configuration;
        var path          = Path.Combine(testAssetsBasePath, "bin", configuration, deploymentParameters.TargetFramework, "publish", GetProfileName(deploymentParameters));
        return(path);
    }
Exemplo n.º 9
0
        public async Task CanDelegateOutOfProcess()
        {
            using var _ = StartLog(out var loggerFactory);

            var logger = loggerFactory.CreateLogger("CanDelegateOutOfProcess");

            // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
            var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("HttpSysServer"), "test", "testassets",
                                               "DelegationSite");
#pragma warning restore 0618

            var deploymentParameters = new DeploymentParameters(
                applicationPath,
                ServerType.HttpSys,
                RuntimeFlavor.CoreClr,
                RuntimeArchitecture.x64)
            {
                EnvironmentName = "Testing",
                TargetFramework = Tfm.Default,
                ApplicationType = ApplicationType.Portable,
                PublishApplicationBeforeDeployment = true,
                StatusMessagesEnabled = true
            };

            var queueName = Guid.NewGuid().ToString();
            deploymentParameters.EnvironmentVariables["queue"] = queueName;

            using var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory);
            var deploymentResult = await deployer.DeployAsync().DefaultTimeout();

            // Make sure the deployment really worked
            var responseString = await deploymentResult.HttpClient.GetStringAsync("").DefaultTimeout();

            Assert.Equal("Hello from delegatee", responseString);

            DelegationRule destination = default;
            using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
            {
                var delegateFeature = httpContext.Features.Get <IHttpSysRequestDelegationFeature>();
                delegateFeature.DelegateRequest(destination);
                return(Task.CompletedTask);
            });

            var delegationProperty = delegator.Features.Get <IServerDelegationFeature>();
            using (destination = delegationProperty.CreateDelegationRule(queueName, deploymentResult.ApplicationBaseUri))
            {
                // Send a request to the delegator that gets transfered to the delegatee in the other process.
                using var client = new HttpClient();
                responseString   = await client.GetStringAsync(delegatorAddress).DefaultTimeout();

                Assert.Equal("Hello from delegatee", responseString);
            }
        }
Exemplo n.º 10
0
        public void CheckMofFile()
        {
// This test code needs to be updated to support distributed testing.
// See https://github.com/aspnet/AspNetCore-Internal/issues/2222
#pragma warning disable 0618
            var path = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "aspnetcoremodulev2", "aspnetcore", "ancm.mof");
#pragma warning restore 0618
            var process = Process.Start("mofcomp.exe", path);
            process.WaitForExit();
            Assert.Equal(0, process.ExitCode);
        }
Exemplo n.º 11
0
        private static async Task <CorsDeploymentResult> CreateDeployments(ILoggerFactory loggerFactory, string startup)
        {
            // https://github.com/aspnet/AspNetCore/issues/7990
#pragma warning disable 0618
            var solutionPath = TestPathUtilities.GetSolutionRootDirectory("Middleware");
#pragma warning restore 0618

            var configuration =
#if RELEASE
                "Release";
#else
                "Debug";
#endif

            var originParameters = new DeploymentParameters
            {
                TargetFramework = "netcoreapp3.0",
                RuntimeFlavor   = RuntimeFlavor.CoreClr,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "test", "testassets", "TestOrigin"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType = ApplicationType.Portable,
                Configuration   = configuration,
            };

            var originFactory    = ApplicationDeployerFactory.Create(originParameters, loggerFactory);
            var originDeployment = await originFactory.DeployAsync();

            var secondOriginFactory    = ApplicationDeployerFactory.Create(originParameters, loggerFactory);
            var secondOriginDeployment = await originFactory.DeployAsync();

            var port = originDeployment.HttpClient.BaseAddress.Port;
            var destinationParameters = new DeploymentParameters
            {
                TargetFramework = "netcoreapp3.0",
                RuntimeFlavor   = RuntimeFlavor.CoreClr,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "test", "testassets", "TestDestination"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType      = ApplicationType.Portable,
                Configuration        = configuration,
                EnvironmentVariables =
                {
                    ["CORS_STARTUP"] = startup,
                    ["ORIGIN_PORT"]  = port.ToString()
                }
            };

            var destinationFactory    = ApplicationDeployerFactory.Create(destinationParameters, loggerFactory);
            var destinationDeployment = await destinationFactory.DeployAsync();

            return(new CorsDeploymentResult(originFactory, originDeployment, secondOriginFactory, secondOriginDeployment, destinationFactory, destinationDeployment));
        }
        public async Task ManualServerShutdown_NoPipeName_ShutsDownServer()
        {
            // We are trying to test whether the correct pipe name is generated (from the location of rzc tool)
            // when we don't explicitly specify a pipe name.

            // Publish rzc tool to a temporary path. This is the location based on which the pipe name is generated.
            var solutionRoot          = TestPathUtilities.GetSolutionRootDirectory("Razor");
            var toolAssemblyDirectory = Path.Combine(solutionRoot, "Razor.Tools", "src");
            var toolAssemblyPath      = Path.Combine(toolAssemblyDirectory, "rzc.csproj");
            var projectDirectory      = new TestProjectDirectory(solutionRoot, toolAssemblyDirectory, toolAssemblyPath);
            var publishDir            = Path.Combine(Path.GetTempPath(), "Razor", Path.GetRandomFileName(), "RzcPublish");
            var publishResult         = await MSBuildProcessManager.RunProcessAsync(projectDirectory, $"/t:Publish /p:PublishDir=\"{publishDir}\"");

            try
            {
                // Make sure publish succeeded.
                Assert.BuildPassed(publishResult);

                // Run the build using the published tool
                var toolAssembly = Path.Combine(publishDir, "rzc.dll");
                var result       = await DotnetMSBuild(
                    "Build",
                    $"/p:_RazorForceBuildServer=true /p:_RazorToolAssembly={toolAssembly}",
                    suppressBuildServer : true); // We don't want to specify a pipe name

                Assert.BuildPassed(result);

                // Manually shutdown the server
                var processStartInfo = new ProcessStartInfo()
                {
                    WorkingDirectory       = publishDir,
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    FileName  = "dotnet",
                    Arguments = $"{toolAssembly} shutdown -w"
                };

                var logFilePath = Path.Combine(publishDir, "out.log");
                processStartInfo.Environment.Add("RAZORBUILDSERVER_LOG", logFilePath);
                var shutdownResult = await MSBuildProcessManager.RunProcessCoreAsync(processStartInfo);

                Assert.Equal(0, shutdownResult.ExitCode);
                var output = await File.ReadAllTextAsync(logFilePath);

                Assert.Contains("shut down completed", output);
            }
            finally
            {
                // Finally delete the temporary publish directory
                ProjectDirectory.CleanupDirectory(publishDir);
            }
        }
Exemplo n.º 13
0
        public async Task ShutdownTestRun()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(ShutdownTestRun));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "TestAssets",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true
                };

                deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTMECHANIC"] = "Run";

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.Equals(args.Data, ApplicationStartedMessage) &&
                            !string.IsNullOrEmpty(args.Data) &&
                            !NowListeningRegex.Match(args.Data).Success)
                        {
                            output += args.Data + '\n';
                        }
                    };

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    output = output.Trim('\n');

                    Assert.Equal("Application is shutting down...\n" +
                                 "Stopping firing\n" +
                                 "Stopping end\n" +
                                 "Stopped firing\n" +
                                 "Stopped end",
                                 output);
                }
            }
        }
Exemplo n.º 14
0
        private static string GetProjectDirectory()
        {
            // On helix we use the published test files
            if (SkipOnHelixAttribute.OnHelix())
            {
                return(AppContext.BaseDirectory);
            }

            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
            var projectDirectory  = Path.Combine(solutionDirectory, "Mvc.Analyzers", "test");

            return(projectDirectory);
        }
        private static string GetProjectDirectory()
        {
            // On helix we use the published test files
            if (SkipOnHelixAttribute.OnHelix())
            {
                return(AppContext.BaseDirectory);
            }

// https://github.com/dotnet/aspnetcore/issues/9431
#pragma warning disable 0618
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
#pragma warning restore 0618
            var projectDirectory = Path.Combine(solutionDirectory, "Mvc.Api.Analyzers", "test");
            return(projectDirectory);
        }
Exemplo n.º 16
0
        public async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(TestVariant variant)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

                // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets", "IStartupInjectionAssemblyName");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath       = applicationPath,
                    StatusMessagesEnabled = false
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    var tcs    = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    var output = string.Empty;

                    deployer.ProcessOutputListener = (data) =>
                    {
                        if (!string.IsNullOrWhiteSpace(data))
                        {
                            output += data + '\n';
                            tcs.TrySetResult();
                        }
                    };

                    await deployer.DeployAsync();

                    try
                    {
                        await tcs.Task.TimeoutAfter(TimeSpan.FromMinutes(1));
                    }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidOperationException("Timeout while waiting for output from host process.", ex);
                    }

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
Exemplo n.º 17
0
        public void Setup()
        {
            var deploymentParameters = new DeploymentParameters(Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "test/testassets/InProcessWebSite"),
                                                                ServerType.IISExpress,
                                                                RuntimeFlavor.CoreClr,
                                                                RuntimeArchitecture.x64)
            {
                ServerConfigTemplateContent = File.ReadAllText("IISExpress.config"),
                SiteName        = "HttpTestSite",
                TargetFramework = "netcoreapp2.1",
                ApplicationType = ApplicationType.Portable
            };

            _deployer = ApplicationDeployerFactory.Create(deploymentParameters, NullLoggerFactory.Instance);
            _client   = _deployer.DeployAsync().Result.HttpClient;
        }
Exemplo n.º 18
0
        public static string GetProjectDirectory(Type type)
        {
            var solutionDir = TestPathUtilities.GetSolutionRootDirectory("Razor");

            var assemblyName     = type.Assembly.GetName().Name;
            var projectDirectory = Path.Combine(solutionDir, "test", assemblyName);

            if (!Directory.Exists(projectDirectory))
            {
                throw new InvalidOperationException(
                          $@"Could not locate project directory for type {type.FullName}.
Directory probe path: {projectDirectory}.");
            }

            return(projectDirectory);
        }
Exemplo n.º 19
0
        private static string GetProjectDirectory()
        {
            // On helix we use the published test files
            if (SkipOnHelixAttribute.OnHelix())
            {
                return(AppContext.BaseDirectory);
            }

            // This test code needs to be updated to support distributed testing.
            // See https://github.com/aspnet/AspNetCore/issues/10422
#pragma warning disable 0618
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Components");
#pragma warning restore 0618
            var projectDirectory = Path.Combine(solutionDirectory, "Analyzers", "test");
            return(projectDirectory);
        }
Exemplo n.º 20
0
        public static void UpdateFile(Assembly assembly, string resourceName, string previousContent, string content)
        {
            // Normalize line endings to '\r\n' for comparison. This removes Environment.NewLine from the equation. Not
            // worth updating files just because we generate baselines on a different system.
            var normalizedPreviousContent = previousContent?.Replace("\r", "").Replace("\n", "\r\n");
            var normalizedContent         = content.Replace("\r", "").Replace("\n", "\r\n");

            if (!string.Equals(normalizedPreviousContent, normalizedContent, StringComparison.Ordinal))
            {
                // The build system compiles every file under the resources folder as a resource available at runtime
                // with the same name as the file name. Need to update this file on disc.
                var solutionPath = TestPathUtilities.GetSolutionRootDirectory("Mvc");
                var projectPath  = Path.Combine(solutionPath, "test", assembly.GetName().Name);
                var fullPath     = Path.Combine(projectPath, resourceName);
                WriteFile(fullPath, content);
            }
        }
        private static async Task <SamplesDeploymentResult> CreateDeployments(ILoggerFactory loggerFactory, string startup)
        {
            var solutionPath = TestPathUtilities.GetSolutionRootDirectory("Middleware");

            var configuration =
#if RELEASE
                "Release";
#else
                "Debug";
#endif

            var destinationParameters = new DeploymentParameters
            {
                TargetFramework = "netcoreapp3.0",
                RuntimeFlavor   = RuntimeFlavor.CoreClr,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "samples", "SampleDestination"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType      = ApplicationType.Portable,
                Configuration        = configuration,
                EnvironmentVariables =
                {
                    ["CORS_STARTUP"] = startup
                }
            };

            var destinationFactory    = ApplicationDeployerFactory.Create(destinationParameters, loggerFactory);
            var destinationDeployment = await destinationFactory.DeployAsync();

            var originParameters = new DeploymentParameters
            {
                TargetFramework = "netcoreapp3.0",
                RuntimeFlavor   = RuntimeFlavor.CoreClr,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "samples", "SampleOrigin"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType = ApplicationType.Portable,
                Configuration   = configuration,
            };

            var originFactory    = ApplicationDeployerFactory.Create(originParameters, loggerFactory);
            var originDeployment = await originFactory.DeployAsync();

            return(new SamplesDeploymentResult(originFactory, originDeployment, destinationFactory, destinationDeployment));
        }
Exemplo n.º 22
0
        public void CanConfigureAppConfigurationFromFile()
        {
            // Needs to look in the project directory like VS would
            var projectDir  = Path.Combine(TestPathUtilities.GetRepoRootDirectory(), "src", "Hosting", "Hosting", "test");
            var hostBuilder = new HostBuilder()
                              .UseContentRoot(projectDir)
                              .ConfigureAppConfiguration((context, configBuilder) =>
            {
                configBuilder.AddJsonFile("appSettings.json", optional: false);
            });

            using (var host = hostBuilder.Build())
            {
                var config = host.Services.GetService <IConfiguration>();
                Assert.NotNull(config);
                Assert.Equal("value", config["key"]);
            }
        }
Exemplo n.º 23
0
        private async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(RuntimeFlavor runtimeFlavor)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "TestAssets", "IStartupInjectionAssemblyName");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    runtimeFlavor,
                    RuntimeArchitecture.x64)
                {
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    var    mre    = new ManualResetEventSlim();
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.Equals(args.Data, ApplicationStartedMessage) &&
                            !string.IsNullOrEmpty(args.Data) &&
                            !NowListeningRegex.Match(args.Data).Success)
                        {
                            output += args.Data + '\n';
                            mre.Set();
                        }
                    };

                    mre.Wait(10000);

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
Exemplo n.º 24
0
        public async Task ShutdownTestWaitForShutdown()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(ShutdownTestWaitForShutdown));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true
                };

                deploymentParameters.EnvironmentVariables.Add(new KeyValuePair <string, string>("ASPNETCORE_STARTMECHANIC", "WaitForShutdown"));

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) => output += args.Data + '\n';

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    output = output.Trim('\n');

                    Assert.Equal(output, "Stopping firing\n" +
                                 "Stopping end\n" +
                                 "Stopped firing\n" +
                                 "Stopped end");
                }
            }
        }
Exemplo n.º 25
0
        protected Project CreateProjectFromFile([CallerMemberName] string fileName = "")
        {
            var solutionDirectory = TestPathUtilities.GetSolutionRootDirectory("Mvc");
            var projectDirectory  = Path.Combine(solutionDirectory, "test", GetType().Assembly.GetName().Name);

            var filePath = Path.Combine(projectDirectory, "TestFiles", fileName + ".cs");

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"TestFile {fileName} could not be found at {filePath}.", filePath);
            }

            const string MarkerStart = "/*MM";
            const string MarkerEnd   = "*/";

            var lines = File.ReadAllLines(filePath);

            for (var i = 0; i < lines.Length; i++)
            {
                var line             = lines[i];
                var markerStartIndex = line.IndexOf(MarkerStart, StringComparison.Ordinal);
                if (markerStartIndex != -1)
                {
                    var markerEndIndex = line.IndexOf(MarkerEnd, markerStartIndex, StringComparison.Ordinal);
                    var markerName     = line.Substring(markerStartIndex + 2, markerEndIndex - markerStartIndex - 2);
                    var resultLocation = new DiagnosticLocation(i + 1, markerStartIndex + 1);;

                    if (DefaultMarkerLocation == null)
                    {
                        DefaultMarkerLocation = resultLocation;
                    }

                    MarkerLocations[markerName] = resultLocation;
                    line = line.Substring(0, markerStartIndex) + line.Substring(markerEndIndex + MarkerEnd.Length);
                }

                lines[i] = line;
            }

            var inputSource = string.Join(Environment.NewLine, lines);

            return(CreateProject(inputSource));
        }
Exemplo n.º 26
0
        public void Setup()
        {
// Deployers do not work in distributed environments
// see https://github.com/dotnet/aspnetcore/issues/10268 and https://github.com/dotnet/extensions/issues/1697
#pragma warning disable 0618
            var deploymentParameters = new DeploymentParameters(Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "IIS/test/testassets/InProcessWebSite"),
                                                                ServerType.IISExpress,
                                                                RuntimeFlavor.CoreClr,
                                                                RuntimeArchitecture.x64)
            {
#pragma warning restore 0618
                ServerConfigTemplateContent = File.ReadAllText("IIS.config"),
                SiteName        = "HttpTestSite",
                TargetFramework = "netcoreapp2.1",
                ApplicationType = ApplicationType.Portable
            };
            _deployer = ApplicationDeployerFactory.Create(deploymentParameters, NullLoggerFactory.Instance);
            _client   = _deployer.DeployAsync().Result.HttpClient;
        }
        private static async Task <SamplesDeploymentResult> CreateDeployments(ILoggerFactory loggerFactory)
        {
            var solutionPath = TestPathUtilities.GetSolutionRootDirectory("Middleware");

            var runtimeFlavor   = GetRuntimeFlavor();
            var applicationType = runtimeFlavor == RuntimeFlavor.Clr ? ApplicationType.Standalone : ApplicationType.Portable;

            var configuration =
#if RELEASE
                "Release";
#else
                "Debug";
#endif

            var destinationParameters = new DeploymentParameters
            {
                RuntimeFlavor   = runtimeFlavor,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "samples", "SampleDestination"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType = applicationType,
                Configuration   = configuration,
            };

            var destinationFactory    = ApplicationDeployerFactory.Create(destinationParameters, loggerFactory);
            var destinationDeployment = await destinationFactory.DeployAsync();

            var originParameters = new DeploymentParameters
            {
                RuntimeFlavor   = runtimeFlavor,
                ServerType      = ServerType.Kestrel,
                ApplicationPath = Path.Combine(solutionPath, "CORS", "samples", "SampleOrigin"),
                PublishApplicationBeforeDeployment = false,
                ApplicationType = applicationType,
                Configuration   = configuration,
            };

            var originFactory    = ApplicationDeployerFactory.Create(originParameters, loggerFactory);
            var originDeployment = await originFactory.DeployAsync();

            return(new SamplesDeploymentResult(originFactory, originDeployment, destinationFactory, destinationDeployment));
        }
Exemplo n.º 28
0
        public async Task LinkedApplicationWorks()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger("LinkedApplicationWorks");

                // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets",
                                                   "BasicLinkedApp");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    TargetFramework     = Tfm.Net50,
                    RuntimeArchitecture = RuntimeArchitecture.x64,
                    ApplicationType     = ApplicationType.Standalone,
                    PublishApplicationBeforeDeployment = true,
                    RestoreDependencies   = true,
                    PublishTimeout        = TimeSpan.FromMinutes(10), // Machines are slow (these tests restore)
                    StatusMessagesEnabled = false
                };

                using var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory);

                var result = await deployer.DeployAsync();

                // The app should have started up
                Assert.False(deployer.HostProcess.HasExited);

                var response = await RetryHelper.RetryRequest(() => result.HttpClient.GetAsync("/"), logger, retryCount : 10);

                var body = await response.Content.ReadAsStringAsync();

                Assert.Equal("Hello World", body);
            }
        }
Exemplo n.º 29
0
        public async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(TestVariant variant)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

// https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets", "IStartupInjectionAssemblyName");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath       = applicationPath,
                    StatusMessagesEnabled = false
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    var    mre    = new ManualResetEventSlim();
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            output += args.Data + '\n';
                            mre.Set();
                        }
                    };

                    mre.Wait(50000);

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
Exemplo n.º 30
0
        private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(testName);

// https://github.com/aspnet/AspNetCore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = Tfm.NetCoreApp30,
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true,
                    StatusMessagesEnabled = false
                };

                deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTMECHANIC"] = shutdownMechanic;

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    var started   = new ManualResetEventSlim();
                    var completed = new ManualResetEventSlim();
                    var output    = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
                        {
                            started.Set();
                            output += args.Data.Substring(StartedMessage.Length) + '\n';
                        }
                        else
                        {
                            output += args.Data + '\n';
                        }

                        if (output.Contains(CompletionMessage))
                        {
                            completed.Set();
                        }
                    };

                    started.Wait(50000);

                    if (!started.IsSet)
                    {
                        throw new InvalidOperationException("Application did not start successfully");
                    }

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    completed.Wait(50000);

                    if (!started.IsSet)
                    {
                        throw new InvalidOperationException($"Application did not write the expected output. The received output is: {output}");
                    }

                    output = output.Trim('\n');

                    Assert.Equal(CompletionMessage, output);
                }
            }
        }