public void Execute(DeploymentParameters deploymentParams)
 {
     var orchestrator = new ServiceOrchestrator();
     var databaseStep = new CreateDatabase(deploymentParams.SubscriptionId, deploymentParams.PublishSettingsFile, deploymentParams.DatabaseName, deploymentParams.ScriptsDirectory, deploymentParams.Username, deploymentParams.Password, ref orchestrator, deploymentParams.DeploymentLocation);
     databaseStep.ExecuteDeploymentStep().Commit();
     CommandHelpers.PrintResult(databaseStep.ConnectionString, databaseStep.GetSuccessText());
 }
 public void Execute(DeploymentParameters deploymentParams)
 {
     var orchestrator = new ServiceOrchestrator();
     var storageStep = new CreateStorage(deploymentParams.SubscriptionId, deploymentParams.PublishSettingsFile, deploymentParams.StorageAccountName, ref orchestrator, deploymentParams.DeploymentLocation);
     storageStep.ExecuteDeploymentStep().Commit();
     storageStep.PostProcess();
     CommandHelpers.PrintResult(storageStep.ConnectionString, storageStep.GetSuccessText());
 }
        public void Execute(DeploymentParameters deploymentParams)
        {
            var certificate = new PublishSettingsExtractor(deploymentParams.PublishSettingsFile)
                                  .AddPublishSettingsToPersonalMachineStore();

            var client = new ServiceClient(deploymentParams.SubscriptionId, certificate, deploymentParams.CloudServiceName);
            client.CreateNewCloudService(deploymentParams.DeploymentLocation);
        }
 public void ValidateParameters(DeploymentParameters deploymentParams)
 {
     CommandHelpers.ValidateExpectedParameters(deploymentParams.SubscriptionId,
                                               deploymentParams.PublishSettingsFile,
                                               deploymentParams.DatabaseName,
                                               deploymentParams.ScriptsDirectory,
                                               deploymentParams.Username,
                                               deploymentParams.Password);
 }
        public async Task HelloWorld(TestVariant variant)
        {
            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath = Helpers.GetInProcessTestSitesPath(),
                PublishApplicationBeforeDeployment = true
            };

            var deploymentResult = await DeployAsync(deploymentParameters);

            var response = await deploymentResult.RetryingHttpClient.GetAsync("/HelloWorld");

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

            Assert.Equal("Hello World", responseText);
        }
Beispiel #6
0
        private async Task ResponseFormats(TestVariant variant, Func <HttpClient, ILogger, Task> scenario, [CallerMemberName] string testName = null)
        {
            testName = $"{testName}_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";
            using (StartLog(out var loggerFactory,
                            variant.Server == ServerType.Nginx ? LogLevel.Trace : LogLevel.Debug, // https://github.com/aspnet/ServerTests/issues/144
                            testName))
            {
                var logger = loggerFactory.CreateLogger("ResponseFormats");

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath = Helpers.GetApplicationPath(),
                    EnvironmentName = "Responses"
                };

                if (variant.Server == ServerType.Nginx)
                {
                    deploymentParameters.ServerConfigTemplateContent = Helpers.GetNginxConfigContent("nginx.conf");
                }

                using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
                {
                    var deploymentResult = await deployer.DeployAsync();

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return(deploymentResult.HttpClient.GetAsync(string.Empty));
                    }, logger, deploymentResult.HostShutdownToken);

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

                    try
                    {
                        Assert.Equal("Running", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }

                    await scenario(deploymentResult.HttpClient, logger);
                }
            }
        }
        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    tcs    = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            output += args.Data + '\n';
                            tcs.TrySetResult();
                        }
                    };

                    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);
                }
            }
        }
Beispiel #8
0
        private async Task <string> RunTestAndGetResponse(
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture runtimeArchitecture,
            string applicationBaseUrl,
            string environmentName,
            string locale)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .CreateLogger(string.Format("Localization Test Site:{0}:{1}:{2}", ServerType.Kestrel, runtimeFlavor, runtimeArchitecture));

            using (logger.BeginScope("LocalizationTest"))
            {
                var deploymentParameters = new DeploymentParameters(_applicationPath, ServerType.Kestrel, runtimeFlavor, runtimeArchitecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName        = environmentName,
                    TargetFramework        = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0"
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();

                    var cookie          = new Cookie(CookieRequestCultureProvider.DefaultCookieName, "c=" + locale + "|uic=" + locale);
                    var cookieContainer = new CookieContainer();
                    cookieContainer.Add(new Uri(deploymentResult.ApplicationBaseUri), cookie);

                    var httpClientHandler = new HttpClientHandler();
                    httpClientHandler.CookieContainer = cookieContainer;

                    using (var httpClient = new HttpClient(httpClientHandler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri)
                    })
                    {
                        // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                        var response = await RetryHelper.RetryRequest(() =>
                        {
                            return(httpClient.GetAsync(string.Empty));
                        }, logger, deploymentResult.HostShutdownToken);

                        return(await response.Content.ReadAsStringAsync());
                    }
                }
            }
        }
        private async Task SetResponseInvalidOperations(RuntimeFlavor runtimeFlavor, ApplicationType applicationType, string path)
        {
            var serverType   = ServerType.IISExpress;
            var architecture = RuntimeArchitecture.x64;
            var testName     = $"SetResponseInvalidOperations_{runtimeFlavor}";

            using (StartLog(out var loggerFactory, testName))
            {
                var logger = loggerFactory.CreateLogger("SetFeaturesTest");

                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(), serverType, runtimeFlavor, architecture)
                {
                    EnvironmentName             = "ResponseInvalidOrdering", // Will pick the Start class named 'StartupInvalidOrdering',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
                    SiteName        = "HttpTestSite",                        // This is configured in the Http.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                    ApplicationType = applicationType
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
                {
                    var deploymentResult = await deployer.DeployAsync();

                    deploymentResult.HttpClient.Timeout = TimeSpan.FromSeconds(5);

                    // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                    var response = await RetryHelper.RetryRequest(() =>
                    {
                        return(deploymentResult.HttpClient.GetAsync(path));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

                    try
                    {
                        Assert.Equal($"Started_{path}Threw_Finished", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
Beispiel #10
0
        public async Task SmokeTestSuite(
            ServerType serverType,
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture architecture,
            ApplicationType applicationType,
            string applicationBaseUrl,
            bool noSource = false)
        {
            using (_logger.BeginScope("SmokeTestSuite"))
            {
                var musicStoreDbName = DbUtils.GetUniqueName();

                var deploymentParameters = new DeploymentParameters(
                    Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "SocialTesting",
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
                    SiteName = "MusicStoreTestSite",
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework       = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType       = applicationType,
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, _logger);
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                .Add(new KeyValuePair <string, string>(
                         MusicStoreConfig.ConnectionStringKey,
                         DbUtils.CreateConnectionString(musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
                {
                    var deploymentResult = deployer.Deploy();

                    Helpers.SetInMemoryStoreForIIS(deploymentParameters, _logger);

                    await SmokeTestHelper.RunTestsAsync(deploymentResult, _logger);
                }
            }
        }
        public async Task WindowsAuthTest(TestVariant variant)
        {
            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath             = Helpers.GetOutOfProcessTestSitesPath(),
                ServerConfigTemplateContent = GetWindowsAuthConfig()
            };

            // The default in hosting sets windows auth to true.
            var deploymentResult = await DeployAsync(deploymentParameters);

            var response = await deploymentResult.HttpClient.GetAsync("/Auth");

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

            Assert.True("backcompat;Windows".Equals(responseText) || "latest;Windows".Equals(responseText), "Auth");
        }
        public void Setup()
        {
            var deploymentParameters = new DeploymentParameters(Path.Combine(TestPathUtilities.GetSolutionRootDirectory("IISIntegration"), "test/Websites/InProcessWebSite"),
                                                                ServerType.IISExpress,
                                                                RuntimeFlavor.CoreClr,
                                                                RuntimeArchitecture.x64)
            {
                ServerConfigTemplateContent = File.ReadAllText("Http.config"),
                SiteName        = "HttpTestSite",
                TargetFramework = "netcoreapp2.1",
                ApplicationType = ApplicationType.Portable,
                AncmVersion     = AncmVersion.AspNetCoreModuleV2
            };

            _deployer = ApplicationDeployerFactory.Create(deploymentParameters, NullLoggerFactory.Instance);
            _client   = _deployer.DeployAsync().Result.HttpClient;
        }
        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));
        }
    private static string GetRuntimeIdentifier(DeploymentParameters deploymentParameters)
    {
        var architecture = deploymentParameters.RuntimeArchitecture;

        if (OperatingSystem.IsWindows())
        {
            return("win-" + architecture);
        }
        if (OperatingSystem.IsLinux())
        {
            return("linux-" + architecture);
        }
        if (OperatingSystem.IsMacOS())
        {
            return("osx-" + architecture);
        }
        throw new InvalidOperationException("Unrecognized operation system platform");
    }
 protected void InvokeUserApplicationCleanup()
 {
     using (Logger.BeginScope("UserAdditionalCleanup"))
     {
         if (DeploymentParameters.UserAdditionalCleanup != null)
         {
             // User cleanup.
             try
             {
                 DeploymentParameters.UserAdditionalCleanup(DeploymentParameters);
             }
             catch (Exception exception)
             {
                 Logger.LogWarning("User cleanup code failed with exception : {exception}", exception.Message);
             }
         }
     }
 }
Beispiel #16
0
        public async Task SmokeTestSuite(
            ServerType serverType,
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture architecture,
            ApplicationType applicationType)
        {
            var testName = $"SmokeTestSuite_{serverType}_{applicationType}";

            using (StartLog(out var loggerFactory, testName))
            {
                var logger           = loggerFactory.CreateLogger("SmokeTestSuite");
                var musicStoreDbName = DbUtils.GetUniqueName();

                var deploymentParameters = new DeploymentParameters(
                    Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    EnvironmentName             = "SocialTesting",
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
                    SiteName = "MusicStoreTestSite",
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework       = runtimeFlavor == RuntimeFlavor.CoreClr ? "netcoreapp2.0" : "net461",
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType       = applicationType,
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, logger);
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                .Add(new KeyValuePair <string, string>(
                         MusicStoreConfig.ConnectionStringKey,
                         DbUtils.CreateConnectionString(musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
                {
                    var deploymentResult = await deployer.DeployAsync();

                    await RunTestsAsync(deploymentResult, logger);
                }
            }
        }
Beispiel #17
0
        public async Task ShutdownTestRun()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(ShutdownTestRun));

                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["ASPNETCORE_STARTMECHANIC"] = "Run";

                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, "Application is shutting down...\n" +
                                 "Stopping firing\n" +
                                 "Stopping end\n" +
                                 "Stopped firing\n" +
                                 "Stopped end");
                }
            }
        }
Beispiel #18
0
    public async Task ApplicationException(TestVariant variant)
    {
        var testName = $"ApplicationException_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";

        using (StartLog(out var loggerFactory, LogLevel.Debug, testName))
        {
            var logger = loggerFactory.CreateLogger("ApplicationException");

            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath = Helpers.GetApplicationPath()
            };

            var output = string.Empty;
            using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
            {
                deployer.ProcessOutputListener = (data) =>
                {
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        output += data + '\n';
                    }
                };

                var deploymentResult = await deployer.DeployAsync();

                // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                using (var response = await RetryHelper.RetryRequest(() =>
                {
                    return(deploymentResult.HttpClient.GetAsync("/throwexception"));
                }, logger, deploymentResult.HostShutdownToken))
                {
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

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

                    Assert.Empty(body);
                }
            }
            // Output should contain the ApplicationException and the 500 status code
            Assert.Contains("System.ApplicationException: Application exception", output);
            Assert.Contains("/throwexception - - - 500", output);
        }
    }
Beispiel #19
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;
        }
Beispiel #20
0
        public static void SetInMemoryStoreForIIS(DeploymentParameters deploymentParameters, ILogger logger)
        {
            if (deploymentParameters.ServerType == ServerType.IIS)
            {
                // Can't use localdb with IIS. Setting an override to use InMemoryStore.
                logger.LogInformation("Creating configoverride.json file to override default config.");

                var compileRoot = Path.GetFullPath(
                    Path.Combine(
                        deploymentParameters.ApplicationPath,
                        "..", "approot", "packages", "MusicStore"));

                // We don't know the exact version number with which sources are built.
                string overrideConfig = Path.Combine(Directory.GetDirectories(compileRoot).First(), "root", "configoverride.json");


                File.WriteAllText(overrideConfig, "{\"UseInMemoryDatabase\": \"true\"}");
            }
        }
Beispiel #21
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);
                }
            }
        }
Beispiel #22
0
        private async Task ExecuteTestApp(string applicationName,
                                          Func <DeploymentResult, ILogger, Task> assertAction,
                                          bool setTestEnvVars = false,
                                          string environment  = "Development")
        {
            var deploymentParameters = new DeploymentParameters(Path.Combine(GetTestSitesPath(), applicationName), ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64);

            if (setTestEnvVars)
            {
                SetEnvironmentVariables(deploymentParameters, environment);
            }

            using (var deployer = IISApplicationDeployerFactory.Create(deploymentParameters, LoggerFactory))
            {
                var deploymentResult = await deployer.DeployAsync();

                await assertAction(deploymentResult, Logger);
            }
        }
        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));
        }
Beispiel #24
0
    public DeploymentParameters(DeploymentParameters parameters)
    {
        foreach (var propertyInfo in typeof(DeploymentParameters).GetProperties())
        {
            if (propertyInfo.CanWrite)
            {
                propertyInfo.SetValue(this, propertyInfo.GetValue(parameters));
            }
        }

        foreach (var kvp in parameters.EnvironmentVariables)
        {
            EnvironmentVariables.Add(kvp);
        }

        foreach (var kvp in parameters.PublishEnvironmentVariables)
        {
            PublishEnvironmentVariables.Add(kvp);
        }
    }
Beispiel #25
0
        public IISTestSiteFixture()
        {
            var deploymentParameters = new DeploymentParameters(Helpers.GetInProcessTestSitesPath(),
                                                                ServerType.IISExpress,
                                                                RuntimeFlavor.CoreClr,
                                                                RuntimeArchitecture.x64)
            {
                ServerConfigTemplateContent = File.ReadAllText("AppHostConfig/Http.config"),
                SiteName        = "HttpTestSite",
                TargetFramework = "netcoreapp2.1",
                ApplicationType = ApplicationType.Portable,
                ANCMVersion     = ANCMVersion.AspNetCoreModuleV2
            };

            _deployer        = ApplicationDeployerFactory.Create(deploymentParameters, NullLoggerFactory.Instance);
            DeploymentResult = _deployer.DeployAsync().Result;
            Client           = DeploymentResult.HttpClient;
            BaseUri          = DeploymentResult.ApplicationBaseUri;
            ShutdownToken    = DeploymentResult.HostShutdownToken;
        }
    private string GetProfileName(DeploymentParameters deploymentParameters)
    {
        // Treat AdditionalPublishParameters as profile name if defined
        string profileName;

        if (!string.IsNullOrEmpty(deploymentParameters.AdditionalPublishParameters))
        {
            profileName = deploymentParameters.AdditionalPublishParameters;
        }
        else if (deploymentParameters.ApplicationType == ApplicationType.Portable)
        {
            profileName = "Portable";
        }
        else
        {
            profileName = "Standalone-" + deploymentParameters.RuntimeArchitecture;
        }

        return(Path.GetFileNameWithoutExtension(_applicationName) + "-" + profileName);
    }
    public override Task <PublishedApplication> Publish(DeploymentParameters deploymentParameters, ILogger logger)
    {
        var path = Path.Combine(AppContext.BaseDirectory, GetProfileName(deploymentParameters));

        if (!Directory.Exists(path))
        {
            var solutionPath = GetProjectReferencePublishLocation(deploymentParameters);
            logger.LogInformation("{PublishDir} doesn't exist falling back to solution based path {SolutionBasedDir}", solutionPath, solutionPath);
            path = solutionPath;
        }

        logger.LogInformation("Using prepublished application from {PublishDir}", path);

        var target = CreateTempDirectory();

        var source = new DirectoryInfo(path);

        CachingApplicationPublisher.CopyFiles(source, target, logger);
        return(Task.FromResult(new PublishedApplication(target.FullName, logger)));
    }
        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);
            }
        }
        public async Task HelloWorld(TestVariant variant)
        {
            // The default in hosting sets windows auth to true.
            // Set it to the IISExpress.config file
            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath = Helpers.GetOutOfProcessTestSitesPath()
            };

            var deploymentResult = await DeployAsync(deploymentParameters);

            var response = await deploymentResult.RetryingHttpClient.GetAsync("/HelloWorld");

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

            Assert.Equal("Hello World", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Path/%3F%3F?query");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("/??", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Query/%3FPath?query?");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("?query?", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/BodyLimit");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("null", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Auth");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.True("backcompat;Windows".Equals(responseText) || "latest;null".Equals(responseText), "Auth");
        }
        public async Task HelloWorld(TestVariant variant)
        {
            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath = Helpers.GetOutOfProcessTestSitesPath(),
            };

            var deploymentResult = await DeployAsync(deploymentParameters);

            var response = await deploymentResult.RetryingHttpClient.GetAsync("/HelloWorld");

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

            Assert.Equal("Hello World", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Path/%3F%3F?query");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("/??", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Query/%3FPath?query?");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("?query?", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/BodyLimit");

            responseText = await response.Content.ReadAsStringAsync();

            Assert.Equal("null", responseText);

            response = await deploymentResult.HttpClient.GetAsync("/Auth");

            responseText = await response.Content.ReadAsStringAsync();

            // We adapted the Http.config file to be used for inprocess too. We specify WindowsAuth is enabled
            // We now expect that windows auth is enabled rather than disabled.
            Assert.True("backcompat;Windows".Equals(responseText) || "latest;Windows".Equals(responseText), "Auth");
        }
Beispiel #31
0
        private async Task HttpsHelloWorldCerts(TestVariant variant, bool sendClientCert)
        {
            var port = TestPortHelper.GetNextSSLPort();
            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath             = Helpers.GetOutOfProcessTestSitesPath(),
                ApplicationBaseUriHint      = $"https://localhost:{port}/",
                ServerConfigTemplateContent = GetHttpsServerConfig()
            };

            var deploymentResult = await DeployAsync(deploymentParameters);

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (a, b, c, d) => true,
                ClientCertificateOptions = ClientCertificateOption.Manual
            };

            if (sendClientCert)
            {
                X509Certificate2 clientCert = FindClientCert();
                Assert.NotNull(clientCert);
                handler.ClientCertificates.Add(clientCert);
            }

            var client = deploymentResult.CreateRetryClient(handler);

            // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
            var response = await client.GetAsync("checkclientcert");

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

            if (sendClientCert)
            {
                Assert.Equal("Scheme:https; Original:http; has cert? True", responseText);
            }
            else
            {
                Assert.Equal("Scheme:https; Original:http; has cert? False", responseText);
            }
        }
        public IISTestSiteFixture()
        {
            var logging = AssemblyTestLog.ForAssembly(typeof(IISTestSiteFixture).Assembly);

            var deploymentParameters = new DeploymentParameters(Helpers.GetInProcessTestSitesPath(),
                                                                ServerType.IISExpress,
                                                                RuntimeFlavor.CoreClr,
                                                                RuntimeArchitecture.x64)
            {
                TargetFramework = Tfm.NetCoreApp22,
                AncmVersion     = AncmVersion.AspNetCoreModuleV2,
                HostingModel    = HostingModel.InProcess,
                PublishApplicationBeforeDeployment = true,
            };

            _deployer        = ApplicationDeployerFactory.Create(deploymentParameters, logging.CreateLoggerFactory(null, nameof(IISTestSiteFixture)));
            DeploymentResult = _deployer.DeployAsync().Result;
            Client           = DeploymentResult.HttpClient;
            BaseUri          = DeploymentResult.ApplicationBaseUri;
            ShutdownToken    = DeploymentResult.HostShutdownToken;
        }
    public WebTestsFixture()
    {
        var logger = new LoggerFactory()
                     .AddConsole(LogLevel.Information)
                     .CreateLogger("Regression");

        _loggerScope = logger.BeginScope("RegressionTestSuite");
        var deploymentParameters = new DeploymentParameters(
            TestConfiguration.Configuration.Get <string>("Settings:ApplicationPath"),
            (ServerType)Enum.Parse(typeof(ServerType), TestConfiguration.Configuration.Get <string>("Settings:ServerType")),
            RuntimeFlavor.Clr,
            RuntimeArchitecture.x86)
        {
            ApplicationBaseUriHint = TestConfiguration.Configuration.Get <string>("Settings:ApplicationUri"),
            EnvironmentName        = TestConfiguration.Configuration.Get <string>("Settings:EnvironmentName"),
            PublishWithNoSource    = false
        };

        _deployer        = ApplicationDeployerFactory.Create(deploymentParameters, logger);
        DeploymentResult = _deployer.Deploy();
    }
Beispiel #34
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);
                }
            }
        }
 public void ValidateParameters(DeploymentParameters deploymentParams)
 {
     CommandHelpers.ValidateExpectedParameters(deploymentParams.SubscriptionId,
                                               deploymentParams.PublishSettingsFile,
                                               deploymentParams.CloudServiceName);
 }
 public void ValidateParameters(DeploymentParameters deploymentParams)
 {
     CommandHelpers.ValidateExpectedParameters(deploymentParams.SubscriptionId,
                                               deploymentParams.PublishSettingsFile,
                                               deploymentParams.StorageAccountName);
 }