Ejemplo n.º 1
0
        public async Task Smoke_Tests(TestVariant variant)
        {
            var testName = $"SmokeTestSuite_{variant}";

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

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath = Helpers.GetApplicationPath(),
                    EnvironmentName = "SocialTesting",
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    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);
                }
            }
        }
        public async Task PublishingPrintsParseErrors(RuntimeFlavor flavor)
        {
            // Arrange
            var applicationPath = ApplicationPaths.GetTestAppDirectory("ApplicationWithParseErrors");
            var indexPath       = Path.Combine(applicationPath, "Views", "Home", "Index.cshtml");
            var viewImportsPath = Path.Combine(applicationPath, "Views", "Home", "About.cshtml");
            var expectedErrors  = new[]
            {
                indexPath + " (0): The code block is missing a closing \"}\" character.  Make sure you have a matching \"}\" character for all the \"{\" characters within this block, and that none of the \"}\" characters are being interpreted as markup.",
                viewImportsPath + " (1): A space or line break was encountered after the \"@\" character.  Only valid identifiers, keywords, comments, \"(\" and \"{\" are valid at the start of a code block and they must occur immediately following \"@\" with no space in between.",
            };
            var testSink             = new TestSink();
            var deploymentParameters = ApplicationTestFixture.GetDeploymentParameters(applicationPath, flavor);
            var loggerFactory        = new TestLoggerFactory(testSink, enabled: true);

            using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
            {
                // Act
                await Assert.ThrowsAsync <Exception>(() => deployer.DeployAsync());

                // Assert
                var logs = testSink.Writes.Select(w => w.State.ToString().Trim()).ToList();
                foreach (var expectedError in expectedErrors)
                {
                    Assert.Contains(logs, log => log.Contains(expectedError));
                }
            }
        }
Ejemplo n.º 3
0
        [Fact] // Consistently fails on CI for net461
        public async Task StandaloneApplication_ExpectCorrectPublish()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger("HelloWorldTest");

                var deploymentParameters = GetBaseDeploymentParameters();

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

                    deploymentParameters.ApplicationType = ApplicationType.Standalone;

                    // 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("HelloWorld"));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

                    try
                    {
                        Assert.Equal("Hello World", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
        private async Task NtlmAuthenticationTest(TestVariant variant)
        {
            var testName = $"NtlmAuthentication_{variant}";

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

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath = Helpers.GetApplicationPath(),
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    EnvironmentName             = "NtlmAuthentication", //Will pick the Start class named 'StartupNtlmAuthentication'
                    ServerConfigTemplateContent = (variant.Server == ServerType.IISExpress) ? File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "NtlmAuthentation.config")) : null,
                    SiteName = "MusicStoreNtlmAuthentication",          //This is configured in the NtlmAuthentication.config
                    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();

                    var httpClientHandler = new HttpClientHandler()
                    {
                        UseDefaultCredentials = true
                    };
                    var httpClient = deploymentResult.CreateHttpClient(httpClientHandler);

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

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);

                    logger.LogInformation("Verifying home page");
                    await validator.VerifyNtlmHomePage(response);

                    logger.LogInformation("Verifying access to store with permissions");
                    await validator.AccessStoreWithPermissions();

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 5
0
        public async Task NtlmAuthenticationTest(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, ApplicationType applicationType, string applicationBaseUrl)
        {
            using (_logger.BeginScope("NtlmAuthenticationTest"))
            {
                var musicStoreDbName = DbUtils.GetUniqueName();

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    PublishApplicationBeforeDeployment = true,
                    PublishTargetFramework             = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType             = applicationType,
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "NtlmAuthentication", //Will pick the Start class named 'StartupNtlmAuthentication'
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("NtlmAuthentation.config") : null,
                    SiteName = "MusicStoreNtlmAuthentication",          //This is configured in the NtlmAuthentication.config
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, _logger);
                    }
                };

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

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
                {
                    var deploymentResult  = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler()
                    {
                        UseDefaultCredentials = true
                    };
                    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(async() =>
                    {
                        return(await httpClient.GetAsync(string.Empty));
                    }, logger : _logger, cancellationToken : deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, _logger, deploymentResult);

                    Console.WriteLine("Verifying home page");
                    await validator.VerifyNtlmHomePage(response);

                    Console.WriteLine("Verifying access to store with permissions");
                    await validator.AccessStoreWithPermissions();

                    _logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 6
0
        public async Task InvalidProcessPath_ExpectServerError()
        {
            var dotnetLocation = "bogus";

            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger("HelloWorldTest");
                var deploymentParameters = GetBaseDeploymentParameters();

                // Point to dotnet installed in user profile.
                deploymentParameters.EnvironmentVariables["DotnetPath"] = Environment.ExpandEnvironmentVariables(dotnetLocation); // Path to dotnet.

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

                    Helpers.ModifyAspNetCoreSectionInWebConfig(deploymentResult, "processPath", "%DotnetPath%");

                    // 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("HelloWorld"));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                }
            }
        }
Ejemplo n.º 7
0
        public static async Task RunSiteTest(string siteName, ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl,
                                             Func <HttpClient, ILogger, CancellationToken, Task> validator)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .CreateLogger(string.Format("{0}:{1}:{2}:{3}", siteName, serverType, runtimeFlavor, architecture));

            using (logger.BeginScope("RunSiteTest"))
            {
                var deploymentParameters = new DeploymentParameters(GetPathToApplication(siteName), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    SiteName = "HttpTestSite",
                    PublishApplicationBeforeDeployment = true,
                    PublishTargetFramework             = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType = runtimeFlavor == RuntimeFlavor.Clr ? ApplicationType.Standalone : ApplicationType.Portable
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult  = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    var httpClient        = new HttpClient(httpClientHandler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
                        Timeout     = TimeSpan.FromSeconds(10)
                    };

                    await validator(httpClient, logger, deploymentResult.HostShutdownToken);
                }
            }
        }
Ejemplo n.º 8
0
        public static async Task RunSiteTest(
            string siteName,
            ServerType serverType,
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture architecture,
            ApplicationType applicationType,
            ILoggerFactory loggerFactory,
            Func <HttpClient, ILogger, CancellationToken, Task> validator)
        {
            var logger = loggerFactory.CreateLogger(siteName);

            var deploymentParameters = new DeploymentParameters(GetApplicationDirectory(siteName), serverType, runtimeFlavor, architecture)
            {
                SiteName = "HttpTestSite",
                ServerConfigTemplateContent        = serverType == ServerType.Nginx ? File.ReadAllText(Path.Combine(WorkingDirectory, "nginx.conf")) : string.Empty,
                PublishApplicationBeforeDeployment = true,
                TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                ApplicationType = applicationType
            };

            using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, loggerFactory))
            {
                logger.LogInformation($"Running deployment for {siteName}:{serverType}:{runtimeFlavor}:{architecture}");
                var deploymentResult = await deployer.DeployAsync();

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

                logger.LogInformation($"Running validation for {siteName}:{serverType}:{runtimeFlavor}:{architecture}");
                await validator(deploymentResult.HttpClient, logger, deploymentResult.HostShutdownToken);
            }
        }
Ejemplo n.º 9
0
        public void Initialize(ILoggerFactory loggerFactory)
        {
            if (_initalized)
            {
                return;
            }

            var sampleList = new Tuple <string, RuntimeFlavor>[]
            {
                Tuple.Create("StarterMvc", RuntimeFlavor.Clr),
                Tuple.Create("StarterMvc", RuntimeFlavor.CoreClr)
            };

            foreach (var sample in sampleList)
            {
                var source     = _sampleManager.GetRestoredSample(sample.Item1);
                var parameters = new DeploymentParameters(source, ServerType.IIS, sample.Item2, RuntimeArchitecture.x64)
                {
                    TargetFramework = "net451"
                };

                // This is a quick fix to turn around the build before the fix in Hosting eventually goes online
                parameters.ApplicationBaseUriHint = "http://localhost:0";

                var deployer = ApplicationDeployerFactory.Create(parameters, loggerFactory.CreateLogger <IISTestManager>());

                var result = deployer.Deploy();
                _deployments[sample] = result;
                _deployer.Add(deployer);
            }

            _initalized = true;
        }
Ejemplo n.º 10
0
        public async Task DeployTestAndAddToSpec(ServerType server, bool ssl, string environment, CancellationToken cancellationToken, Action <AutobahnExpectations> expectationConfig = null)
        {
            var sslNamePart = ssl ? "SSL" : "NoSSL";
            var name        = $"{server}|{sslNamePart}|{environment}";
            var logger      = _loggerFactory.CreateLogger($"AutobahnTestApp:{server}:{sslNamePart}:{environment}");

            var appPath         = Helpers.GetApplicationPath("AutobahnTestApp");
            var configPath      = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "Http.config");
            var targetFramework =
#if NETCOREAPP2_2
                "netcoreapp2.2";
#else
#error Target frameworks need to be updated
#endif
            var parameters = new DeploymentParameters(appPath, server, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64)
            {
                Scheme                      = (ssl ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
                ApplicationType             = ApplicationType.Portable,
                TargetFramework             = targetFramework,
                EnvironmentName             = environment,
                SiteName                    = "HttpTestSite", // This is configured in the Http.config
                ServerConfigTemplateContent = (server == ServerType.IISExpress) ? File.ReadAllText(configPath) : null,
            };

            var deployer = ApplicationDeployerFactory.Create(parameters, _loggerFactory);
            var result   = await deployer.DeployAsync();

            _deployers.Add(deployer);
            _deployments.Add(result);
            cancellationToken.ThrowIfCancellationRequested();

            var handler = new HttpClientHandler();
            // Win7 HttpClient on NetCoreApp2.2 defaults to TLS 1.0 and won't connect to Kestrel. https://github.com/dotnet/corefx/issues/28733
            // Mac HttpClient on NetCoreApp2.0 doesn't alow you to set some combinations.
            // https://github.com/dotnet/corefx/blob/586cffcdfdf23ad6c193a4bf37fce88a1bf69508/src/System.Net.Http/src/System/Net/Http/CurlHandler/CurlHandler.SslProvider.OSX.cs#L104-L106
            handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
            handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var client = result.CreateHttpClient(handler);

            // Make sure the server works
            var resp = await RetryHelper.RetryRequest(() =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                return(client.GetAsync(result.ApplicationBaseUri));
            }, logger, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, result.HostShutdownToken).Token);

            resp.EnsureSuccessStatusCode();

            cancellationToken.ThrowIfCancellationRequested();

            // Add to the current spec
            var wsUrl = result.ApplicationBaseUri.Replace("https://", "wss://").Replace("http://", "ws://");
            Spec.WithServer(name, wsUrl);

            var expectations = new AutobahnExpectations(server, ssl, environment);
            expectationConfig?.Invoke(expectations);
            _expectations.Add(expectations);

            cancellationToken.ThrowIfCancellationRequested();
        }
        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,
                Configuration   =
#if DEBUG
                    "Debug"
#else
                    "Release"
#endif
            };

            _deployer        = ApplicationDeployerFactory.Create(deploymentParameters, NullLoggerFactory.Instance);
            DeploymentResult = _deployer.DeployAsync().Result;
            Client           = DeploymentResult.HttpClient;
            BaseUri          = DeploymentResult.ApplicationBaseUri;
            ShutdownToken    = DeploymentResult.HostShutdownToken;
        }
Ejemplo n.º 12
0
        private async Task OpenIdConnectTestSuite(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl)
        {
            var logger = new LoggerFactory()
                         .AddConsole(LogLevel.Warning)
                         .CreateLogger(string.Format("OpenId:{0}:{1}:{2}", serverType, runtimeFlavor, architecture));

            using (logger.BeginScope("OpenIdConnectTestSuite"))
            {
                var musicStoreDbName = Guid.NewGuid().ToString().Replace("-", string.Empty);
                var connectionString = string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName);

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName        = "OpenIdConnectTesting",
                    UserAdditionalCleanup  = parameters =>
                    {
                        if (!Helpers.RunningOnMono)
                        {
                            // Mono uses InMemoryStore
                            DbUtils.DropDatabase(musicStoreDbName, logger);
                        }
                    }
                };

                // Override the connection strings using environment based configuration
                deploymentParameters.EnvironmentVariables
                .Add(new KeyValuePair <string, string>(
                         "SQLAZURECONNSTR_DefaultConnection",
                         string.Format(DbUtils.CONNECTION_STRING_FORMAT, musicStoreDbName)));

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult  = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    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(async() =>
                    {
                        return(await httpClient.GetAsync(string.Empty));
                    }, logger : logger, cancellationToken : deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);
                    await validator.VerifyHomePage(response);

                    // OpenIdConnect login.
                    await validator.LoginWithOpenIdConnect();

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 13
0
        private async Task OpenIdConnectTestSuite(ServerType serverType, RuntimeFlavor runtimeFlavor, ApplicationType applicationType)
        {
            var architecture = RuntimeArchitecture.x64;
            var testName     = $"OpenIdConnectTestSuite_{serverType}_{runtimeFlavor}_{architecture}_{applicationType}";

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

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework       = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType       = applicationType,
                    EnvironmentName       = "OpenIdConnectTesting",
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, logger);
                    },
                    AdditionalPublishParameters = " /p:PublishForTesting=true"
                };

                // 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();

                    var httpClientHandler = new HttpClientHandler();
                    var httpClient        = deploymentResult.CreateHttpClient(httpClientHandler);

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

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);

                    logger.LogInformation("Verifying home page");
                    await validator.VerifyHomePage(response);

                    logger.LogInformation("Verifying login by OpenIdConnect");
                    await validator.LoginWithOpenIdConnect();

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 14
0
        public async Task <Deployment> CreateDeploymentAsync(RuntimeFlavor flavor)
        {
            var deploymentParameters = GetDeploymentParameters(flavor);
            var deployer             = ApplicationDeployerFactory.Create(deploymentParameters, LoggerFactory);
            var deploymentResult     = await deployer.DeployAsync();

            return(new Deployment(deployer, deploymentResult));
        }
Ejemplo n.º 15
0
        private async Task HelloWorld(RuntimeFlavor runtimeFlavor, ApplicationType applicationType)
        {
            var serverType   = ServerType.IISExpress;
            var architecture = RuntimeArchitecture.x64;
            var testName     = $"HelloWorld_{runtimeFlavor}";

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

                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(), serverType, runtimeFlavor, architecture)
                {
                    EnvironmentName             = "HelloWorld", // Will pick the Start class named 'StartupHelloWorld',
                    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(string.Empty));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

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

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

                        responseText = await response.Content.ReadAsStringAsync();

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

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

                        responseText = await response.Content.ReadAsStringAsync();

                        Assert.Equal("?query?", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public async Task SmokeTestSuite(ServerType serverType, string storeDirectory)
        {
            var targetFramework = "netcoreapp2.0";
            var testName        = $"SmokeTestsUsingStore_{serverType}";

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

                var deploymentParameters = new DeploymentParameters(
                    Helpers.GetApplicationPath(ApplicationType.Portable), serverType, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64)
                {
                    EnvironmentName = "SocialTesting",
                    SiteName        = "MusicStoreTestSiteUsingStore",
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework       = targetFramework,
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType       = ApplicationType.Portable,
                    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)));

                deploymentParameters.EnvironmentVariables.Add(
                    new KeyValuePair <string, string>("DOTNET_SHARED_STORE", storeDirectory));

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

                    logger.LogInformation("Published output directory structure:");
                    logger.LogInformation(GetDirectoryStructure(deploymentResult.ContentRoot));

                    var mvcCoreDll = "Microsoft.AspNetCore.Mvc.Core.dll";
                    logger.LogInformation(
                        $"Checking if published output was trimmed by verifying that the dll '{mvcCoreDll}' is not present...");

                    var mvcCoreDllPath = Path.Combine(deploymentResult.ContentRoot, mvcCoreDll);
                    var fileInfo       = new FileInfo(mvcCoreDllPath);
                    Assert.False(
                        File.Exists(mvcCoreDllPath),
                        $"The file '{fileInfo.Name}.{fileInfo.Extension}' was not expected to be present in the publish directory");

                    logger.LogInformation($"Published output does not have the dll '{mvcCoreDll}', so the output seems to be trimmed");

                    await SmokeTestRunner.RunTestsAsync(deploymentResult, logger);
                }
            }
        }
Ejemplo n.º 17
0
        private async Task HttpsHelloWorld(RuntimeFlavor runtimeFlavor, ApplicationType applicationType, int port)
        {
            var serverType   = ServerType.IISExpress;
            var architecture = RuntimeArchitecture.x64;

            var applicationBaseUrl = $"https://localhost:{port}/";
            var testName           = $"HttpsHelloWorld_{runtimeFlavor}";

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

                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "HttpsHelloWorld", // Will pick the Start class named 'StartupHttpsHelloWorld',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Https.config") : null,
                    SiteName        = "HttpsTestSite",               // This is configured in the Https.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                    ApplicationType = applicationType,
                    Configuration   =
#if DEBUG
                        "Debug"
#else
                        "Release"
#endif
                };

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

                    var handler = new HttpClientHandler();
                    handler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true;
                    var httpClient = deploymentResult.CreateHttpClient(handler);
                    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(httpClient.GetAsync(string.Empty));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

                    try
                    {
                        Assert.Equal("Scheme:https; Original:http", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
        private async Task ResponseCompression(TestVariant variant,
                                               Func <HttpClient, ILogger, Task> scenario,
                                               bool hostCompression,
                                               [CallerMemberName] string testName = null)
        {
            testName = $"{testName}_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";
            using (StartLog(out var loggerFactory, testName))
            {
                var logger = loggerFactory.CreateLogger("ResponseCompression");

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath = Helpers.GetApplicationPath(),
                    EnvironmentName = "ResponseCompression",
                };
                if (hostCompression)
                {
                    deploymentParameters.ServerConfigTemplateContent = Helpers.GetNginxConfigContent(variant.Server, "nginx.conf");
                }
                else
                {
                    deploymentParameters.ServerConfigTemplateContent = Helpers.GetConfigContent(variant.Server, "NoCompression.config", "NoCompression.conf");
                }

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

                    var httpClientHandler = new HttpClientHandler()
                    {
                        AutomaticDecompression = DecompressionMethods.None
                    };
                    Assert.True(httpClientHandler.SupportsAutomaticDecompression);
                    var httpClient = deploymentResult.CreateHttpClient(httpClientHandler);

                    // 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);

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

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

                    await scenario(httpClient, logger);
                }
            }
        }
        private async Task UpgradeFeatureDetectionDeployer(RuntimeFlavor runtimeFlavor,
                                                           ApplicationType applicationType,
                                                           string configPath,
                                                           string sitePath,
                                                           string expected)
        {
            var serverType   = ServerType.IISExpress;
            var architecture = RuntimeArchitecture.x64;
            var testName     = $"HelloWorld_{runtimeFlavor}";

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

                var deploymentParameters = new DeploymentParameters(Helpers.GetInProcessTestSitesPath(), serverType, runtimeFlavor, architecture)
                {
                    EnvironmentName             = "UpgradeFeatureDetection", // Will pick the Start class named 'StartupHelloWorld',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText(configPath) : null,
                    SiteName        = "HttpTestSite",                        // This is configured in the Http.config
                    TargetFramework = "netcoreapp2.1",
                    ApplicationType = applicationType,
                    Configuration   =
#if DEBUG
                        "Debug"
#else
                        "Release"
#endif
                };

                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("UpgradeFeatureDetection"));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

                    try
                    {
                        Assert.Equal(expected, responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
    }
Ejemplo n.º 20
0
        public async Task RunDeveloperTests(
            ServerType serverType,
            RuntimeFlavor runtimeFlavor,
            ApplicationType applicationType,
            RuntimeArchitecture runtimeArchitecture)
        {
            var testName = $"PublishAndRunTests_{serverType}_{runtimeFlavor}_{applicationType}";

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

                var deploymentParameters = new DeploymentParameters(
                    Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, runtimeArchitecture)
                {
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
                    TargetFramework       = Helpers.GetTargetFramework(runtimeFlavor),
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    EnvironmentName       = "Development",
                    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();

                    var httpClientHandler = new HttpClientHandler {
                        UseDefaultCredentials = true
                    };
                    var httpClient = deploymentResult.CreateHttpClient(httpClientHandler);

                    // Request to base address and check if various parts of the body are rendered &
                    // measure the cold startup time.
                    // Add retry logic since tests are flaky on mono due to connection issues
                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);
                    var response  = await RetryHelper.RetryRequest(() => httpClient.GetAsync("PageThatThrows"), logger, cancellationToken : deploymentResult.HostShutdownToken);

                    logger.LogInformation("Verifying developer exception page");
                    await validator.VerifyDeveloperExceptionPage(response);

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 21
0
        // TODO: temporarily disabling x86 tests as dotnet xunit test runner currently does not support 32-bit

        //[ConditionalTheory(Skip = "https://github.com/aspnet/MusicStore/issues/565"), Trait("E2Etests", "E2Etests")]
        //[OSSkipCondition(OperatingSystems.Windows)]
        //[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5045/")]
        //public async Task OpenIdConnect_OnMono(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, ApplicationType applicationType, string applicationBaseUrl)
        //{
        //    await OpenIdConnectTestSuite(serverType, runtimeFlavor, architecture, applicationBaseUrl);
        //}

        private async Task OpenIdConnectTestSuite(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, ApplicationType applicationType, string applicationBaseUrl)
        {
            using (_logger.BeginScope("OpenIdConnectTestSuite"))
            {
                var musicStoreDbName = DbUtils.GetUniqueName();

                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    PublishApplicationBeforeDeployment = true,
                    PublishTargetFramework             = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType        = applicationType,
                    ApplicationBaseUriHint = applicationBaseUrl,
                    EnvironmentName        = "OpenIdConnectTesting",
                    UserAdditionalCleanup  = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, _logger);
                    }
                };

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

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
                {
                    var deploymentResult  = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    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(async() =>
                    {
                        return(await httpClient.GetAsync(string.Empty));
                    }, logger : _logger, cancellationToken : deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, _logger, deploymentResult);

                    Console.WriteLine("Verifying home page");
                    await validator.VerifyHomePage(response);

                    Console.WriteLine("Verifying login by OpenIdConnect");
                    await validator.LoginWithOpenIdConnect();

                    _logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 22
0
        public async Task DeployTestAndAddToSpec(ServerType server, bool ssl, Action <AutobahnExpectations> expectationConfig = null)
        {
            var port        = Interlocked.Increment(ref _nextPort);
            var baseUrl     = ssl ? $"https://localhost:{port}" : $"http://localhost:{port}";
            var sslNamePart = ssl ? "SSL" : "NoSSL";
            var name        = $"{server}|{sslNamePart}";
            var logger      = _loggerFactory.CreateLogger($"AutobahnTestApp:{server}:{sslNamePart}");

            var appPath    = Helpers.GetApplicationPath("WebSocketsTestApp");
            var parameters = new DeploymentParameters(appPath, server, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64)
            {
                ApplicationBaseUriHint = baseUrl,
                ApplicationType        = ApplicationType.Portable,
                TargetFramework        = "netcoreapp1.1",
                EnvironmentName        = "Development"
            };

            var deployer = ApplicationDeployerFactory.Create(parameters, logger);
            var result   = deployer.Deploy();

            result.HostShutdownToken.ThrowIfCancellationRequested();

#if NET451
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (_, __, ___, ____) => true;
            var client = new HttpClient();
#else
            var handler = new HttpClientHandler();
            if (ssl)
            {
                // Don't take this out of the "if(ssl)". If we set it on some platforms, it crashes
                // So we avoid running SSL tests on those platforms (for now).
                // See https://github.com/dotnet/corefx/issues/9728
                handler.ServerCertificateCustomValidationCallback = (_, __, ___, ____) => true;
            }
            var client = new HttpClient(handler);
#endif

            // Make sure the server works
            var resp = await RetryHelper.RetryRequest(() =>
            {
                return(client.GetAsync(result.ApplicationBaseUri));
            }, logger, result.HostShutdownToken, retryCount : 5);

            resp.EnsureSuccessStatusCode();

            // Add to the current spec
            var wsUrl = result.ApplicationBaseUri.Replace("https://", "wss://").Replace("http://", "ws://");
            Spec.WithServer(name, wsUrl);

            _deployers.Add(deployer);

            var expectations = new AutobahnExpectations(server, ssl);
            expectationConfig?.Invoke(expectations);
            _expectations.Add(expectations);
        }
Ejemplo n.º 23
0
        public async Task DotnetRun_Tests(TestVariant variant)
        {
            var testName = $"DotnetRunTests_{variant}";

            using (StartLog(out var loggerFactory, testName))
            {
                var logger               = loggerFactory.CreateLogger("DotnetRunTests");
                var musicStoreDbName     = DbUtils.GetUniqueName();
                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath = Helpers.GetApplicationPath(),
                    PublishApplicationBeforeDeployment = false,
                    EnvironmentName       = "Development",
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, logger);
                    },
                    EnvironmentVariables =
                    {
                        { MusicStoreConfig.ConnectionStringKey, DbUtils.CreateConnectionString(musicStoreDbName) },
                    },
                };

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

                    var httpClientHandler = new HttpClientHandler {
                        UseDefaultCredentials = true
                    };
                    var httpClient = deploymentResult.CreateHttpClient(httpClientHandler);

                    var response = await RetryHelper.RetryRequest(
                        () => httpClient.GetAsync(string.Empty), logger, deploymentResult.HostShutdownToken);

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);

                    logger.LogInformation("Verifying home page");
                    // Verify HomePage should validate that we're using precompiled views.
                    await validator.VerifyHomePage(response);

                    // Verify developer exception page
                    logger.LogInformation("Verifying developer exception page");
                    response = await RetryHelper.RetryRequest(
                        () => httpClient.GetAsync("PageThatThrows"), logger, cancellationToken : deploymentResult.HostShutdownToken);

                    await validator.VerifyDeveloperExceptionPage(response);

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 24
0
        private async Task JavaScriptSnippetInjectionTestSuite(string targetFramework, ApplicationType applicationType)
        {
            var testName = $"ApplicationInsightsJavaScriptSnippetTest_{applicationType}";

            using (StartLog(out var loggerFactory, testName))
            {
                var logger = loggerFactory.CreateLogger(nameof(JavaScriptSnippetTest));
                var deploymentParameters = new DeploymentParameters(GetApplicationPath(), ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64)
                {
                    PublishApplicationBeforeDeployment       = true,
                    PreservePublishedApplicationForDebugging = PreservePublishedApplicationForDebugging,
                    TargetFramework      = targetFramework,
                    Configuration        = GetCurrentBuildConfiguration(),
                    ApplicationType      = applicationType,
                    EnvironmentName      = "JavaScript",
                    EnvironmentVariables =
                    {
                        new KeyValuePair <string, string>(
                            "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES",
                            "Microsoft.AspNetCore.ApplicationInsights.HostingStartup"),
                    },
                };

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

                    var httpClientHandler = new HttpClientHandler();
                    var httpClient        = deploymentResult.CreateHttpClient(httpClientHandler);

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

                    Assert.False(response == null, "Response object is null because the client could not " +
                                 "connect to the server after multiple retries");

                    var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult);

                    logger.LogInformation("Verifying layout page");
                    await validator.VerifyLayoutPage(response);

                    logger.LogInformation("Verifying layout page before script");
                    await validator.VerifyLayoutPageBeforeScript(response);

                    logger.LogInformation("Verifying layout page after script");
                    await validator.VerifyLayoutPageAfterScript(response);

                    logger.LogInformation("Variation completed successfully.");
                }
            }
        }
Ejemplo n.º 25
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));
        }
Ejemplo n.º 26
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.1",
                    Configuration         = Helpers.GetCurrentBuildConfiguration(),
                    ApplicationType       = applicationType,
                    UserAdditionalCleanup = parameters =>
                    {
                        DbUtils.DropDatabase(musicStoreDbName, _logger);
                    }
                };

                if (applicationType == ApplicationType.Standalone)
                {
                    deploymentParameters.AdditionalPublishParameters = " -r " + RuntimeEnvironment.GetRuntimeIdentifier();
                }

                // 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);
                }
            }
        }
Ejemplo n.º 27
0
        public async Task HttpsHelloWorld(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl, ApplicationType applicationType)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .AddDebug()
                         .CreateLogger($"HttpsHelloWorld:{serverType}:{runtimeFlavor}:{architecture}");

            using (logger.BeginScope("HttpsHelloWorldTest"))
            {
                var deploymentParameters = new DeploymentParameters(Helpers.GetTestSitesPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "HttpsHelloWorld", // Will pick the Start class named 'StartupHttpsHelloWorld',
                    ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Https.config") : null,
                    SiteName        = "HttpsTestSite",               // This is configured in the Https.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType = applicationType
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult = deployer.Deploy();
                    var handler          = new WebRequestHandler();
                    handler.ServerCertificateValidationCallback = (a, b, c, d) => true;
                    var httpClient = new HttpClient(handler)
                    {
                        BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
                        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(httpClient.GetAsync(string.Empty));
                    }, logger, deploymentResult.HostShutdownToken, retryCount : 30);

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

                    try
                    {
                        Assert.Equal("Scheme:https; Original:http", responseText);
                    }
                    catch (XunitException)
                    {
                        logger.LogWarning(response.ToString());
                        logger.LogWarning(responseText);
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public async Task RunTestAndVerifyResponse(
            RuntimeFlavor runtimeFlavor,
            RuntimeArchitecture runtimeArchitechture,
            string applicationBaseUrl,
            string environmentName,
            string locale,
            string expectedText)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .CreateLogger(string.Format("Localization Test Site:{0}:{1}:{2}", ServerType.Kestrel, runtimeFlavor, runtimeArchitechture));

            using (logger.BeginScope("LocalizationTest"))
            {
                var deploymentParameters = new DeploymentParameters(GetApplicationPath(), ServerType.Kestrel, runtimeFlavor, runtimeArchitechture)
                {
                    ApplicationBaseUriHint = applicationBaseUrl,
                    Command         = "web",
                    EnvironmentName = environmentName
                };

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

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

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

                    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);

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

                    Console.WriteLine("Response Text " + responseText);
                    Assert.Equal(expectedText, responseText);
                }
            }
        }
Ejemplo n.º 29
0
        public async Task ResponseFormats(ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl, Func <HttpClient, ILogger, Task> scenario, ApplicationType applicationType)
        {
            var logger = new LoggerFactory()
                         .AddConsole()
                         .CreateLogger(string.Format("ResponseFormats:{0}:{1}:{2}:{3}", serverType, runtimeFlavor, architecture, applicationType));

            using (logger.BeginScope("ResponseFormatsTest"))
            {
                var deploymentParameters = new DeploymentParameters(Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
                {
                    ApplicationBaseUriHint      = applicationBaseUrl,
                    EnvironmentName             = "Responses",
                    ServerConfigTemplateContent = Helpers.GetConfigContent(serverType, "Http.config", "nginx.conf"),
                    SiteName        = "HttpTestSite", // This is configured in the Http.config
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
                    ApplicationType = applicationType
                };

                using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
                {
                    var deploymentResult  = deployer.Deploy();
                    var httpClientHandler = new HttpClientHandler();
                    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);

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

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

                    await scenario(httpClient, logger);
                }
            }
        }
Ejemplo n.º 30
0
        public async Task <DeploymentResult> CreateDeploymentAsync(ILoggerFactory loggerFactory)
        {
            lock (_deploymentLock)
            {
                if (_deploymentTask == null)
                {
                    var deploymentParameters = GetDeploymentParameters();
                    _deployer       = ApplicationDeployerFactory.Create(deploymentParameters, loggerFactory);
                    _deploymentTask = _deployer.DeployAsync();
                }
            }

            return(await _deploymentTask);
        }