public bool LaunchProcess(TestProcessStartInfo startInfo, ProcessCallbacks processStreamCallbacks)
        {
            var endpoint = this.InitializeChannel();

            var process = new Process();

            try
            {
                this.InitializeStartInfo(process, startInfo, endpoint);

                process.EnableRaisingEvents = true;
                process.OutputDataReceived += (sender, args) => processStreamCallbacks.outputReceived(sender as Process, args.Data);
                process.ErrorDataReceived  += (sender, args) => processStreamCallbacks.errorReceived(sender as Process, args.Data);
                process.Exited += (sender, args) =>
                {
                    // Call WaitForExit without again to ensure all streams are flushed,
                    var exitingProcess = sender as Process;
                    try
                    {
                        // Add timeout to avoid indefinite waiting on child process exit.
                        if (exitingProcess.WaitForExit(500))
                        {
                            Console.WriteLine("JSTest: Process with id {0} exited successfully.", jsProcessId);
                        }
                        else
                        {
                            Console.Error.WriteLine("JSTest: WaitForExit timed out for process {0}.{1}", jsProcessId);
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        Console.WriteLine("JSTest: Process with id {0} exited successfully.{1}", jsProcessId);
                    }

                    // If exit callback has code that access Process object, ensure that the exceptions handling should be done properly.
                    processStreamCallbacks.exitReceived(exitingProcess);
                };

                EqtTrace.Verbose("JSProcess: Starting process '{0}' with command line '{1}'", startInfo.FileName, startInfo.Arguments);

                process.Start();
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                this.jsProcessId = process.Id;
            }
            catch (Exception exception)
            {
                process.Dispose();
                process = null;

                EqtTrace.Error("JSProcess: Test runner {0} failed to launch with the following exception: {1}", startInfo.FileName, exception.Message);
                throw;
            }

            this.process = process;

            this.channel.WaitForClientConnection(GetConnectionTimeout());

            return(process != null);
        }
        public DotnetTestHostManagerTests()
        {
            this.mockTestHostLauncher  = new Mock <ITestHostLauncher>();
            this.mockProcessHelper     = new Mock <IProcessHelper>();
            this.mockFileHelper        = new Mock <IFileHelper>();
            this.mockMessageLogger     = new Mock <IMessageLogger>();
            this.mockEnvironment       = new Mock <IEnvironment>();
            this.defaultConnectionInfo = new TestRunnerConnectionInfo {
                Port = 123, ConnectionInfo = new TestHostConnectionInfo {
                    Endpoint = "127.0.0.1:123", Role = ConnectionRole.Client
                }, RunnerProcessId = 0
            };

            string defaultSourcePath = Path.Combine($"{Path.DirectorySeparatorChar}tmp", "test.dll");

            this.defaultTestHostPath = @"\tmp\testhost.dll";
            this.dotnetHostManager   = new TestableDotnetTestHostManager(
                this.mockProcessHelper.Object,
                this.mockFileHelper.Object,
                new DotnetHostHelper(this.mockFileHelper.Object, this.mockEnvironment.Object),
                this.mockEnvironment.Object);
            this.dotnetHostManager.Initialize(this.mockMessageLogger.Object, string.Empty);

            this.dotnetHostManager.HostExited += this.DotnetHostManagerHostExited;

            // Setup a dummy current process for tests
            this.mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns(DefaultDotnetPath);
            this.mockProcessHelper.Setup(ph => ph.GetTestEngineDirectory()).Returns(DefaultDotnetPath);
            this.mockFileHelper.Setup(ph => ph.Exists(this.defaultTestHostPath)).Returns(true);

            this.defaultTestProcessStartInfo = this.dotnetHostManager.GetTestHostProcessStartInfo(new[] { defaultSourcePath }, null, this.defaultConnectionInfo);
        }
Beispiel #3
0
 /// <inheritdoc/>
 public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo)
 {
     return(this.processHelper.LaunchProcess(
                defaultTestHostStartInfo.FileName,
                defaultTestHostStartInfo.Arguments,
                defaultTestHostStartInfo.WorkingDirectory).Id);
 }
        public DotnetTestHostManagerTests()
        {
            this.mockTestHostLauncher  = new Mock <ITestHostLauncher>();
            this.mockProcessHelper     = new Mock <IProcessHelper>();
            this.mockFileHelper        = new Mock <IFileHelper>();
            this.mockMessageLogger     = new Mock <IMessageLogger>();
            this.defaultConnectionInfo = default(TestRunnerConnectionInfo);
            string defaultSourcePath = Path.Combine($"{Path.DirectorySeparatorChar}tmp", "test.dll");

            this.defaultTestHostPath = @"\tmp\testhost.dll";
            this.dotnetHostManager   = new TestableDotnetTestHostManager(
                this.mockProcessHelper.Object,
                this.mockFileHelper.Object,
                new DotnetHostHelper(this.mockFileHelper.Object),
                this.maxStdErrStringLength);
            this.dotnetHostManager.Initialize(this.mockMessageLogger.Object, string.Empty);

            this.dotnetHostManager.HostExited += this.DotnetHostManagerHostExited;

            // Setup a dummy current process for tests
            this.mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns(DefaultDotnetPath);
            this.mockProcessHelper.Setup(ph => ph.GetTestEngineDirectory()).Returns(DefaultDotnetPath);
            this.mockFileHelper.Setup(ph => ph.Exists(this.defaultTestHostPath)).Returns(true);

            this.defaultTestProcessStartInfo = this.dotnetHostManager.GetTestHostProcessStartInfo(new[] { defaultSourcePath }, null, this.defaultConnectionInfo);
        }
Beispiel #5
0
        public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo, CancellationToken cancellationToken)
        {
            var processInfo = new ProcessStartInfo(defaultTestHostStartInfo.FileName, defaultTestHostStartInfo.Arguments)
            {
                WorkingDirectory       = defaultTestHostStartInfo.WorkingDirectory,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            processInfo.EnvironmentVariables["ActiveMutation"] = _activeMutation.ToString();

            var process = new Process {
                StartInfo = processInfo, EnableRaisingEvents = true
            };

            process.Start();

            if (process != null)
            {
                // Asynchronously read the standard output of the spawned process.
                // This raises OutputDataReceived events for each line of output.
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.Exited += (sender, args) =>
                {
                    _callback();
                };

                return(process.Id);
            }

            throw new Exception("Process in invalid state.");
        }
Beispiel #6
0
        /// <inheritdoc/>
        public int LaunchTestHost(TestProcessStartInfo testHostStartInfo)
        {
            var processId = this.testHostLauncher.LaunchTestHost(testHostStartInfo);

            this.testHostProcess = Process.GetProcessById(processId);
            return(processId);
        }
        private void InitializeStartInfo(Process process, TestProcessStartInfo startInfo, IPEndPoint endPoint)
        {
            process.StartInfo.FileName         = startInfo.FileName;
            process.StartInfo.WorkingDirectory = startInfo.WorkingDirectory;
            process.StartInfo.Arguments        = string.Format("{0} {1} {2} {3} {4}",
                                                               startInfo.Arguments,
                                                               endPoint.Address,
                                                               endPoint.Port,
                                                               this.GetTestSessionArgs(),
                                                               this.GetDebugArg());

            foreach (var entry in startInfo.EnvironmentVariables)
            {
#if NETSTANDARD14
                process.StartInfo.Environment.Add(entry);
#endif
#if NET451
                process.StartInfo.EnvironmentVariables.Add(entry.Key, entry.Value);
#endif
            }

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow  = true;

            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
        }
        private bool LaunchHost(TestProcessStartInfo testHostStartInfo, CancellationToken cancellationToken)
        {
            this.testHostProcessStdError = new StringBuilder(0, CoreUtilities.Constants.StandardErrorMaxLength);
            EqtTrace.Verbose("Launching default test Host Process {0} with arguments {1}", testHostStartInfo.FileName, testHostStartInfo.Arguments);

            // We launch the test host process here if we're on the normal test running workflow.
            // If we're debugging and we have access to the newest version of the testhost launcher
            // interface we launch it here as well, but we expect to attach later to the test host
            // process by using its PID.
            // For every other workflow (e.g.: profiling) we ask the IDE to launch the custom test
            // host for us. In the profiling case this is needed because then the IDE sets some
            // additional environmental variables for us to help with probing.
            if ((this.customTestHostLauncher == null) ||
                (this.customTestHostLauncher.IsDebug &&
                 this.customTestHostLauncher is ITestHostLauncher2))
            {
                EqtTrace.Verbose("DefaultTestHostManager: Starting process '{0}' with command line '{1}'", testHostStartInfo.FileName, testHostStartInfo.Arguments);
                cancellationToken.ThrowIfCancellationRequested();
                this.testHostProcess = this.processHelper.LaunchProcess(testHostStartInfo.FileName, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, testHostStartInfo.EnvironmentVariables, this.ErrorReceivedCallback, this.ExitCallBack, null) as Process;
            }
            else
            {
                int processId = this.customTestHostLauncher.LaunchTestHost(testHostStartInfo, cancellationToken);
                this.testHostProcess = Process.GetProcessById(processId);
                this.processHelper.SetExitCallback(processId, this.ExitCallBack);
            }

            this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched", 0, this.testHostProcess.Id));
            return(this.testHostProcess != null);
        }
Beispiel #9
0
        public async Task <bool> LaunchProcessAsync(TestProcessStartInfo runtimeProcessStartInfo, CancellationToken cancellationToken)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    EqtTrace.Verbose("RuntimeManager: Starting process '{0}' with command line '{1}'", runtimeProcessStartInfo.FileName, runtimeProcessStartInfo.Arguments);

                    cancellationToken.ThrowIfCancellationRequested();

                    var callbacks = new ProcessCallbacks
                    {
                        outputReceived = this.ProcessOutputReceived,
                        errorReceived = this.ProcessErrorReceived,
                        exitReceived = this.ProcessExitReceived
                    };

                    this.jsProcess.LaunchProcess(runtimeProcessStartInfo, callbacks);
                }
                catch (OperationCanceledException ex)
                {
                    EqtTrace.Error("RuntimeManager: Failed to launch node: {0}", ex);
                    Console.WriteLine(ex);
                    return false;
                }

                this.InitializeCommunication(cancellationToken);
                return this.jsProcess.IsAlive;
            }));
        }
Beispiel #10
0
        public async Task <bool> LaunchProcessAsync(TestProcessStartInfo runtimeProcessStartInfo, CancellationToken cancellationToken)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    this.processStdError = new StringBuilder(this.ErrorLength, this.ErrorLength);
                    EqtTrace.Verbose("DotnetTestHostManager: Starting process '{0}' with command line '{1}'", runtimeProcessStartInfo.FileName, runtimeProcessStartInfo.Arguments);

                    cancellationToken.ThrowIfCancellationRequested();

                    this.jsProcess.LaunchProcess(runtimeProcessStartInfo, this.ProcessErrorReceived, this.ProcessExitReceived);
                }
                catch (OperationCanceledException ex)
                {
                    EqtTrace.Error("DotnetTestHostManager.LaunchHost: Failed to launch testhost: {0}", ex);
                    //this.messageLogger.SendMessage(TestMessageLevel.Error, ex.ToString());
                    Console.Write(ex);
                    return false;
                }

                //this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched", 0, this.testHostProcess.Id));
                this.InitializeCommunication(cancellationToken);

                return this.jsProcess.IsAlive;
            }));
        }
        private int LaunchHost(TestProcessStartInfo testHostStartInfo)
        {
            try
            {
                this.testHostProcessStdError = new StringBuilder(this.ErrorLength, this.ErrorLength);
                EqtTrace.Verbose("Launching default test Host Process {0} with arguments {1}", testHostStartInfo.FileName, testHostStartInfo.Arguments);

                if (this.customTestHostLauncher == null)
                {
                    EqtTrace.Verbose("DefaultTestHostManager: Starting process '{0}' with command line '{1}'", testHostStartInfo.FileName, testHostStartInfo.Arguments);
                    this.testHostProcess = this.processHelper.LaunchProcess(testHostStartInfo.FileName, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, testHostStartInfo.EnvironmentVariables, this.ErrorReceivedCallback, this.ExitCallBack) as Process;
                }
                else
                {
                    int processId = this.customTestHostLauncher.LaunchTestHost(testHostStartInfo);
                    this.testHostProcess = Process.GetProcessById(processId);
                }
            }
            catch (OperationCanceledException ex)
            {
                this.OnHostExited(new HostProviderEventArgs(ex.Message, -1, 0));
                return(-1);
            }

            var pId = this.testHostProcess != null ? this.testHostProcess.Id : 0;

            this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched with Pid: " + pId));
            return(pId);
        }
Beispiel #12
0
        /// <summary>
        /// Send a custom host launch message to IDE
        /// </summary>
        /// <param name="testProcessStartInfo">
        /// The test Process Start Info.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo)
        {
            lock (ackLockObject)
            {
                var     waitHandle = new AutoResetEvent(false);
                Message ackMessage = null;
                this.onAckMessageReceived = (ackRawMessage) =>
                {
                    ackMessage = ackRawMessage;
                    waitHandle.Set();
                };

                this.communicationManager.SendMessage(MessageType.CustomTestHostLaunch, testProcessStartInfo);

                // LifeCycle of the TP through DesignModeClient is maintained by the IDEs or user-facing-clients like LUTs, who call TestPlatform
                // TP is handing over the control of launch to these IDEs and so, TP has to wait indefinite
                // Even if TP has a timeout here, there is no way TP can abort or stop the thread/task that is hung in IDE or LUT
                // Even if TP can abort the API somehow, TP is essentially putting IDEs or Clients in inconsistent state without having info on
                // Since the IDEs own user-UI-experience here, TP will let the custom host launch as much time as IDEs define it for their users
                waitHandle.WaitOne();
                this.onAckMessageReceived = null;

                var ackPayload = this.dataSerializer.DeserializePayload <CustomHostLaunchAckPayload>(ackMessage);

                if (ackPayload.HostProcessId > 0)
                {
                    return(ackPayload.HostProcessId);
                }
                else
                {
                    throw new TestPlatformException(ackPayload.ErrorMessage);
                }
            }
        }
Beispiel #13
0
        private bool LaunchHost(TestProcessStartInfo testHostStartInfo, CancellationToken cancellationToken)
        {
            try
            {
                this.testHostProcessStdError = new StringBuilder(this.ErrorLength, this.ErrorLength);
                if (this.testHostLauncher == null)
                {
                    EqtTrace.Verbose("DotnetTestHostManager: Starting process '{0}' with command line '{1}'", testHostStartInfo.FileName, testHostStartInfo.Arguments);

                    cancellationToken.ThrowIfCancellationRequested();
                    this.testHostProcess = this.processHelper.LaunchProcess(testHostStartInfo.FileName, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, testHostStartInfo.EnvironmentVariables, this.ErrorReceivedCallback, this.ExitCallBack) as Process;
                }
                else
                {
                    var processId = this.testHostLauncher.LaunchTestHost(testHostStartInfo);
                    this.testHostProcess = Process.GetProcessById(processId);
                    this.processHelper.SetExitCallback(processId, this.ExitCallBack);
                }
            }
            catch (OperationCanceledException ex)
            {
                EqtTrace.Error("DotnetTestHostManager.LaunchHost: Failed to launch testhost: {0}", ex);
                this.messageLogger.SendMessage(TestMessageLevel.Error, ex.ToString());
                return(false);
            }

            this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched", 0, this.testHostProcess.Id));

            return(this.testHostProcess != null);
        }
        private int LaunchHost(TestProcessStartInfo testHostStartInfo)
        {
            try
            {
                this.testHostProcessStdError = new StringBuilder(this.ErrorLength, this.ErrorLength);
                EqtTrace.Verbose("Launching default test Host Process {0} with arguments {1}", testHostStartInfo.FileName, testHostStartInfo.Arguments);

                if (this.customTestHostLauncher == null)
                {
                    this.testHostProcess = this.processHelper.LaunchProcess(testHostStartInfo.FileName, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, this.ErrorReceivedCallback);
                }
                else
                {
                    int processId = this.customTestHostLauncher.LaunchTestHost(testHostStartInfo);
                    this.testHostProcess = Process.GetProcessById(processId);
                }
            }
            catch (OperationCanceledException ex)
            {
                this.OnHostExited(new HostProviderEventArgs(ex.Message, -1));
                return(-1);
            }
            this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched with Pid: " + this.testHostProcess.Id));
            return(this.testHostProcess.Id);
        }
        public void LaunchProcessWithDebuggerAttachedShouldUpdateEnvironmentVariables()
        {
            // Setup
            var mockRunEventsHandler = new Mock <ITestRunEventsHandler>();
            TestProcessStartInfo launchedStartInfo = null;

            mockRunEventsHandler.Setup(runHandler => runHandler.LaunchProcessWithDebuggerAttached(It.IsAny <TestProcessStartInfo>())).Callback
                ((TestProcessStartInfo startInfo) => { launchedStartInfo = startInfo; });
            var proxyExecutionManager = new ProxyExecutionManagerWithDataCollection(this.mockRequestData.Object, this.mockRequestSender.Object, this.mockTestHostManager.Object, this.mockDataCollectionManager.Object);
            var mockTestRunCriteria   = new Mock <TestRunCriteria>(new List <string> {
                "source.dll"
            }, 10);
            var testProcessStartInfo = new TestProcessStartInfo
            {
                Arguments            = string.Empty,
                EnvironmentVariables = new Dictionary <string, string>
                {
                    { "variable1", "value1" },
                    { "variable2", "value2" }
                }
            };

            // Act.
            proxyExecutionManager.StartTestRun(mockTestRunCriteria.Object, mockRunEventsHandler.Object);
            proxyExecutionManager.LaunchProcessWithDebuggerAttached(testProcessStartInfo);

            // Verify.
            Assert.IsTrue(launchedStartInfo != null, "Failed to get the start info");
            foreach (var envVaribale in testProcessStartInfo.EnvironmentVariables)
            {
                Assert.AreEqual(envVaribale.Value, launchedStartInfo.EnvironmentVariables[envVaribale.Key], $"Expected environment variable {envVaribale.Key} : {envVaribale.Value} not found");
            }
        }
Beispiel #16
0
        public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo, CancellationToken cancellationToken)
        {
            var processInfo = new ProcessStartInfo(
                defaultTestHostStartInfo.FileName,
                defaultTestHostStartInfo.Arguments)
            {
                WorkingDirectory = defaultTestHostStartInfo.WorkingDirectory
            };

            processInfo.EnvironmentVariables["ActiveMutation"] = _activeMutation.ToString();

            var process = new Process {
                StartInfo = processInfo, EnableRaisingEvents = true
            };

            process.Start();

            if (process != null)
            {
                process.Exited += (sender, args) =>
                {
                    _callback();
                };

                return(process.Id);
            }

            throw new Exception("Process in invalid state.");
        }
Beispiel #17
0
        /// <summary>
        /// Launch the specified process with the debugger attached.
        /// </summary>
        /// <param name="filePath">File path to the exe to launch.</param>
        /// <param name="workingDirectory">Working directory that process should use.</param>
        /// <param name="arguments">Command line arguments the process should be launched with.</param>
        /// <param name="environmentVariables">Environment variables to be set in target process</param>
        /// <returns>Process ID of the started process.</returns>
        public int LaunchProcessWithDebuggerAttached(string filePath, string workingDirectory, string arguments, IDictionary <string, string> environmentVariables)
        {
            // If an adapter attempts to launch a process after the run is complete (=> this object is disposed)
            // throw an error.
            if (this.isDisposed)
            {
                throw new ObjectDisposedException("IFrameworkHandle");
            }

            // If it is not a debug run, then throw an error
            if (!this.testExecutionContext.IsDebug)
            {
                throw new InvalidOperationException(CrossPlatEngineResources.LaunchDebugProcessNotAllowedForANonDebugRun);
            }

            var processInfo = new TestProcessStartInfo()
            {
                Arguments            = arguments,
                EnvironmentVariables = environmentVariables,
                FileName             = filePath,
                WorkingDirectory     = workingDirectory
            };

            return(this.testRunEventsHandler.LaunchProcessWithDebuggerAttached(processInfo));
        }
        public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo, CancellationToken cancellationToken)
        {
            var processInfo = new ProcessStartInfo(defaultTestHostStartInfo.FileName, defaultTestHostStartInfo.Arguments)
            {
                WorkingDirectory       = defaultTestHostStartInfo.WorkingDirectory,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
            };

            foreach (var(key, value) in _envVars)
            {
                processInfo.EnvironmentVariables[key] = value;
            }
            _currentProcess = new Process {
                StartInfo = processInfo, EnableRaisingEvents = true
            };

            _currentProcess.Exited += CurrentProcess_Exited;

            _currentProcess.OutputDataReceived += Process_OutputDataReceived;
            _currentProcess.ErrorDataReceived  += Process_ErrorDataReceived;

            if (!_currentProcess.Start())
            {
                Logger.LogError($"Runner {_id}: Failed to start process {processInfo.Arguments}.");
            }

            _currentProcess.BeginOutputReadLine();
            _currentProcess.BeginErrorReadLine();

            return(_currentProcess.Id);
        }
Beispiel #19
0
        public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo, CancellationToken cancellationToken)
        {
            var processInfo = new ProcessStartInfo(
                defaultTestHostStartInfo.FileName,
                defaultTestHostStartInfo.Arguments)
            {
                WorkingDirectory = defaultTestHostStartInfo.WorkingDirectory
            };
            var process = new Process {
                StartInfo = processInfo, EnableRaisingEvents = true
            };

            process.Start();

            if (process != null)
            {
                process.Exited += (sender, args) =>
                {
                    Console.WriteLine("Test host has exited. Signal run end.");
                    this.callback();
                };

                return(process.Id);
            }

            throw new Exception("Process in invalid state.");
        }
Beispiel #20
0
        public DefaultTestHostManagerTests()
        {
            this.mockProcessHelper = new Mock <IProcessHelper>();
            this.mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("vstest.console.exe");

            this.testHostManager = new DefaultTestHostManager(Architecture.X64, Framework.DefaultFramework, this.mockProcessHelper.Object, true);
            this.startInfo       = this.testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty <string>(), null, default(TestRunnerConnectionInfo));
        }
Beispiel #21
0
        /// <summary>
        /// This method is exposed to enable drived classes to modify TestProcessStartInfo. E.g. DataCollection need additional environment variables to be passed, etc.
        /// </summary>
        /// <param name="testProcessStartInfo">
        /// The sources.
        /// </param>
        /// <returns>
        /// The <see cref="TestProcessStartInfo"/>.
        /// </returns>
        protected virtual TestProcessStartInfo UpdateTestProcessStartInfo(TestProcessStartInfo testProcessStartInfo)
        {
            // Update Telemetry Opt in status because by default in Test Host Telemetry is opted out
            var telemetryOptedIn = this.requestData.IsTelemetryOptedIn ? "true" : "false";

            testProcessStartInfo.Arguments += " --telemetryoptedin " + telemetryOptedIn;
            return(testProcessStartInfo);
        }
Beispiel #22
0
        public void LaunchProcessWithDebuggerAttachedShouldJustPassOnTheEventToRunEventsHandler()
        {
            var testProcessStartInfo = new TestProcessStartInfo();

            this.parallelRunEventsHandler.LaunchProcessWithDebuggerAttached(testProcessStartInfo);

            this.mockTestRunEventsHandler.Verify(mt => mt.LaunchProcessWithDebuggerAttached(testProcessStartInfo), Times.Once);
        }
Beispiel #23
0
        int StartCustomTestHost(TestProcessStartInfo startInfo, TestContext currentTestContext)
        {
            OperationConsole console = currentTestContext.ExecutionContext.ConsoleFactory.CreateConsole(
                OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle(GettextCatalog.GetString("Unit Tests")));
            ExecutionCommand command;

            if (runJobInProgress.Project is DotNetProject dnp)
            {
                if (dnp.HasFlavor <DotNetCoreProjectExtension> () && dnp.TargetFramework.IsNetCoreApp())
                {
                    command = new DotNetCoreExecutionCommand(
                        startInfo.WorkingDirectory,
                        startInfo.FileName,
                        startInfo.Arguments
                        )
                    {
                        EnvironmentVariables = startInfo.EnvironmentVariables
                    };
                    ((DotNetCoreExecutionCommand)command).Command   = startInfo.FileName;
                    ((DotNetCoreExecutionCommand)command).Arguments = startInfo.Arguments;
                }
                else
                {
                    var portArgument = startInfo.Arguments.IndexOf(" --port", StringComparison.Ordinal);
                    var assembly     = startInfo.Arguments.Remove(portArgument - 1).Trim(new char[] { '"' });
                    var arguments    = startInfo.Arguments.Substring(portArgument + 1);
                    command = new DotNetExecutionCommand(
                        assembly,
                        arguments,
                        startInfo.WorkingDirectory,
                        startInfo.EnvironmentVariables
                        );
                }
            }
            else
            {
                command = new NativeExecutionCommand(
                    startInfo.WorkingDirectory,
                    startInfo.FileName,
                    startInfo.Arguments,
                    startInfo.EnvironmentVariables);
            }

            runJobInProgress.ProcessOperation = currentTestContext.ExecutionContext.ExecutionHandler.Execute(command, console);
            var eventProcessSet = new ManualResetEvent(false);

            runJobInProgress.ProcessOperation.ProcessIdSet += delegate {
                eventProcessSet.Set();
            };
            if (runJobInProgress.ProcessOperation.ProcessId == 0)
            {
                if (!eventProcessSet.WaitOne(5000) && runJobInProgress.ProcessOperation.ProcessId == 0)
                {
                    throw new Exception("Timeout, process id not set.");
                }
            }
            return(runJobInProgress.ProcessOperation.ProcessId);
        }
Beispiel #24
0
 /// <inheritdoc/>
 public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo)
 {
     return(this.processHelper.LaunchProcess(
                defaultTestHostStartInfo.FileName,
                defaultTestHostStartInfo.Arguments,
                defaultTestHostStartInfo.WorkingDirectory,
                defaultTestHostStartInfo.EnvironmentVariables,
                defaultTestHostStartInfo.ErrorReceivedCallback).Id);
 }
Beispiel #25
0
        public void DesignModeClientLaunchCustomHostMustThrowIfCancellationOccursBeforeHostLaunch()
        {
            var testableDesignModeClient = new TestableDesignModeClient(this.mockCommunicationManager.Object, JsonDataSerializer.Instance, this.mockPlatformEnvrironment.Object);

            var info = new TestProcessStartInfo();
            var cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Cancel();

            testableDesignModeClient.LaunchCustomHost(info, cancellationTokenSource.Token);
        }
        public DefaultTestHostManagerTests()
        {
            this.mockProcessHelper = new Mock <IProcessHelper>();
            this.mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("vstest.console.exe");

            this.mockMessageLogger = new Mock <IMessageLogger>();

            this.testHostManager = new DefaultTestHostManager(this.mockProcessHelper.Object);
            this.testHostManager.Initialize(this.mockMessageLogger.Object, $"<?xml version=\"1.0\" encoding=\"utf-8\"?><RunSettings> <RunConfiguration> <TargetPlatform>{Architecture.X64}</TargetPlatform> <TargetFrameworkVersion>{Framework.DefaultFramework}</TargetFrameworkVersion> <DisableAppDomain>{false}</DisableAppDomain> </RunConfiguration> </RunSettings>");
            this.startInfo = this.testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty <string>(), null, default(TestRunnerConnectionInfo));
        }
Beispiel #27
0
        /// <inheritdoc/>
        private int LaunchHost(TestProcessStartInfo testHostStartInfo)
        {
            this.testHostProcessStdError            = new StringBuilder(this.ErrorLength, this.ErrorLength);
            testHostStartInfo.ErrorReceivedCallback = this.ErrorReceivedCallback;
            var processId = this.testHostLauncher.LaunchTestHost(testHostStartInfo);

            this.testHostProcess = Process.GetProcessById(processId);

            this.OnHostLaunched(new HostProviderEventArgs("Test Runtime launched with Pid: " + processId));

            return(processId);
        }
Beispiel #28
0
        /// <summary>
        /// Launch process with debugger attached
        /// </summary>
        /// <param name="testProcessStartInfo"></param>
        /// <returns>processid</returns>
        public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testProcessStartInfo)
        {
            int processId = -1;

            // Only launch while the test run is in progress and the launcher is a debug one
            if (this.State == TestRunState.InProgress && this.testRunCriteria.TestHostLauncher.IsDebug)
            {
                processId = this.testRunCriteria.TestHostLauncher.LaunchTestHost(testProcessStartInfo);
            }

            return(processId);
        }
        public void StartTestRunShouldNotifyLaunchWithDebuggerOnMessageReceived()
        {
            var launchMessagePayload = new TestProcessStartInfo();

            this.SetupDeserializeMessage(MessageType.LaunchAdapterProcessWithDebuggerAttached, launchMessagePayload);
            this.SetupFakeCommunicationChannel();

            this.testRequestSender.StartTestRun(this.testRunCriteriaWithSources, this.mockExecutionEventsHandler.Object);

            this.RaiseMessageReceivedEvent();
            this.mockExecutionEventsHandler.Verify(eh => eh.LaunchProcessWithDebuggerAttached(launchMessagePayload), Times.Once);
        }
        public void StartTestRunShouldSendLaunchDebuggerAttachedCallbackOnMessageReceivedWithVersion()
        {
            var launchMessagePayload = new TestProcessStartInfo();

            this.SetupFakeChannelWithVersionNegotiation(DUMMYNEGOTIATEDPROTOCOLVERSION);
            this.SetupDeserializeMessage(MessageType.LaunchAdapterProcessWithDebuggerAttached, launchMessagePayload);

            this.testRequestSender.StartTestRun(this.testRunCriteriaWithSources, this.mockExecutionEventsHandler.Object);

            this.RaiseMessageReceivedEvent();
            this.mockDataSerializer.Verify(ds => ds.SerializePayload(MessageType.LaunchAdapterProcessWithDebuggerAttachedCallback, It.IsAny <int>(), DUMMYNEGOTIATEDPROTOCOLVERSION), Times.Once);
        }