public void ExecutePassesOnOutput() { var fileSystemMock = InitialiseFileSystemMockForExecute(); var info = new ProcessInfo("sleeper", "1"); var output = new List <ProcessOutputEventArgs>(); var executor = new ProcessExecutor { FileSystem = fileSystemMock.Object }; executor.ProcessOutput += (o, e) => output.Add(e); var projectName = "aProject"; var waitHandle = new ManualResetEvent(false); ProcessResult result = null; var thread = new Thread( () => { try { result = executor.Execute(info, projectName, "aTask", "C:\\somewhere.txt"); } finally { waitHandle.Set(); } }); thread.Start(); waitHandle.WaitOne(TimeSpan.FromSeconds(30)); CollectionAssert.IsNotEmpty(output); Assert.IsTrue(result.Succeeded); }
public void ExecuteChangesPriority() { var fileSystemMock = InitialiseFileSystemMockForExecute(); var info = new ProcessInfo("sleeper", "1", null, ProcessPriorityClass.BelowNormal); var executor = new ProcessExecutor { FileSystem = fileSystemMock.Object }; var projectName = "aProject"; var waitHandle = new ManualResetEvent(false); ProcessResult result = null; var thread = new Thread( () => { try { result = executor.Execute(info, projectName, "aTask", "C:\\somewhere.txt"); } finally { waitHandle.Set(); } }); thread.Start(); waitHandle.WaitOne(TimeSpan.FromSeconds(30)); Assert.IsTrue(result.Succeeded); }
/// <summary> /// Gets the specified files from the server, potentially overwriting it, even if it's checked out. /// </summary> /// <param name="overwrite">if set to <c>true</c> [overwrite].</param> /// <param name="fileNames">The file names.</param> /// <exception cref="System.Exception">Unable to determin if file is different than contents for the file + sourcePath + Environment.NewLine + ex</exception> public string Get(bool overwrite, params string[] fileNames) { if (fileNames == null || fileNames.Length == 0) { return("No Files Given"); } var fileNameBatches = fileNames.BatchLessThanMaxLength(MaxCommandLength, "Filename \"{0}\" is longer than the max length {1}.", 3 // 1 for each quote, and one more for the space between. ); var output = new StringBuilder(); foreach (var batch in fileNameBatches) { try { var files = string.Join(" ", batch.Select(WrapPathInQuotes)); var info = CreateProcessExecutorInfo("get", null, files + (overwrite ? " /overwrite": ""), Directory.GetParent(fileNames.First()).FullName); output.AppendLine(ProcessExecutor.ExecuteCmd(info)); } catch (Exception ex) { throw new Exception("Unable to get files " + string.Join(", ", batch) + Environment.NewLine + ex); } } return(output.ToString()); }
public void ExecuteTimesOut() { var fileSystemMock = InitialiseFileSystemMockForExecute(); var info = new ProcessInfo("sleeper") { TimeOut = TimeSpan.FromSeconds(1) }; var executor = new ProcessExecutor { FileSystem = fileSystemMock.Object }; var projectName = "aProject"; var waitHandle = new ManualResetEvent(false); ProcessResult result = null; var thread = new Thread( () => { try { result = executor.Execute(info, projectName, "aTask", "C:\\somewhere.txt"); } finally { waitHandle.Set(); } }); thread.Start(); waitHandle.WaitOne(TimeSpan.FromSeconds(30)); Assert.IsTrue(result.TimedOut); }
private void AssertDurationsFileIsCreated(bool parallelExecution) { string sampleTestsDurationsFile = TestResources.SampleTests + GoogleTestConstants.DurationsExtension; RemoveFileIfNecessary(sampleTestsDurationsFile); string crashingTestsDurationsFile = TestResources.HardCrashingSampleTests + GoogleTestConstants.DurationsExtension; RemoveFileIfNecessary(crashingTestsDurationsFile); MockOptions.Setup(o => o.ParallelTestExecution).Returns(parallelExecution); MockOptions.Setup(o => o.MaxNrOfThreads).Returns(2); var processExecutor = new ProcessExecutor(null, TestEnvironment.Logger); var collectingReporter = new FakeFrameworkReporter(); var testExecutor = new GoogleTestExecutor(TestEnvironment.Logger, TestEnvironment.Options); testExecutor.RunTests(TestDataCreator.AllTestCasesExceptLoadTests, TestDataCreator.AllTestCasesExceptLoadTests, collectingReporter, null, false, TestResources.SampleTestsSolutionDir, processExecutor); sampleTestsDurationsFile.AsFileInfo() .Should() .Exist("Test execution should result in test durations"); var durations = new TestDurationSerializer().ReadTestDurations(TestDataCreator.AllTestCasesOfSampleTests); durations.Keys.Should().Contain( TestDataCreator.AllTestCasesOfSampleTests.Where(tc => collectingReporter.ReportedTestResults.Any(tr => tc.Equals(tr.TestCase) && (tr.Outcome == TestOutcome.Passed || tr.Outcome == TestOutcome.Failed)))); crashingTestsDurationsFile.AsFileInfo() .Should() .Exist("Test execution should result in test durations file"); durations = new TestDurationSerializer().ReadTestDurations(TestDataCreator.AllTestCasesOfHardCrashingTests); durations.Keys.Should().Contain(TestDataCreator.AllTestCasesOfHardCrashingTests.Where(tc => collectingReporter.ReportedTestResults.Any(tr => tc.Equals(tr.TestCase) && (tr.Outcome == TestOutcome.Passed || tr.Outcome == TestOutcome.Failed)))); }
private void DoRunTests(ICollection <TestCase> testCasesToRun, IRunContext runContext, IFrameworkHandle frameworkHandle) { if (testCasesToRun.Count == 0) { return; } bool isRunningInsideVisualStudio = !string.IsNullOrEmpty(runContext.SolutionDirectory); var reporter = new VsTestFrameworkReporter(frameworkHandle, isRunningInsideVisualStudio, _logger); var launcher = new DebuggedProcessLauncher(frameworkHandle); ProcessExecutor processExecutor = null; if (_settings.UseNewTestExecutionFramework) { IDebuggerAttacher debuggerAttacher = null; if (runContext.IsBeingDebugged) { debuggerAttacher = new MessageBasedDebuggerAttacher(_settings.DebuggingNamedPipeId, _logger); } processExecutor = new ProcessExecutor(debuggerAttacher, _logger); } lock (_lock) { if (_canceled) { return; } _executor = new GoogleTestExecutor(_logger, _settings); } _executor.RunTests(testCasesToRun, reporter, launcher, runContext.IsBeingDebugged, runContext.SolutionDirectory, processExecutor); reporter.AllTestsFinished(); }
private void RunBatch(BatchType batchType, string workingDirectory, string batch, bool isBeingDebugged) { string batchTypeString = (batchType == BatchType.TestSetup) ? Resources.TestSetupBatchFile : Resources.TestTeardownBatchFile; int batchExitCode; if (_settings.UseNewTestExecutionFramework) { var executor = new ProcessExecutor(null, _logger); batchExitCode = executor.ExecuteBatchFileBlocking(batch, "", workingDirectory, "", s => { }); } else { new TestProcessLauncher(_logger, _settings, isBeingDebugged).GetOutputOfCommand( workingDirectory, null, batch, "", false, false, null, out batchExitCode); } if (batchExitCode == 0) { _logger.DebugInfo(String.Format(Resources.SuccessfullyRun, _threadName, batchTypeString, batch)); } else { _logger.LogWarning(String.Format(Resources.BatchReturnedExitCode, _threadName, batchTypeString, batchExitCode, batch)); } }
/// <summary> /// Initializes a new instance of the <see cref="UpdateConfigurationTask"/> class. /// </summary> /// <param name="executor">The executor to use.</param> public UpdateConfigurationTask(ProcessExecutor executor) { this.executor = executor; this.TimeOut = 600; this.Priority = ProcessPriorityClass.Normal; this.ValidateFile = true; }
/// <summary> /// Checks the file out. /// </summary> /// <param name="filePath">The file path.</param> /// <exception cref="System.Exception"> /// Unable to check out file /// or /// File is read only, please checkout the file before running /// </exception> public void Checkout(string filePath) { if (!File.GetAttributes(filePath).HasFlag(FileAttributes.ReadOnly)) { return; } string output; try { var info = new ProcessExecutorInfo($"\"{TfPath}\"", $"checkout {WrapPathInQuotes(filePath)}") { WorkingDirectory = Directory.GetParent(filePath).FullName }; output = ProcessExecutor.ExecuteCmd(info); } catch (Exception ex) { throw new Exception("Unable to check out file " + filePath + Environment.NewLine + ex); } if (File.GetAttributes(filePath).HasFlag(FileAttributes.ReadOnly)) { throw new Exception("File \"" + filePath + "\" is read only even though it should have been checked out, please checkout the file before running. Output: " + output); } }
public void StartNonTerminatingProcessAndInterruptCurrentProcessShouldKillProcessButLeaveThreadRunning() { // ARRANGE Thread thread = new Thread(StartSleeperProcess); thread.Name = "sleeper thread"; thread.Start(); WaitForProcessToStart(); // ACT ProcessExecutor.KillProcessCurrentlyRunningForProject("sleeper thread"); // ASSERT // Sleeper runs for 60 seconds. We need to give up early and fail the test if it takes longer than 50. // If it runs for the full 60 seconds it will look the same as being interrupted, and the test will pass // incorrectly. Assert.IsTrue(thread.Join(TimeSpan.FromSeconds(50)), "Thread did not exit in reasonable time."); Assert.IsTrue(runnerThreadCompletedNormally, "Runner thread should have exited through normally."); // Ensure the external process was killed try { Assert.AreEqual(0, Process.GetProcessesByName("sleeper").Length); } catch (Exception) { Process.GetProcessesByName("sleeper")[0].Kill(); Assert.Fail("Process was not killed."); } }
public void Kill(string project) { //IProjectIntegrator integrator = GetIntegrator(project); //integrator.Abort(); Log.Warning("Kill all child processes."); foreach (ProcessInformation processInfo in ProcessExecutor.RetrieveProcessInformation(project)) { try { Log.Warning(string.Format("Trying to kill process: {0} {1}", processInfo.ProcessName, processInfo.Id)); Project p = GetProjectInstance(project); KillUtil.KillPid(processInfo.Id, p.KillExceptions); Log.Warning(string.Format("The process has been killed: {0} {1}", processInfo.ProcessName, processInfo.Id)); } catch (Exception ex) { Log.Error(string.Format("Error trying to kill process: {0} {1}", processInfo.ProcessName, processInfo.Id)); Log.Error(ex.ToString()); } } ProcessExecutor.ManagedProcesses[project] = new List <Process>(); ProcessExecutor.ManagedProcessInformationListCache[project] = new ThoughtWorks.CruiseControl.Core.Util.ProcessExecutor.CacheItem(DateTime.Now, new ProcessInformationList()); //integrator.WaitForExit(); //integrator.Start(); }
private void userControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (SystemContext.Instance.TileMode == Enums.TileMode.Normal) { ProcessExecutor.Execute(this.AppMeta); } }
/// <summary> /// Generate compatibility files under unix. /// </summary> /// <returns>Returns the compatible content.</returns> protected virtual string GenerateUnixProxyCode(string binPath, string link) { binPath = BaseFileSystem.GetRelativePath(link, binPath); var binDirPath = ProcessExecutor.Escape(Path.GetDirectoryName(binPath)); var binFile = Path.GetFileName(binPath); var proxyCode = @"#!/usr/bin/env sh dir=$(cd ""${0%[/\\]*}"" > /dev/null; cd %binDirPath% && pwd) if [ -d /proc/cygdrive ]; then case $(which dotnet) in $(readlink -n /proc/cygdrive)/*) dir=$(cygpath -m ""$dir""); ;; esac fi ""${dir}/%binFile%"" ""$@"" "; proxyCode = proxyCode.Replace("%binDirPath%", binDirPath); proxyCode = proxyCode.Replace("%binFile%", binFile); proxyCode = proxyCode.Replace("\r\n", "\n"); return proxyCode; }
private IList <TestCase> NewCreateTestcases(Action <TestCase> reportTestCase, List <string> standardOutput) { var testCases = new List <TestCase>(); var resolver = new NewTestCaseResolver( _executable, _settings.GetPathExtension(_executable), _diaResolverFactory, _settings.ParseSymbolInformation, _logger); var parser = new StreamingListTestsParser(_settings.TestNameSeparator); parser.TestCaseDescriptorCreated += (sender, args) => { TestCase testCase; if (_settings.ParseSymbolInformation) { TestCaseLocation testCaseLocation = resolver.FindTestCaseLocation( _signatureCreator.GetTestMethodSignatures(args.TestCaseDescriptor).ToList()); testCase = CreateTestCase(args.TestCaseDescriptor, testCaseLocation.Yield().ToList()); } else { testCase = CreateTestCase(args.TestCaseDescriptor); } reportTestCase?.Invoke(testCase); testCases.Add(testCase); }; Action <string> lineAction = s => { standardOutput.Add(s); parser.ReportLine(s); }; try { var executor = new ProcessExecutor(null, _logger); int processExitCode = executor.ExecuteCommandBlocking( _executable, GoogleTestConstants.ListTestsOption.Trim(), "", _settings.GetPathExtension(_executable), lineAction); if (!CheckProcessExitCode(processExitCode, standardOutput)) { return(new List <TestCase>()); } } catch (Exception e) { SequentialTestRunner.LogExecutionError(_logger, _executable, Path.GetFullPath(""), GoogleTestConstants.ListTestsOption.Trim(), e); return(new List <TestCase>()); } return(testCases); }
public void ExecuteWritesToStdIn() { var fileSystemMock = InitialiseFileSystemMockForExecute(); var info = new ProcessInfo("sleeper", "1") { StandardInputContent = "SomeData" }; var executor = new ProcessExecutor { FileSystem = fileSystemMock.Object }; var projectName = "aProject"; var waitHandle = new ManualResetEvent(false); ProcessResult result = null; var thread = new Thread( () => { try { result = executor.Execute(info, projectName, "aTask", "C:\\somewhere.txt"); } finally { waitHandle.Set(); } }); thread.Start(); waitHandle.WaitOne(TimeSpan.FromSeconds(30)); Assert.IsTrue(result.Succeeded); }
/// <summary> /// Fetch the specified reference or synchronize the git repository. /// </summary> /// <param name="uri">The specified git repository. can use ssh.</param> /// <param name="reference">The specified git reference.</param> /// <param name="path">The specified saved path. this path will be based on the file system.</param> /// <returns>True if fetched. false is sync mirror.</returns> public bool FetchReferenceOrSyncMirror(string uri, string reference, string path = null) { var parsedPath = string.IsNullOrEmpty(path) ? GetRepositoryNameFromUri(uri) : path; if (fileSystem is IReportPath report) { parsedPath = report.ApplyRootPath(parsedPath); } if (string.IsNullOrEmpty(parsedPath)) { throw new FileSystemException("Clone path is invalid, cannot be empty."); } if (fileSystem.Exists(parsedPath, FileSystemOptions.Directory) && process.Execute("git rev-parse --git-dir", out string output, parsedPath) == 0 && output.Trim() == ".") { var escapedReference = ProcessExecutor.Escape($"{reference}^{{commit}}"); if (process.Execute($"git rev-parse --quiet --verify {escapedReference}", parsedPath) == 0) { return(true); } } SyncMirror(uri, path); return(false); }
/// <summary> /// Whether the driver support the specified uri. /// </summary> /// <param name="io">The input/output instance.</param> /// <param name="config">The config instance.</param> /// <param name="uri">Thr specified uri.</param> /// <param name="deep">Whether is deep checker.</param> /// <returns>True if the driver is supported.</returns> public static bool IsSupport(IIO io, Config config, string uri, bool deep = false) { if (Regex.IsMatch(uri, @"(^git://|\.git/?$|git(?:olite)?@|//git\.|//github\.com/|//gitlib\.com/)", RegexOptions.IgnoreCase)) { return(true); } bool ProcessCheck(string command, string cwd) { var process = new BucketProcessExecutor(io); return(process.Execute(command, cwd) == 0); } if (FileSystemLocal.IsLocalPath(uri)) { uri = FileSystemLocal.GetPlatformPath(uri); if (!Directory.Exists(uri)) { return(false); } return(ProcessCheck("git tag", uri)); } if (!deep) { return(false); } return(ProcessCheck($"git ls-remote --heads {ProcessExecutor.Escape(uri)}", null)); }
/// <summary> /// Initializes a new instance of the <see cref="Mks" /> class. /// </summary> /// <param name="parser">The parser.</param> /// <param name="executor">The executor.</param> /// <remarks></remarks> public Mks(IHistoryParser parser, ProcessExecutor executor) : base(parser, executor) { this.Executable = DefaultExecutable; this.AutoGetSource = DefaultAutoGetSource; this.AutoDisconnect = DefaultAutoDisconnect; this.Port = DefaultPort; }
private static Mks CreateMks(string xml, IHistoryParser historyParser, ProcessExecutor executor) { Mks newMks = new Mks(historyParser, executor); NetReflector.Read(xml, newMks); return(newMks); }
public P4(ProcessExecutor processExecutor, IP4Initializer initializer, IP4Purger p4Purger, IP4ProcessInfoCreator processInfoCreator) { this.processExecutor = processExecutor; this.p4Initializer = initializer; this.processInfoCreator = processInfoCreator; this.p4Purger = p4Purger; }
private void RunBatch(string batchType, string workingDirectory, string batch, bool isBeingDebugged) { int batchExitCode; if (_settings.UseNewTestExecutionFramework) { var executor = new ProcessExecutor(null, _logger); batchExitCode = executor.ExecuteBatchFileBlocking(batch, "", workingDirectory, "", s => { }); } else { new TestProcessLauncher(_logger, _settings, isBeingDebugged).GetOutputOfCommand( workingDirectory, batch, "", false, false, null, out batchExitCode); } if (batchExitCode == 0) { _logger.DebugInfo( $"{_threadName}Successfully ran {batchType} batch \'{batch}\'"); } else { _logger.LogWarning( $"{_threadName}{batchType} batch returned exit code {batchExitCode}, executed command: \'{batch}\'"); } }
public P4() { processExecutor = new ProcessExecutor(); processInfoCreator = new P4ConfigProcessInfoCreator(); p4Initializer = new ProcessP4Initializer(processExecutor, processInfoCreator); p4Purger = new ProcessP4Purger(processExecutor, processInfoCreator); }
public async Task EnvironmentVariablesTest() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } using var executor = new ProcessExecutor(new ProcessStartInfo("powershell", "-Command \"Write-Host $env:TestUser\"") { Environment = { { "TestUser", "Alice" } } }); var list = new List <string>(); executor.OnOutputDataReceived += (sender, str) => { if (str != null) { list.Add(str); } }; var exitCode = -1; executor.OnExited += (sender, code) => { exitCode = code; }; await executor.ExecuteAsync(); Assert.NotEmpty(list); Assert.Contains(list, x => "Alice".Equals(x)); Assert.Equal(0, exitCode); }
public async Task HostNameTest() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } using var executor = new ProcessExecutor("hostName"); var list = new List <string>(); executor.OnOutputDataReceived += (sender, str) => { list.Add(str); }; var exitCode = -1; executor.OnExited += (sender, code) => { exitCode = code; }; await executor.ExecuteAsync(); Assert.NotEmpty(list); var hostName = Dns.GetHostName(); Assert.Contains(list, x => hostName.Equals(x)); Assert.Equal(0, exitCode); }
public async Task DotnetInfoAsyncTest() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } using var executor = new ProcessExecutor("dotnet", "--info"); var list = new List <string>(); executor.OnOutputDataReceived += (sender, str) => { list.Add(str); }; var exitCode = -1; executor.OnExited += (sender, code) => { exitCode = code; }; await executor.ExecuteAsync(); Assert.NotEmpty(list); Assert.Equal(0, exitCode); }
public static DockerUri Uri(this string machine) { var resp = new ProcessExecutor <SingleStringResponseParser, string>( "docker-machine".ResolveBinary(), $"url {machine}").Execute(); return(resp.Data.StartsWith("Host is not running") ? null : new DockerUri(resp.Data)); }
/// <summary> /// Initializes a new instance of the <see cref="FinalBuilderTask" /> class. /// </summary> /// <param name="registry">The registry.</param> /// <param name="executor">The executor.</param> /// <remarks></remarks> public FinalBuilderTask(IRegistry registry, ProcessExecutor executor) { _executor = executor; _registry = registry; _fbversion = FinalBuilderVersion.FBUnknown; _fbcmdpath = String.Empty; this.ProjectFile = string.Empty; }
/// <summary> /// Create an instance of the source control integration. /// </summary> public ExternalSourceControl(IHistoryParser parser, ProcessExecutor executor) : base(parser, executor) { this.ArgString = string.Empty; this.AutoGetSource = false; this.EnvironmentVariables = new EnvironmentVariable[0]; this.LabelOnSuccess = false; }
/// <summary> /// Initializes a new instance of the <see cref="DupFinderTask"/> class. /// </summary> /// <param name="executor">The executor to use.</param> public DupFinderTask(ProcessExecutor executor) { this.executor = executor; this.TimeOut = 600; this.Threshold = 5; this.Width = 2; this.Priority = ProcessPriorityClass.Normal; }
public void PopulateKillProcessThrowsExceptionForUnknownPlatform() { var killProcess = new Process(); var operatingSystem = new OperatingSystem(PlatformID.Xbox, new Version(5, 0)); Assert.Throws <CruiseControlException>( () => ProcessExecutor.PopulateKillProcess(killProcess, 1, operatingSystem)); }