Exemplo n.º 1
0
        public void SetupChannelShouldCallSetupClientIfRunnerIsClient()
        {
            var connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":124",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };
            ProtocolConfig protocolConfig = new ProtocolConfig {
                Version = 2
            };
            var mockCommunicationEndpoint = new Mock <ICommunicationEndPoint>();

            mockCommunicationEndpoint.Setup(mc => mc.Start(connectionInfo.Endpoint)).Returns(connectionInfo.Endpoint).Callback(() =>
            {
                mockCommunicationEndpoint.Raise(
                    s => s.Connected += null,
                    mockCommunicationEndpoint.Object,
                    new ConnectedEventArgs(this.mockChannel.Object));
            });

            this.SetupChannelMessage(MessageType.VersionCheck, MessageType.VersionCheck, protocolConfig.Version);
            var testRequestSender = new TestRequestSender(mockCommunicationEndpoint.Object, connectionInfo, mockDataSerializer.Object, new ProtocolConfig {
                Version = 2
            }, CLIENTPROCESSEXITWAIT);

            this.mockTestHostManager.Setup(thm => thm.GetTestHostConnectionInfo()).Returns(connectionInfo);

            var localTestOperationManager = new TestableProxyOperationManager(this.mockRequestData.Object, testRequestSender, this.mockTestHostManager.Object);

            localTestOperationManager.SetupChannel(Enumerable.Empty <string>());

            mockCommunicationEndpoint.Verify(s => s.Start(It.IsAny <string>()), Times.Once);
        }
Exemplo n.º 2
0
        private static TestHostConnectionInfo GetConnectionInfo(IDictionary <string, string> argsDictionary)
        {
            // vstest.console < 15.5 won't send endpoint and role arguments.
            // So derive endpoint from port argument and Make connectionRole as Client.
            var endpoint = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, EndpointArgument);

            if (string.IsNullOrWhiteSpace(endpoint))
            {
                var port = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, "--port");
                endpoint = IPAddress.Loopback + ":" + port;
            }

            EqtTrace.Info("DefaultEngineInvoker.GetConnectionInfo: Initialize communication on endpoint address: '{0}'", endpoint);

            var    connectionRole = ConnectionRole.Client;
            string role           = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, RoleArgument);

            if (!string.IsNullOrWhiteSpace(role) && string.Equals(role, "host", StringComparison.OrdinalIgnoreCase))
            {
                connectionRole = ConnectionRole.Host;
            }

            // Start Processing of requests
            var connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = endpoint,
                Role      = connectionRole,
                Transport = Transport.Sockets
            };

            return(connectionInfo);
        }
Exemplo n.º 3
0
        public void SetupChannelShouldCallSetupClientIfRunnerIsClient()
        {
            var connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };
            ProtocolConfig protocolConfig = new ProtocolConfig {
                Version = 2
            };
            var mockCommunicationManager = new Mock <ICommunicationManager>();

            mockCommunicationManager.Setup(mc => mc.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, 0)));
            mockCommunicationManager.Setup(mc => mc.WaitForServerConnection(It.IsAny <int>())).Returns(true);
            var mockDataSerializer = new Mock <IDataSerializer>();
            var testRequestSender  = new TestRequestSender(mockCommunicationManager.Object, connectionInfo, mockDataSerializer.Object, new ProtocolConfig {
                Version = 2
            });

            this.mockTestHostManager.Setup(thm => thm.GetTestHostConnectionInfo()).Returns(connectionInfo);
            var message = new Message()
            {
                MessageType = MessageType.VersionCheck, Payload = protocolConfig.Version
            };

            mockCommunicationManager.Setup(mc => mc.ReceiveMessage()).Returns(message);
            mockDataSerializer.Setup(ds => ds.DeserializePayload <int>(It.IsAny <Message>())).Returns(protocolConfig.Version);

            var localTestOperationManager = new TestableProxyOperationManager(testRequestSender, this.mockTestHostManager.Object, this.connectionTimeout);

            localTestOperationManager.SetupChannel(Enumerable.Empty <string>(), CancellationToken.None);

            mockCommunicationManager.Verify(s => s.SetupClientAsync(It.IsAny <IPEndPoint>()), Times.Once);
        }
Exemplo n.º 4
0
        public TestRequestHandlerTests()
        {
            this.mockCommunicationClient = new Mock <ICommunicationEndPoint>();
            this.mockChannel             = new Mock <ICommunicationChannel>();
            this.dataSerializer          = JsonDataSerializer.Instance;
            this.testHostConnectionInfo  = new TestHostConnectionInfo
            {
                Endpoint = IPAddress.Loopback + ":123",
                Role     = ConnectionRole.Host
            };

            this.jobQueue = new JobQueue <Action>(
                action => { action(); },
                "TestHostOperationQueue",
                500,
                25000000,
                true,
                message => EqtTrace.Error(message));

            // Setup mock discovery and execution managers
            this.mockTestHostManagerFactory = new Mock <ITestHostManagerFactory>();
            this.mockDiscoveryManager       = new Mock <IDiscoveryManager>();
            this.mockExecutionManager       = new Mock <IExecutionManager>();
            this.mockTestHostManagerFactory.Setup(mf => mf.GetDiscoveryManager()).Returns(this.mockDiscoveryManager.Object);
            this.mockTestHostManagerFactory.Setup(mf => mf.GetExecutionManager()).Returns(this.mockExecutionManager.Object);

            this.requestHandler = new TestableTestRequestHandler(
                this.testHostConnectionInfo,
                this.mockCommunicationClient.Object,
                JsonDataSerializer.Instance,
                jobQueue);
        }
Exemplo n.º 5
0
        private void SetupReceiveRawMessageAsyncAndDeserializeMessageAndInitialize(string rawMessage, Message message)
        {
            TestHostConnectionInfo connectionInfo;

            connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Client,
                Transport = Transport.Sockets
            };
            this.mockCommunicationManager = new Mock <ICommunicationManager>();
            this.mockDataSerializer       = new Mock <IDataSerializer>();
            this.testRequestSender        = new TestRequestSender(this.mockCommunicationManager.Object, connectionInfo, this.mockDataSerializer.Object, this.protocolConfig);
            this.mockCommunicationManager.Setup(mc => mc.HostServer(It.IsAny <IPEndPoint>())).Returns(new IPEndPoint(IPAddress.Loopback, 0));
            this.mockCommunicationManager.Setup(mc => mc.WaitForClientConnection(It.IsAny <int>())).Returns(true);
            this.testRequestSender.InitializeCommunication();
            this.mockCommunicationManager.Setup(mc => mc.ReceiveRawMessageAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(rawMessage));
            this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(rawMessage)).Returns(message);

            this.testDiscoveryManager = new ProxyDiscoveryManager(
                this.mockRequestData.Object,
                this.testRequestSender,
                this.mockTestHostManager.Object,
                this.mockDataSerializer.Object,
                this.testableClientConnectionTimeout);

            this.CheckAndSetProtocolVersion();
        }
Exemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestRequestSender"/> class.
 /// Used only for testing to inject communication endpoint.
 /// </summary>
 /// <param name="communicationEndPoint">Communication server implementation.</param>
 /// <param name="connectionInfo">ConnectionInfo to set up transport layer</param>
 /// <param name="serializer">Serializer implementation.</param>
 /// <param name="protocolConfig">Protocol configuration.</param>
 /// <param name="clientExitedWaitTime">Time to wait for client process exit.</param>
 internal TestRequestSender(
     ICommunicationEndPoint communicationEndPoint,
     TestHostConnectionInfo connectionInfo,
     IDataSerializer serializer,
     ProtocolConfig protocolConfig,
     int clientExitedWaitTime)
     : this(connectionInfo, serializer, protocolConfig, clientExitedWaitTime)
 {
     this.communicationEndpoint = communicationEndPoint;
 }
        public void GetTestHostConnectionInfoShouldIncludeEndpointRoleAndChannelType()
        {
            var connectionInfo = new TestHostConnectionInfo {
                Endpoint = "127.0.0.1:0", Role = ConnectionRole.Client, Transport = Transport.Sockets
            };

            var info = this.dotnetHostManager.GetTestHostConnectionInfo();

            Assert.AreEqual(connectionInfo, info);
        }
 protected TestRequestHandler(TestHostConnectionInfo connectionInfo, ICommunicationEndpointFactory communicationEndpointFactory, IDataSerializer dataSerializer, JobQueue <Action> jobQueue, Action <Message> onAckMessageRecieved)
 {
     this.communicationEndpointFactory = communicationEndpointFactory;
     this.ConnectionInfo              = connectionInfo;
     this.dataSerializer              = dataSerializer;
     this.requestSenderConnected      = new ManualResetEventSlim(false);
     this.testHostManagerFactoryReady = new ManualResetEventSlim(false);
     this.sessionCompleted            = new ManualResetEventSlim(false);
     this.onAckMessageRecieved        = onAckMessageRecieved;
     this.jobQueue = jobQueue;
 }
Exemplo n.º 9
0
 public void TestInit()
 {
     this.connectionInfo = new TestHostConnectionInfo
     {
         Endpoint  = IPAddress.Loopback + ":0",
         Role      = ConnectionRole.Client,
         Transport = Transport.Sockets
     };
     this.mockCommunicationManager = new Mock <ICommunicationManager>();
     this.mockDataSerializer       = new Mock <IDataSerializer>();
     this.testRequestHandler       = new TestRequestHandler(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object);
 }
Exemplo n.º 10
0
 public void TestInit()
 {
     this.connectionInfo = new TestHostConnectionInfo
     {
         Endpoint  = IPAddress.Loopback + ":0",
         Role      = ConnectionRole.Client,
         Transport = Transport.Sockets
     };
     this.mockCommunicationManager = new Mock <ICommunicationManager>();
     this.mockDataSerializer       = new Mock <IDataSerializer>();
     this.testRequestSender        = new TestRequestSender(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object, this.protocolConfig);
     this.CheckAndSetProtocolVersion();
 }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestRequestSender"/> class.
        /// </summary>
        /// <param name="communicationManager">Communication Manager for sending and receiving messages.</param>
        /// <param name="connectionInfo">ConnectionInfo to set up transport layer</param>
        /// <param name="dataSerializer">Serializer for serialization and deserialization of the messages.</param>
        /// <param name="protocolConfig">Protocol related information</param>
        internal TestRequestSender(ICommunicationManager communicationManager, TestHostConnectionInfo connectionInfo, IDataSerializer dataSerializer, ProtocolConfig protocolConfig)
        {
            this.highestSupportedVersion = protocolConfig.Version;
            this.communicationManager    = communicationManager;

            // The connectionInfo here is that of RuntimeProvider, so reverse the role of runner.
            connectionInfo.Role = connectionInfo.Role == ConnectionRole.Host
                                                ? ConnectionRole.Client
                                                : ConnectionRole.Host;

            this.transport      = new SocketTransport(communicationManager, connectionInfo);
            this.dataSerializer = dataSerializer;
        }
Exemplo n.º 12
0
 public TestableTestRequestHandler(
     TestHostConnectionInfo testHostConnectionInfo,
     ICommunicationEndpointFactory communicationEndpointFactory,
     IDataSerializer dataSerializer,
     JobQueue <Action> jobQueue)
     : base(
         testHostConnectionInfo,
         communicationEndpointFactory,
         dataSerializer,
         jobQueue,
         OnLaunchAdapterProcessWithDebuggerAttachedAckReceived,
         OnAttachDebuggerAckRecieved)
 {
 }
Exemplo n.º 13
0
        public void CloseShouldCallStopServerOnCommunicationManagerIfTestRunnerIsServer()
        {
            // These settings are that recieved by Test runtime(testhost)
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };

            this.testRequestHandler = new TestRequestHandler(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object);
            this.testRequestHandler.Close();

            this.mockCommunicationManager.Verify(mc => mc.StopServer(), Times.Once);
        }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestRequestSender"/> class.
 /// Used only for testing to inject communication endpoint.
 /// </summary>
 /// <param name="communicationEndPoint">Communication server implementation.</param>
 /// <param name="connectionInfo">ConnectionInfo to set up transport layer</param>
 /// <param name="serializer">Serializer implementation.</param>
 /// <param name="protocolConfig">Protocol configuration.</param>
 /// <param name="clientExitedWaitTime">Time to wait for client process exit.</param>
 internal TestRequestSender(
     ICommunicationEndPoint communicationEndPoint,
     TestHostConnectionInfo connectionInfo,
     IDataSerializer serializer,
     ProtocolConfig protocolConfig,
     int clientExitedWaitTime)
     : this(
         runtimeProvider : null,
         communicationEndPoint,
         connectionInfo,
         serializer,
         protocolConfig,
         clientExitedWaitTime)
 {
 }
Exemplo n.º 15
0
        private string SetupFakeCommunicationChannel(string connectionArgs = "123")
        {
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":" + connectionArgs,
                Role      = ConnectionRole.Client,
                Transport = Transport.Sockets
            };

            // Setup mock connected event and initialize communication channel
            this.mockServer.Setup(mc => mc.Start(this.connectionInfo.Endpoint))
            .Returns(this.connectionInfo.Endpoint)
            .Callback(() => this.mockServer.Raise(s => s.Connected += null, this.mockServer.Object, this.connectedEventArgs));

            return(this.testRequestSender.InitializeCommunication().ToString());
        }
Exemplo n.º 16
0
        public void WaitForRequestHandlerConnectionShouldCallWaitForServerConnectionIfTestRunnerIsClient()
        {
            // These settings are that of Test runtime(testhost)
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };

            this.testRequestSender = new TestRequestSender(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object, this.protocolConfig);
            this.CheckAndSetProtocolVersion();

            this.testRequestSender.WaitForRequestHandlerConnection(123);

            this.mockCommunicationManager.Verify(mc => mc.WaitForServerConnection(123), Times.Once);
        }
Exemplo n.º 17
0
        public void InitializeCommunicationShouldThrowIfServerIsNotAccessible()
        {
            var connectionInfo = new TestHostConnectionInfo
            {
                Endpoint = IPAddress.Loopback + ":123",
                Role = ConnectionRole.Host
            };
            var socketClient = new SocketClient();
            socketClient.Connected += (sender, connectedEventArgs) =>
            {
                Assert.IsFalse(connectedEventArgs.Connected);
                Assert.AreEqual(typeof(SocketException), connectedEventArgs.Fault.InnerException.GetType());
            };
            var rh = new TestableTestRequestHandler(connectionInfo, socketClient, this.dataSerializer, this.jobQueue);

            rh.InitializeCommunication();
            this.requestHandler.WaitForRequestSenderConnection(1000);
        }
Exemplo n.º 18
0
        public void InitializeCommunicationShouldSetUpClientIfTestRunnerIsClient()
        {
            this.mockCommunicationManager.Setup(mc => mc.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, 0)));

            // These settings are that of Test runtime(testhost)
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };
            this.testRequestSender = new TestRequestSender(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object, this.protocolConfig);
            this.CheckAndSetProtocolVersion();

            this.testRequestSender.InitializeCommunication();

            this.mockCommunicationManager.Verify(mc => mc.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, 0)), Times.Once);
        }
Exemplo n.º 19
0
        public void InitializeCommunicationShouldHostServerAndAcceptClientIfTestHostIsServer()
        {
            this.mockCommunicationManager.Setup(mc => mc.HostServer(new IPEndPoint(IPAddress.Loopback, 0))).Returns(new IPEndPoint(IPAddress.Loopback, 123));

            // These settings are that received by(testhost)
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Host,
                Transport = Transport.Sockets
            };
            this.testRequestHandler = new TestRequestHandler(this.mockCommunicationManager.Object, this.connectionInfo, this.mockDataSerializer.Object);

            this.testRequestHandler.InitializeCommunication();

            this.mockCommunicationManager.Verify(mc => mc.HostServer(new IPEndPoint(IPAddress.Loopback, 0)), Times.Once);
            this.mockCommunicationManager.Verify(mc => mc.AcceptClientAsync(), Times.Once);
        }
Exemplo n.º 20
0
        protected TestRequestHandler(TestHostConnectionInfo connectionInfo, IDataSerializer dataSerializer)
        {
            this.connectionInfo              = connectionInfo;
            this.dataSerializer              = dataSerializer;
            this.requestSenderConnected      = new ManualResetEventSlim(false);
            this.sessionCompleted            = new ManualResetEventSlim(false);
            this.testHostManagerFactoryReady = new ManualResetEventSlim(false);
            this.onAckMessageRecieved        = (message) => { throw new NotImplementedException(); };

            this.SetCommunicationEndPoint();

            this.jobQueue = new JobQueue <Action>(
                (action) => { action(); },
                "TestHostOperationQueue",
                500,
                25000000,
                true,
                (message) => EqtTrace.Error(message));
        }
Exemplo n.º 21
0
        internal TestRequestSender(
            TestHostConnectionInfo connectionInfo,
            IDataSerializer serializer,
            ProtocolConfig protocolConfig,
            int clientExitedWaitTime)
        {
            this.dataSerializer       = serializer;
            this.connected            = new ManualResetEventSlim(false);
            this.clientExited         = new ManualResetEventSlim(false);
            this.clientExitedWaitTime = clientExitedWaitTime;
            this.operationCompleted   = 0;

            this.highestSupportedVersion = protocolConfig.Version;

            // The connectionInfo here is that of RuntimeProvider, so reverse the role of runner.
            this.connectionInfo.Endpoint = connectionInfo.Endpoint;
            this.connectionInfo.Role     = connectionInfo.Role == ConnectionRole.Host
                ? ConnectionRole.Client
                : ConnectionRole.Host;
        }
Exemplo n.º 22
0
        public TestRequestSenderTests()
        {
            this.connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":123",
                Role      = ConnectionRole.Client,
                Transport = Transport.Sockets
            };
            this.mockChannel        = new Mock <ICommunicationChannel>();
            this.mockServer         = new Mock <ICommunicationEndPoint>();
            this.mockDataSerializer = new Mock <IDataSerializer>();
            this.testRequestSender  = new TestableTestRequestSender(this.mockServer.Object, this.connectionInfo, this.mockDataSerializer.Object, new ProtocolConfig {
                Version = DUMMYPROTOCOLVERSION
            });

            this.connectedEventArgs         = new ConnectedEventArgs(this.mockChannel.Object);
            this.mockDiscoveryEventsHandler = new Mock <ITestDiscoveryEventsHandler2>();
            this.mockExecutionEventsHandler = new Mock <ITestRunEventsHandler>();
            this.testRunCriteriaWithSources = new TestRunCriteriaWithSources(new Dictionary <string, IEnumerable <string> >(), "runsettings", null, null);
        }
Exemplo n.º 23
0
        private void SetupAndInitializeTestRequestSender()
        {
            var connectionInfo = new TestHostConnectionInfo
            {
                Endpoint  = IPAddress.Loopback + ":0",
                Role      = ConnectionRole.Client,
                Transport = Transport.Sockets
            };

            this.mockCommunicationEndpoint = new Mock <ICommunicationEndPoint>();
            this.mockDataSerializer        = new Mock <IDataSerializer>();
            this.testRequestSender         = new TestRequestSender(this.mockCommunicationEndpoint.Object, connectionInfo, this.mockDataSerializer.Object, this.protocolConfig, CLIENTPROCESSEXITWAIT);
            this.mockCommunicationEndpoint.Setup(mc => mc.Start(connectionInfo.Endpoint)).Returns(connectionInfo.Endpoint).Callback(() =>
            {
                this.mockCommunicationEndpoint.Raise(
                    s => s.Connected += null,
                    this.mockCommunicationEndpoint.Object,
                    new ConnectedEventArgs(this.mockChannel.Object));
            });
            this.SetupChannelMessage(MessageType.VersionCheck, MessageType.VersionCheck, this.protocolConfig.Version);

            this.testRequestSender.InitializeCommunication();
        }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestRequestSender"/> class.
 /// </summary>
 /// <param name="protocolConfig">Protocol related information</param>
 /// <param name="connectionInfo">Transport layer to set up connection</param>
 public TestRequestSender(ProtocolConfig protocolConfig, TestHostConnectionInfo connectionInfo)
     : this(new SocketCommunicationManager(), connectionInfo, JsonDataSerializer.Instance, protocolConfig)
 {
 }
Exemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestRequestSender"/> class.
 /// </summary>
 /// <param name="protocolConfig">Protocol configuration.</param>
 /// <param name="connectionInfo">Transport layer to set up connection</param>
 public TestRequestSender(ProtocolConfig protocolConfig, TestHostConnectionInfo connectionInfo)
     : this(connectionInfo, JsonDataSerializer.Instance, protocolConfig, ClientProcessExitWaitTimeout)
 {
     this.SetCommunicationEndPoint();
 }
Exemplo n.º 26
0
        /// <summary>
        /// Ensure that the engine is ready for test operations.
        /// Usually includes starting up the test host process.
        /// </summary>
        /// <param name="sources">
        /// List of test sources.
        /// </param>
        /// <param name="cancellationToken">
        /// </param>
        /// <returns>
        /// Returns true if Communation is established b/w runner and host
        /// </returns>
        public virtual bool SetupChannel(IEnumerable <string> sources)
        {
            this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();
            var connTimeout = EnvironmentHelper.GetConnectionTimeout();

            if (!this.initialized)
            {
                this.testHostProcessStdError = string.Empty;
                TestHostConnectionInfo testHostConnectionInfo = this.testHostManager.GetTestHostConnectionInfo();
                var portNumber = 0;

                if (testHostConnectionInfo.Role == ConnectionRole.Client)
                {
                    portNumber = this.RequestSender.InitializeCommunication();
                    testHostConnectionInfo.Endpoint += portNumber;
                }

                var processId      = this.processHelper.GetCurrentProcessId();
                var connectionInfo = new TestRunnerConnectionInfo {
                    Port = portNumber, ConnectionInfo = testHostConnectionInfo, RunnerProcessId = processId, LogFile = this.GetTimestampedLogFile(EqtTrace.LogFile), TraceLevel = (int)EqtTrace.TraceLevel
                };

                // Subscribe to TestHost Event
                this.testHostManager.HostLaunched += this.TestHostManagerHostLaunched;
                this.testHostManager.HostExited   += this.TestHostManagerHostExited;

                // Get the test process start info
                var testHostStartInfo = this.UpdateTestProcessStartInfo(this.testHostManager.GetTestHostProcessStartInfo(sources, null, connectionInfo));
                try
                {
                    // Launch the test host.
                    var hostLaunchedTask = this.testHostManager.LaunchTestHostAsync(testHostStartInfo, this.CancellationTokenSource.Token);
                    this.testHostLaunched = hostLaunchedTask.Result;

                    if (this.testHostLaunched && testHostConnectionInfo.Role == ConnectionRole.Host)
                    {
                        // If test runtime is service host, try to poll for connection as client
                        this.RequestSender.InitializeCommunication();
                    }
                }
                catch (Exception ex)
                {
                    EqtTrace.Error("ProxyOperationManager: Failed to launch testhost :{0}", ex);

                    this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();
                    throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.FailedToLaunchTestHost, ex.ToString()));
                }

                // Warn the user that execution will wait for debugger attach.
                var hostDebugEnabled = Environment.GetEnvironmentVariable("VSTEST_HOST_DEBUG");
                if (!string.IsNullOrEmpty(hostDebugEnabled) && hostDebugEnabled.Equals("1", StringComparison.Ordinal))
                {
                    ConsoleOutput.Instance.WriteLine(CrossPlatEngineResources.HostDebuggerWarning, OutputLevel.Warning);
                    ConsoleOutput.Instance.WriteLine(
                        string.Format("Process Id: {0}, Name: {1}", this.testHostProcessId, this.processHelper.GetProcessName(this.testHostProcessId)),
                        OutputLevel.Information);

                    // Increase connection timeout when debugging is enabled.
                    connTimeout *= 5;
                }

                // If TestHost does not launch then throw exception
                // If Testhost launches, wait for connection.
                if (!this.testHostLaunched ||
                    !this.RequestSender.WaitForRequestHandlerConnection(connTimeout * 1000, this.CancellationTokenSource.Token))
                {
                    this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();
                    this.ThrowExceptionOnConnectionFailure(connTimeout);
                }

                // Handling special case for dotnet core projects with older test hosts
                // Older test hosts are not aware of protocol version check
                // Hence we should not be sending VersionCheck message to these test hosts
                this.CompatIssueWithVersionCheckAndRunsettings();

                if (this.versionCheckRequired)
                {
                    this.RequestSender.CheckVersionWithTestHost();
                }

                this.initialized = true;
            }

            return(true);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Ensures that the engine is ready for test operations. Usually includes starting up the
        /// test host process.
        /// </summary>
        ///
        /// <param name="sources">List of test sources.</param>
        /// <param name="runSettings">Run settings to be used.</param>
        ///
        /// <returns>
        /// Returns true if the communication is established b/w runner and host, false otherwise.
        /// </returns>
        public virtual bool SetupChannel(IEnumerable <string> sources, string runSettings)
        {
            this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();

            //System.Diagnostics.Debugger.Launch();
            //System.Diagnostics.Debugger.Break();

            if (this.initialized)
            {
                return(true);
            }

            var connTimeout = EnvironmentHelper.GetConnectionTimeout();

            this.testHostProcessStdError = string.Empty;
            TestHostConnectionInfo testHostConnectionInfo = this.TestHostManager.GetTestHostConnectionInfo();

            var portNumber = 0;

            if (testHostConnectionInfo.Role == ConnectionRole.Client)
            {
                portNumber = this.RequestSender.InitializeCommunication();
                testHostConnectionInfo.Endpoint += portNumber;
            }

            var processId      = this.processHelper.GetCurrentProcessId();
            var connectionInfo = new TestRunnerConnectionInfo()
            {
                Port            = portNumber,
                ConnectionInfo  = testHostConnectionInfo,
                RunnerProcessId = processId,
                LogFile         = this.GetTimestampedLogFile(EqtTrace.LogFile),
                TraceLevel      = (int)EqtTrace.TraceLevel
            };

            // Subscribe to test host events.
            this.TestHostManager.HostLaunched += this.TestHostManagerHostLaunched;
            this.TestHostManager.HostExited   += this.TestHostManagerHostExited;

            // Get environment variables from run settings.
            var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettings);

            // Get the test process start info.
            var hostStartInfo = this.TestHostManager.GetTestHostProcessStartInfo(
                sources,
                envVars,
                connectionInfo);


            EqtTrace.Verbose("DefaultTestHostmanager::Received path is: " + hostStartInfo.FileName);

            if (!File.Exists(hostStartInfo.FileName))
            {
                // Somehow can not set path to file in Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DefaultTestHostManager::GetTestHostProcessStartInfo()
                // :( :( :( Why ?? :(
                var fileName         = Path.GetFileName(hostStartInfo.FileName);
                var directory        = Path.GetDirectoryName(hostStartInfo.FileName);
                var frameworkMoniker = fileName.Split('.');

                EqtTrace.Verbose("DefaultTestHostmanager::[1] directory is: " + directory);

                while (directory.Contains("\\TestHost"))
                {
                    directory = directory.Replace("\\TestHost", "");
                }

                EqtTrace.Verbose("DefaultTestHostmanager::[2] directory is: " + directory);

                if (directory.Contains("\\TestsHosts") == false)
                {
                    fileName = Path.Combine(directory, "TestsHosts", frameworkMoniker[1], "win7-x86", fileName);
                }
                else
                {
                    fileName = Path.Combine(directory, frameworkMoniker[1], "win7-x86", fileName);
                }

                hostStartInfo.FileName = fileName;

                EqtTrace.Verbose("DefaultTestHostmanager::Fixed path to: " + hostStartInfo.FileName);
            }

            var testHostStartInfo = this.UpdateTestProcessStartInfo(hostStartInfo);

            try
            {
                // Launch the test host.
                var hostLaunchedTask = this.TestHostManager.LaunchTestHostAsync(
                    testHostStartInfo,
                    this.CancellationTokenSource.Token);
                this.testHostLaunched = hostLaunchedTask.Result;

                if (this.testHostLaunched && testHostConnectionInfo.Role == ConnectionRole.Host)
                {
                    // If test runtime is service host, try to poll for connection as client.
                    this.RequestSender.InitializeCommunication();
                }
            }
            catch (Exception ex)
            {
                EqtTrace.Error("ProxyOperationManager: Failed to launch testhost :{0}", ex);

                this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();
                throw new TestPlatformException(string.Format(
                                                    CultureInfo.CurrentUICulture,
                                                    CrossPlatEngineResources.FailedToLaunchTestHost,
                                                    ex.ToString()));
            }

            // Warn the user that execution will wait for debugger attach.
            var hostDebugEnabled       = Environment.GetEnvironmentVariable("VSTEST_HOST_DEBUG");
            var nativeHostDebugEnabled = Environment.GetEnvironmentVariable("VSTEST_HOST_NATIVE_DEBUG");

            if (!string.IsNullOrEmpty(hostDebugEnabled) && hostDebugEnabled.Equals("1", StringComparison.Ordinal) ||
                new PlatformEnvironment().OperatingSystem.Equals(PlatformOperatingSystem.Windows) &&
                !string.IsNullOrEmpty(nativeHostDebugEnabled) && nativeHostDebugEnabled.Equals("1", StringComparison.Ordinal))
            {
                ConsoleOutput.Instance.WriteLine(
                    CrossPlatEngineResources.HostDebuggerWarning,
                    OutputLevel.Warning);

                ConsoleOutput.Instance.WriteLine(
                    string.Format(
                        "Process Id: {0}, Name: {1}",
                        this.testHostProcessId,
                        this.processHelper.GetProcessName(this.testHostProcessId)),
                    OutputLevel.Information);

                // Increase connection timeout when debugging is enabled.
                connTimeout *= 5;
            }

            // If test host does not launch then throw exception, otherwise wait for connection.
            if (!this.testHostLaunched ||
                !this.RequestSender.WaitForRequestHandlerConnection(
                    connTimeout * 1000,
                    this.CancellationTokenSource.Token))
            {
                EqtTrace.Verbose($"Test host failed to start Test host launched:{testHostLaunched} test host exited: {testHostExited.IsSet}");
                // Throw a test platform exception with the appropriate message if user requested cancellation.
                this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested();

                // Throw a test platform exception along with the error messages from the test if the test host exited unexpectedly
                // before communication was established.
                this.ThrowOnTestHostExited(this.testHostExited.IsSet);

                // Throw a test platform exception stating the connection to test could not be established even after waiting
                // for the configure timeout period.
                this.ThrowExceptionOnConnectionFailure(connTimeout);
            }

            // Handling special case for dotnet core projects with older test hosts.
            // Older test hosts are not aware of protocol version check, hence we should not be
            // sending VersionCheck message to these test hosts.
            this.CompatIssueWithVersionCheckAndRunsettings();

            if (this.versionCheckRequired)
            {
                this.RequestSender.CheckVersionWithTestHost();
            }

            this.initialized = true;

            return(true);
        }
Exemplo n.º 28
0
 public TestableTestRequestSender(ICommunicationEndPoint commEndpoint, TestHostConnectionInfo connectionInfo, IDataSerializer serializer, ProtocolConfig protocolConfig)
     : base(commEndpoint, connectionInfo, serializer, protocolConfig, 0)
 {
 }
 public TestableTestRequestHandler(TestHostConnectionInfo testHostConnectionInfo, ICommunicationEndpointFactory communicationEndpointFactory, IDataSerializer dataSerializer, JobQueue <Action> jobQueue)
     : base(testHostConnectionInfo, communicationEndpointFactory, dataSerializer, jobQueue, OnAckMessageReceived)
 {
 }
Exemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestRequestHandler2" />.
 /// </summary>
 public TestRequestHandler(TestHostConnectionInfo connectionInfo) : this(connectionInfo, JsonDataSerializer.Instance)
 {
 }