Example #1
0
        /// <summary>
        /// Start the web application .exe as web server with optional parameters
        /// overriding the default configuration in appsettings.json:
        /// Server: path to the server.exe (the .NET Core binary)
        /// Root: server application root directory
        /// Port: port to listen on
        /// RequestTimeout: expected duration of all tests in sec
        /// ServerStartTimeout: expected start time of the server in sec
        /// </summary>
        /// <param name="config">default configuration</param>
        /// <param name="server">explicit path to the server.exe (the .NET Core binary)</param>
        /// <param name="root">explicit server application root directory</param>
        /// <param name="port">explicit port to listen on</param>
        /// <param name="timeout">explicit expected duration of all tests in sec</param>
        /// <param name="servertimeout">expected start time of the server in sec</param>
        public static void StartServer(this ITestServer inst, IConfiguration config,
                                       string server = null, string root       = null, int?port = null,
                                       int?timeout   = null, int?servertimeout = null)
        {
            string cserver        = server ?? config["Server"];
            string croot          = root ?? config["Root"];
            int    cport          = port ?? config.GetValue <int>("Port");
            int    ctimeout       = timeout ?? config.GetValue <int>("RequestTimeout");
            int    cservertimeout = servertimeout ?? config.GetValue <int>("ServerStartTimeout");

            var info = new ProcessStartInfo();

            info.FileName         = Path.GetFullPath(Path.Join(TestContext.CurrentContext.WorkDirectory, cserver));
            info.Arguments        = String.Format("--urls=http://localhost:{0}/", cport);
            info.WorkingDirectory = Path.GetFullPath(Path.Join(TestContext.CurrentContext.WorkDirectory, croot));
            info.UseShellExecute  = true;
            inst.ServerProcess    = Process.Start(info);
            TestServerExtensionBase.WaitForServerPort(cport, cservertimeout);
            SeleniumExtensionBase.OutOfProcess   = true;
            SeleniumExtensionBase.Port           = cport;
            SeleniumExtensionBase.RequestTimeout = ctimeout;
            inst.driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ctimeout); // too late after OneTimeSetUBrowser()

            TestServerIPC.CreateOrOpenMmmfs();                                         // Create as parent process
        }
        private static async Task <T> ThrowsException <T>(ITestServer server) where T : Exception
        {
            return(await server.ExecuteAsync(async address =>
            {
                // Arrange
                var retryHandler = new HttpRetryHandler();
                var countingHandler = new CountingHandler {
                    InnerHandler = new HttpClientHandler()
                };
                var httpClient = new HttpClient(countingHandler);
                var request = new HttpRetryHandlerRequest(httpClient, () => new HttpRequestMessage(HttpMethod.Get, address))
                {
                    MaxTries = 2,
                    RetryDelay = TimeSpan.Zero
                };

                // Act
                Func <Task> actionAsync = () => retryHandler.SendAsync(
                    request,
                    new TestLogger(),
                    CancellationToken.None);

                // Act & Assert
                var exception = await Assert.ThrowsAsync <T>(actionAsync);
                Assert.Equal(2, countingHandler.Hits);
                return exception;
            }));
        }
Example #3
0
        /// <summary>
        /// Start IIS Express according with optional parameters
        /// overriding the default configuration in App.config
        /// Server: IIS Express, optionally overrides %PROGRAMFILES%\IIS Express\iisexpress.exe
        /// Root: server application root directory
        /// Port: port to listen on
        /// RequestTimeout: expected duration of all tests in sec
        /// ServerStartTimeout: expected start time of the server in sec
        /// </summary>
        /// <param name="server">IIS Express, usually %PROGRAMFILES%\IIS Express\iisexpress.exe</param>
        /// <param name="root">server application root directory</param>
        /// <param name="port">port to listen on</param>
        /// <param name="timeout">expected duration of all tests in sec</param>
        /// <param name="servertimeout">expected start time of the server in sec</param>
        public static void StartServer(this ITestServer inst, string server = null, string root = null,
                                       int?port = null, int?timeout = null, int?servertimeout = null)
        {
            string cserver = server ?? ConfigurationManager.AppSettings["Server"] ??
                             @"%PROGRAMFILES%\IIS Express\iisexpress.exe";
            string croot          = root ?? ConfigurationManager.AppSettings["Root"];
            int    cport          = port ?? int.Parse(ConfigurationManager.AppSettings["Port"]);
            int    ctimeout       = timeout ?? int.Parse(ConfigurationManager.AppSettings["RequestTimeout"]);
            int    cservertimeout = servertimeout ?? int.Parse(ConfigurationManager.AppSettings["ServerStartTimeout"]);

            var info = new ProcessStartInfo();

            info.FileName = cserver.Replace("%PROGRAMFILES%",
                                            System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
            var path = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.WorkDirectory, croot));

            info.Arguments       = String.Format("/path:{0} /port:{1} /trace:error", path, cport);
            info.UseShellExecute = true;
            inst.ServerProcess   = Process.Start(info);
            TestServerExtensionBase.WaitForServerPort(cport, cservertimeout);
            SeleniumExtensionBase.OutOfProcess   = true;
            SeleniumExtensionBase.Port           = cport;
            SeleniumExtensionBase.RequestTimeout = ctimeout;
            inst.driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ctimeout); // too late after OneTimeSetUBrowser()

            TestServerIPC.CreateOrOpenMmmfs();                                         // Create as parent process
        }
Example #4
0
        protected async Task RunE2ETestsBase(string methodName, int expectedMessageCount, Func <string, ITestClientSet, Task> coreTask)
        {
            ITestServer server = null;

            try
            {
                server = _testServerFactory.Create(_output);
                var serverUrl = await server.StartAsync();

                var count   = 0;
                var clients = _testClientSetFactory.Create(serverUrl, DefaultClientCount, _output);
                clients.AddListener(methodName, message => Interlocked.Increment(ref count));
                await clients.StartAsync();
                await coreTask(methodName, clients);

                await Task.Delay(DefaultDelayMilliseconds);

                await clients.StopAsync();

                await Task.Delay(DefaultDelayMilliseconds);

                Assert.Equal(expectedMessageCount, count);
            }
            finally
            {
                await server?.StopAsync();
            }
        }
 private TestServerSession(string scenario, TestServerVersion version, bool allowUnmatched, string[] expectedCoverage)
 {
     _scenario         = scenario;
     _version          = version;
     _allowUnmatched   = allowUnmatched;
     _expectedCoverage = expectedCoverage;
     Server            = GetServer();
 }
Example #6
0
 public static IConfiguration GetConfig(this ITestServer inst)
 {
     return(new ConfigurationBuilder()
            .SetBasePath(TestContext.CurrentContext.WorkDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build());
 }
Example #7
0
        public ServiceE2EFactsBase(ITestServer testServer, Func <string, int, ITestClientSet> testClientSetFactory, ITestOutputHelper output) : base(output)
        {
            _testServer           = testServer;
            _testClientSetFactory = testClientSetFactory;

            _verifiableLog = StartVerifiableLog(out var loggerFactory);
            _serverUrl     = _testServer.StartAsync(loggerFactory).Result;
        }
        /// <summary>
        /// Initializes a new instance of <see cref="RespContentApiClientBehavior"/>
        /// </summary>
        public RespContentApiClientBehavior(WebApplicationFactory <Startup> webApplicationFactory, ITestOutputHelper output)
        {
            _output = output;
            var clientProvider = new DelegateHttpClientProvider(webApplicationFactory.CreateClient);

            _client = new ApiClient <ITestServer>(clientProvider);
            _proxy  = ApiProxy <ITestServer> .Create(clientProvider);
        }
        public async Task It_should_get_a_200(ITestServer testServer)
        {
            testServer.Start<Startup>();

            var httpClient = testServer.CreateClient();

            var response = await httpClient.GetAsync("api/values");

            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
Example #10
0
        protected ControllerTestsBase(ITestServer testServer, HttpClient client)
        {
            _testServer        = testServer;
            client.BaseAddress = new Uri("https://www.stackoverflow.com");

            client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");

            client.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
            Client = client;
        }
		//[ClassCleanup]
		public static void ClassCleanup()
		{
			_testServer = null;

			if (_clientChannel != null)
			{
				ChannelServices.UnregisterChannel(_clientChannel);
				_clientChannel = null;
			}

			if (_serverDomain != null)
			{
				AppDomain.Unload(_serverDomain);
				_serverDomain = null;
			}
		}
		//[ClassInitialize]
		public static void ClassInitialize(TestContext context)
		{
			_serverDomain = AppDomain.CreateDomain("ServerDomain #2", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
			_serverDomain.DoCallBack(() =>
			{
				var serverChannel = new IpcServerChannel("ipc server #2", "localhost:9091", new ProtobufServerFormatterSinkProvider { FallbackToBinaryFormatter = true });
				ChannelServices.RegisterChannel(serverChannel, false);

				RemotingServices.Marshal(new TestServer(), "TestServer", typeof(ITestServer));
			});

			_clientChannel = new IpcClientChannel("ipc client #2", new BinaryClientFormatterSinkProvider());
			ChannelServices.RegisterChannel(_clientChannel, false);

			_testServer = (ITestServer)Activator.GetObject(typeof(TestServer), "ipc://localhost:9091/TestServer");
		}
Example #13
0
 /// <summary>
 /// Kill the web server process
 /// </summary>
 /// <param name="inst"></param>
 public static void StopServer(this ITestServer inst)
 {
     TestServerIPC.Dispose();
     try
     {
         if (inst.ServerProcess != null)
         {
             inst.ServerProcess.Kill(); // parent process only in .NET Framework, unlike Core
             inst.ServerProcess.WaitForExit();
         }
     }
     catch { }
     finally
     {
         inst.ServerProcess.Dispose();
         inst.ServerProcess = null;
     }
 }
Example #14
0
 /// <summary>
 /// Kill the web server process
 /// </summary>
 /// <param name="inst"></param>
 public static void StopServer(this ITestServer inst)
 {
     TestServerIPC.Dispose();
     try
     {
         if (inst.ServerProcess != null)
         {
             inst.ServerProcess.Kill(true); // recursive in .NET Core, unlike Framework
             inst.ServerProcess.WaitForExit();
         }
     }
     catch { }
     finally
     {
         inst.ServerProcess.Dispose();
         inst.ServerProcess = null;
     }
 }
        private static async Task <T> ThrowsException <T>(ITestServer server) where T : Exception
        {
            return(await server.ExecuteAsync(async address =>
            {
                int maxTries = 2;
                TimeSpan retryDelay = TimeSpan.Zero;

                TestEnvironmentVariableReader testEnvironmentVariableReader = new TestEnvironmentVariableReader(
                    new Dictionary <string, string>()
                {
                    [EnhancedHttpRetryHelper.RetryCountEnvironmentVariableName] = maxTries.ToString(),
                    [EnhancedHttpRetryHelper.DelayInMillisecondsEnvironmentVariableName] = retryDelay.TotalMilliseconds.ToString()
                });

                // Arrange
                var retryHandler = new HttpRetryHandler(testEnvironmentVariableReader);
                var countingHandler = new CountingHandler {
                    InnerHandler = new HttpClientHandler()
                };
                var httpClient = new HttpClient(countingHandler);
                var request = new HttpRetryHandlerRequest(httpClient, () => new HttpRequestMessage(HttpMethod.Get, address))
                {
                    MaxTries = maxTries,
                    RetryDelay = retryDelay
                };

                // Act
                Func <Task> actionAsync = () => retryHandler.SendAsync(
                    request,
                    new TestLogger(),
                    CancellationToken.None);

                // Act & Assert
                var exception = await Assert.ThrowsAsync <T>(actionAsync);
                Assert.Equal(2, countingHandler.Hits);
                return exception;
            }));
        }
 public TestServiceForProxy(ITestServer server)
 {
     _server = server;
 }
Example #17
0
        /// <summary>
        /// Start the web application .exe as web server according to appsettings.json:
        /// Server: path to the server.exe (the .NET Core binary)
        /// Root: server application root directory
        /// Port: port to listen on
        /// RequestTimeout: expected duration of all tests in sec
        /// ServerStartTimeout: expected start time of the server in sec
        /// </summary>
        public static void StartServer(this ITestServer inst)
        {
            var config = GetConfig(inst);

            StartServer(inst, config);
        }