public void ProcRunner_FailsOnTimeout() { // Arrange string exeName = TestUtils.WriteBatchFileForTest(TestContext, @"TIMEOUT 2 @echo Hello world "); TestLogger logger = new TestLogger(); ProcessRunnerArguments args = new ProcessRunnerArguments(exeName, logger) { TimeoutInMilliseconds = 100 }; ProcessRunner runner = new ProcessRunner(); // Act bool success = runner.Execute(args); // Assert Assert.IsFalse(success, "Expecting the process to have failed"); Assert.AreEqual(ProcessRunner.ErrorCode, runner.ExitCode, "Unexpected exit code"); logger.AssertMessageNotLogged("Hello world"); // Give the spawned process a chance to terminate. // This isn't essential (and having a Sleep in the test isn't ideal), but it stops // the test framework outputting this warning which appears in the TeamBuild summary: // "System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen // if the test(s) started a thread but did not stop it. Make sure that all the threads started by // the test(s) are stopped before completion." System.Threading.Thread.Sleep(1100); }
public void StartShouldRunProcessInBackground() { var runner = new ProcessRunner(); var process = runner.Start("ping 127.0.0.1 -n 20"); Assert.That(process.HasExited, Is.False); process.KillTree(); }
public KarmaSystemDependency(ProcessRunner processRunner, NodeModulesHelper nodeModulesHelper) { Name = "Karma"; MinVersion = new Version(0, 10, 8); _processRunner = processRunner; _nodeModulesHelper = nodeModulesHelper; }
public void VerifyOutputReceived() { var processRunner = new ProcessRunner(); string output = null; processRunner.RunProcess("ping", "localhost", s => output += s, s => output += s).Wait(); ObjectApprover.VerifyWithJson(output.ReplaceCaseless(Environment.MachineName, "")); }
public void GenerateFromDbml() { //1. gather prerequisites (compiler, sqlmetal etc) string cscExe = GetCompilerPath(); string sqlMetal = GetSqlMetalPath(); //2. run SqlMetal to generate 'bin/Northwind_temp.cs' string currDir = Directory.GetCurrentDirectory(); string mysqlExampleDir = "../../../Example/DbLinq.Mysql.Example/nwind"; bool ok = Directory.Exists(mysqlExampleDir); string args1 = string.Format(" -provider=MySql -namespace:nwind -code:Northwind_temp.cs -sprocs {0}/Northwind_from_mysql.dbml" , mysqlExampleDir); ProcessRunner p1 = new ProcessRunner(); int sqlMetalExitCode = p1.Run(sqlMetal, args1, 5000); Assert.IsTrue(sqlMetalExitCode == 0, "Got SqlMetal.exe error exit code " + sqlMetalExitCode); //3. make sure generated code compiles with 'bin/Northwind_temp.cs' Directory.SetCurrentDirectory(".."); string dependencies = @"/r:bin\nunit.framework.dll /r:bin\DbLinq.dll /r:bin\DbLinq.mysql.dll /r:bin\Mysql.data.dll"; string cscArgs = @"/nologo /target:library /d:MYSQL /out:bin/SqlMetal_test.dll bin/Northwind_temp.cs ReadTest.cs WriteTest.cs TestBase.cs " + dependencies; ProcessRunner p2 = new ProcessRunner(); int cscExitCode = p2.Run(cscExe, cscArgs, 5000); Logger.Write(Level.Information, "csc exitCode:" + cscExitCode + ", output: " + p2._stdout); Assert.IsTrue(cscExitCode == 0, "csc.exe failed with exit code " + cscExitCode); Directory.SetCurrentDirectory(currDir); }
public void ShouldAllowAsynchronousReadingOfStandardOutput() { var output = ""; var process = new ProcessRunner().Start("cmd /c echo test"); process.OutputUpdated += (sender, e) => output = process.StandardOutput; process.WaitForExit(TimeSpan.FromSeconds(30)); Assert.That(output, Is.EqualTo("test")); }
public void ShouldRunGivenProcessAndSaveStandardError() { // I had trouble finding a simple Windows exe (in system32) that // behaves correctly with regards to stderr var process = new ProcessRunner().Exec("svn", TimeSpan.MaxValue); Assert.That(!process.WasSuccessful); Assert.That(process.StandardError, Is.EqualTo("Type 'svn help' for usage.")); }
public void ShouldAllowAsynchronousReadingOfStandardError() { var error = ""; var process = new ProcessRunner().Start("svn"); process.ErrorUpdated += (sender, e) => error = process.StandardError; process.WaitForExit(TimeSpan.FromSeconds(30)); Assert.That(error, Is.EqualTo("Type 'svn help' for usage.")); }
public void ExecShouldKillEntireProcessTreeAfterTimeout() { SystemAssert.AssertProcessKilled("ping", () => { var runner = new ProcessRunner(); runner.Exec("cmd /c cmd /c ping 127.0.0.1 -n 20", TimeSpan.FromMilliseconds(100)); }); }
private void RunCommand(string command, string workingDirectory, Action<SystemProcess> onFailure) { log.Info("svn {0}", command); var processRunner = new ProcessRunner(workingDirectory); var process = processRunner.Exec("svn " + command, commandTimeout); if (!process.WasSuccessful) onFailure(process); }
public static string MSBuild(string projectFileAndArgs, TimeSpan timeout) { var commandLine = string.Format(@"C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe {0}", projectFileAndArgs); var process = new ProcessRunner().Exec(commandLine, timeout); ThrowIfFailed(process); return process.StandardOutput; }
public static void RmDir(string directoryName) { // I can't figure out why we can't delete the directory using Directory.Delete, but we can in the shell. // Neither Process Explorer nor Unlocker find any locks on the directory. // It only happens with svn files. var commandLine = string.Format("cmd /c rmdir /S /Q \"{0}\"", directoryName); var process = new ProcessRunner().Exec(commandLine, TimeSpan.FromSeconds(10)); ThrowIfFailed(process); }
public void ShouldAllowKillingTreeWhenRunInBackground() { SystemAssert.AssertProcessKilled("ping", () => { var process = new ProcessRunner().Start("cmd /c cmd /c ping 127.0.0.1 -n 20"); Assert.That(process.WasKilled, Is.False); process.KillTree(); Assert.That(process.WasKilled, Is.True); }); }
public void ShouldHandleMultilineOutput() { Using.Directory("processRunnerTest", () => { var lines = new StringBuilder().AppendLine("first line").Append("second line"); File.WriteAllText("multiline.txt", lines.ToString()); var runner = new ProcessRunner(); var process = runner.Exec("cmd /c type multiline.txt", TimeSpan.MaxValue); Assert.That(process.StandardOutput, Is.EqualTo(lines.ToString())); }); }
public void Run_ValidCommand_LogOutputToDebug(MemoryAppender appender, ProcessRunner sut) { //Arrange BasicConfigurator.Configure(appender); //Act sut.Run("help", "dir"); //Assert appender.Events.Should().OnlyContain(x => x.Level == Level.DEBUG); }
public static void SvnRepo(Action<string> test) { var repoPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var currentDirectory = Environment.CurrentDirectory; Using.Directory(repoPath, () => { var process = new ProcessRunner().Exec("svnadmin create .", TimeSpan.FromSeconds(30)); NUnit.Framework.Assert.That(process.WasSuccessful, process.ToString()); Using.Directory(Path.Combine(currentDirectory, "svn"), () => test(MakeFileUrl(repoPath))); }); }
public static GitProvider Clone(string url, ILogger log, TimeSpan commandTimeout) { var localPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(localPath); var runner = new ProcessRunner(localPath); var process = runner.Exec(string.Format("git clone \"{0}\"", url), TimeSpan.FromMinutes(5)); if (!process.WasSuccessful) throw new ArgumentException(process.ToString()); return new GitProvider(log, localPath, commandTimeout); }
public void Run_ValidCommand_AddPrefixToLog(string prefix, MemoryAppender appender, ProcessRunner sut) { //Arrange sut.LogPrefix = prefix; BasicConfigurator.Configure(appender); //Act sut.Run("help", "dir"); //Assert appender.Events.Should().OnlyContain(x => x.RenderedMessage.Contains(prefix)); }
public void SingleLineOfOutput() { ProcessRunner runner = new ProcessRunner(); runner.WorkingDirectory = GetConsoleAppFileName().GetParentDirectory(); string echoText = "Test"; string expectedOutput = "Test\r\n"; runner.RedirectStandardOutput = true; runner.Start(GetConsoleAppFileName(), String.Concat("-echo:", echoText)); string output = runner.OpenStandardOutputReader().ReadToEnd(); Assert.AreEqual(expectedOutput, output, "Should have some output."); }
public void ExecShouldKillProcessAfterTimeout() { SystemAssert.AssertProcessKilled("ping", () => { var runner = new ProcessRunner(); var start = DateTime.Now; runner.Exec("ping 127.0.0.1 -n 20", TimeSpan.FromMilliseconds(100)); // Lots of buffer adding because of virtualization, etc // Should take 20 seconds or so without being killed Assert.That(DateTime.Now - start, Is.LessThan(TimeSpan.FromSeconds(8))); }); }
public void ProcessExitEvent() { ProcessRunner runner = new ProcessRunner(); runner.WorkingDirectory = GetConsoleAppFileName().GetParentDirectory(); string echoText = "Test"; runner.Start(GetConsoleAppFileName(), String.Concat("-echo:", echoText)); bool exited = runner.WaitForExitAsync().Wait(2500); Assert.IsTrue(exited, "Timed out waiting for exit event."); Assert.AreEqual(0, runner.ExitCode, "Exit code should be zero."); }
public async void Run() { SvcUtilMessageView.ClearText(); var commandLine = new SvcUtilCommandLine(Options); commandLine.Command = GetSvcUtilPath(); using (ProcessRunner processRunner = new ProcessRunner()) { this.ExitCode = await processRunner.RunInOutputPadAsync(SvcUtilMessageView.Category, commandLine.Command, commandLine.GetArguments()); } if (ProcessExited != null) { ProcessExited(this, new EventArgs()); } }
public bool Run(TextDocument document) { Debug.Assert(document.Uri != null, "The document needs to be saved before NVShaderPerf can be run."); Logger.Info(CultureInfo.InvariantCulture, "Running NVShaderPerf.exe for \"{0}\".", Path.GetFileName(document.Uri.LocalPath)); string programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); string shaderPerfFileName = Path.Combine(programFilesPath, @"NVIDIA Corporation\NVIDIA ShaderPerf\NVShaderPerf.exe"); if (!File.Exists(shaderPerfFileName)) { string message = "NVIDIA ShaderPerf (NVShaderPerf.exe) not found."; Logger.Error(message); _outputService.WriteLine(message); return false; } using (var processRunner = new ProcessRunner()) { processRunner.OutputDataReceived += (s, e) => _outputService.WriteLine(e.Data); processRunner.ErrorDataReceived += (s, e) => _outputService.WriteLine(e.Data); // Analyze the passes in the effect. var shaderParser = new ShaderParser(new HlslIntelliSense()); var techniquesAndPasses = shaderParser.GetTechniquesAndPasses(document.AvalonEditDocument.CreateSnapshot()); foreach (var techniqueAndPasses in techniquesAndPasses) { string technique = techniqueAndPasses.Item1; foreach (string pass in techniqueAndPasses.Item2) { _outputService.WriteLine(string.Format(CultureInfo.InvariantCulture, "NVShaderPerf.exe -g G80 -t {0} -p {1} {2}\n", technique, pass, Path.GetFileName(document.Uri.LocalPath))); processRunner.Start(shaderPerfFileName, string.Format(CultureInfo.InvariantCulture, "-g G80 -t {0} -p {1} -include \"{2}\" \"{3}\"", technique, pass, Path.GetDirectoryName(document.Uri.LocalPath), document.Uri.LocalPath)); processRunner.WaitForExit(); if (processRunner.ExitCode != 0) { // Break on error. Logger.Info("Failed."); //_outputService.WriteLine(); return false; } } } Logger.Info("Success."); //_outputService.WriteLine(); return true; } }
public void NonZeroExitCode() { ProcessRunner runner = new ProcessRunner(); runner.WorkingDirectory = GetConsoleAppFileName().GetParentDirectory(); int expectedExitCode = 1; //Assert.IsFalse(runner.IsRunning, "IsRunning should be false."); runner.Start(GetConsoleAppFileName(), String.Concat("-exitcode:", expectedExitCode.ToString())); runner.WaitForExit(); Assert.AreEqual(expectedExitCode, runner.ExitCode, "Exit code is incorrect."); //Assert.IsFalse(runner.IsRunning, "IsRunning should be false."); }
public void ProcRunner_ExecutionFailed() { // Arrange string exeName = TestUtils.WriteBatchFileForTest(TestContext, "exit -2"); TestLogger logger = new TestLogger(); ProcessRunnerArguments args = new ProcessRunnerArguments(exeName, logger); ProcessRunner runner = new ProcessRunner(); // Act bool success = runner.Execute(args); // Assert Assert.IsFalse(success, "Expecting the process to have failed"); Assert.AreEqual(-2, runner.ExitCode, "Unexpected exit code"); }
public DeployForm(IEnvironmentLoader environmentLoader, IDeployCommandBuilder commandBuilder, ProcessRunner processRunner) { this.environmentLoader = environmentLoader; this.commandBuilder = commandBuilder; this.processRunner = processRunner; InitializeComponent(); Load += (sender, e) => Initialize(); uxUseExternalFile.CheckedChanged += (sender, e) => ToggleConfigSelection(); uxUsePackagedFile.CheckedChanged += (sender, e) => ToggleConfigSelection(); uxEnvironments.SelectedValueChanged += (sender, e) => LoadEnvironmentProperties(); uxLoadExternalFile.Click += (sender, e) => SelectFile(new OpenFileDialog(), LoadExternalFile); uxSave.Click += (sender, e) => SelectFile(new SaveFileDialog(), Save); uxDeploy.Click += (sender, e) => ShowDeployLog(Deploy()); }
public FakeCakeContext () { testsDir = new DirectoryPath ( System.IO.Path.GetFullPath (AppDomain.CurrentDomain.BaseDirectory)); var fileSystem = new FileSystem (); var environment = new CakeEnvironment (); var globber = new Globber (fileSystem, environment); log = new FakeLog (); var args = new FakeCakeArguments (); var processRunner = new ProcessRunner (environment, log); var registry = new WindowsRegistry (); context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry); context.Environment.WorkingDirectory = testsDir; }
public void NoOutput() { ProcessRunner runner = new ProcessRunner(); runner.WorkingDirectory = GetConsoleAppFileName().GetParentDirectory(); runner.RedirectStandardOutput = true; runner.RedirectStandardError = true; runner.Start(GetConsoleAppFileName()); runner.WaitForExit(); //Assert.IsFalse(runner.IsRunning, "IsRunning should be false."); Assert.AreEqual(0, runner.ExitCode, "Exit code is incorrect."); Assert.AreEqual("", runner.OpenStandardOutputReader().ReadToEnd(), "Should not be any output."); Assert.AreEqual("", runner.OpenStandardErrorReader().ReadToEnd(), "Should not be any error output."); }
public FakeCakeContext () { testsDir = new DirectoryPath ( System.IO.Path.GetFullPath (AppDomain.CurrentDomain.BaseDirectory)); var fileSystem = new FileSystem (); var environment = new CakeEnvironment (new CakePlatform (), new CakeRuntime ()); var globber = new Globber (fileSystem, environment); log = new FakeLog (); var args = new FakeCakeArguments (); var processRunner = new ProcessRunner (environment, log); var registry = new WindowsRegistry (); var toolRepo = new ToolRepository (environment); var config = new Core.Configuration.CakeConfigurationProvider (fileSystem, environment).CreateConfiguration (testsDir, new Dictionary<string, string> ()); var toolResolutionStrategy = new ToolResolutionStrategy (fileSystem, environment, globber, config); var toolLocator = new ToolLocator (environment, toolRepo, toolResolutionStrategy); context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry, toolLocator); context.Environment.WorkingDirectory = testsDir; }
public FakeCakeContext () { testsDir = new DirectoryPath ( System.IO.Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location)); var fileSystem = new FileSystem (); var environment = new CakeEnvironment (); var globber = new Globber (fileSystem, environment); log = new FakeLog (); var args = new FakeCakeArguments (); var processRunner = new ProcessRunner (environment, log); var registry = new WindowsRegistry (); var toolRepo = new ToolRepository (environment); var config = new Core.Configuration.CakeConfigurationProvider (fileSystem, environment).CreateConfiguration (new Dictionary<string, string> ()); var toolResStrat = new ToolResolutionStrategy (fileSystem, environment, globber, config); var toolLocator = new ToolLocator (environment, toolRepo, toolResStrat); context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry, toolLocator); context.Environment.WorkingDirectory = testsDir; }
public void TestFormatArgs() { string tempfile = Path.GetTempFileName(); try { ProcessRunner runner = new ProcessRunner("cmd.exe", "/C", "ECHO", "Hello", ">{0}"); runner.StartFormatArgs(tempfile); Assert.AreEqual(0, runner.ExitCode); string output = File.ReadAllText(tempfile).Trim(); Assert.AreEqual("Hello", output); File.Delete(tempfile); Assert.AreEqual(0, runner.RunFormatArgs(tempfile)); output = File.ReadAllText(tempfile).Trim(); Assert.AreEqual("Hello", output); } finally { File.Delete(tempfile); } }
public string Pack(bool nuspec = true) { string content = null; ProcessRunner.When(p => p.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>())) .Do(info => { content = GetContent(info[1] as ProcessSettings); }); var tool = new ChocolateyPacker(FileSystem, Environment, ProcessRunner, Log, Globber, ChocolateyToolResolver); if (nuspec) { tool.Pack(NuSpecFilePath, Settings); } else { tool.Pack(Settings); } // Return the content. return(content); }
public UnityRunnerFixture() { Context = Substitute.For <ICakeContext>(); ProjectPath = new DirectoryPath("C:/Project"); Platform = Substitute.For <IUnityPlatform>(); DefaultToolPathExist = true; ProjectPathExist = true; Process = Substitute.For <IProcess>(); Process.GetExitCode().Returns(0); ProcessRunner = Substitute.For <IProcessRunner>(); ProcessRunner.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>()).Returns(Process); Environment = Substitute.For <ICakeEnvironment>(); Environment.WorkingDirectory = "/Working"; Environment.GetSpecialPath(Arg.Is(SpecialPath.ProgramFilesX86)).Returns("C:/Program Files (x86)"); FileSystem = Substitute.For <IFileSystem>(); FileSystem.Exist(Arg.Is <FilePath>(a => a.FullPath == "C:/Program Files (x86)/Unity/Editor/Unity.exe")).Returns(c => DefaultToolPathExist); FileSystem.Exist(Arg.Is <DirectoryPath>(a => ProjectPath != null && a.FullPath == ProjectPath.FullPath)).Returns(c => ProjectPathExist); }
public void ProcRunner_ExecutionSucceeded() { // Arrange var exeName = TestUtils.WriteBatchFileForTest(TestContext, @"@echo Hello world xxx yyy @echo Testing 1,2,3...>&2 "); var logger = new TestLogger(); var args = new ProcessRunnerArguments(exeName, true); var runner = new ProcessRunner(logger); // Act var success = runner.Execute(args); // Assert success.Should().BeTrue("Expecting the process to have succeeded"); runner.ExitCode.Should().Be(0, "Unexpected exit code"); logger.AssertMessageLogged("Hello world"); // Check output message are passed to the logger logger.AssertErrorLogged("Testing 1,2,3..."); // Check error messages are passed to the logger }
/// <summary> /// Start background process /// </summary> private void StartAscRunner(string flexPath) { currentSDK = flexPath; if (ascRunner != null && ascRunner.IsRunning) { ascRunner.KillProcess(); } string cmd = "-Duser.language=en -Duser.region=US" + " -classpath \"" + ascPath + ";" + flexShellsPath + "\" AscShell"; TraceManager.Add(TextHelper.GetString("Info.StartAscRunner") + "\n" + JvmConfigHelper.GetJavaEXE(jvmConfig) + " " + cmd, -1); // run asc shell ascRunner = new ProcessRunner(); ascRunner.WorkingDirectory = Path.GetDirectoryName(ascPath); ascRunner.RedirectInput = true; ascRunner.Run(JvmConfigHelper.GetJavaEXE(jvmConfig), cmd, true); ascRunner.Output += ascRunner_Output; ascRunner.Error += ascRunner_Error; errorState = 0; Thread.Sleep(100); }
public async Task ConfigureGitCredentials() { //We don't do this anymore, we just clone by doing this: https://{username}:{password}@github.com/{username}/project.git //AdysTech.CredentialManager //Console.WriteLine($"Configuring git credentials in CredentialManager..."); //var cred = new System.Net.NetworkCredential("PersonalAccessToken", _config.GitHubToken); //var icred = cred.ToICredential(); //icred.TargetName = "git:https://github.com"; //icred.Persistance = Persistance.LocalMachine; //var result = icred.SaveCredential(); //Console.WriteLine($"Credential configuration result: {result}"); //git config --global user.email "*****@*****.**" //git config --global user.name "Your Name" await ProcessRunner.RunAsyncAndLogToConsole("git", $"config --global user.email \"{_config.GitHubEmail}\""); await ProcessRunner.RunAsyncAndLogToConsole("git", $"config --global user.name \"{_config.GitHubUserName}\""); }
public void ProcRunner_ExecutionSucceeded() { // Arrange string exeName = WriteBatchFileForTest( @"@echo Hello world xxx yyy @echo Testing 1,2,3... "); TestLogger logger = new TestLogger(); ProcessRunner runner = new ProcessRunner(); // Act bool success = runner.Execute(exeName, null, null, 1000, logger); // Assert Assert.IsTrue(success, "Expecting the process to have succeeded"); Assert.AreEqual(0, runner.ExitCode, "Unexpected exit code"); logger.AssertMessageLogged("Hello world"); // Check output message are passed to the logger logger.AssertMessageLogged("Testing 1,2,3..."); logger.AssertErrorLogged("'xxx' is not recognized as an internal or external command,"); // Check error messages are passed to the logger }
public void ProcRunner_ExecutionSucceeded() { // Arrange string exeName = TestUtils.WriteBatchFileForTest(TestContext, @"@echo Hello world xxx yyy @echo Testing 1,2,3...>&2 "); TestLogger logger = new TestLogger(); ProcessRunnerArguments args = new ProcessRunnerArguments(exeName, true, logger); ProcessRunner runner = new ProcessRunner(); // Act bool success = runner.Execute(args); // Assert Assert.IsTrue(success, "Expecting the process to have succeeded"); Assert.AreEqual(0, runner.ExitCode, "Unexpected exit code"); logger.AssertMessageLogged("Hello world"); // Check output message are passed to the logger logger.AssertErrorLogged("Testing 1,2,3..."); // Check error messages are passed to the logger }
protected virtual void Run(string args, string workingDirectory) { try { if (!args.StartsWith("status")) { TraceManager.AddAsync("svn " + args); } runner = new ProcessRunner(); runner.WorkingDirectory = workingDirectory; runner.Run(GetSvnCmd(), args); runner.Output += new LineOutputHandler(runner_Output); runner.Error += new LineOutputHandler(runner_Error); runner.ProcessEnded += new ProcessEndedHandler(runner_ProcessEnded); } catch (Exception ex) { runner = null; String label = TextHelper.GetString("SourceControl.Info.UnableToStartCommand"); TraceManager.AddAsync(label + "\n" + ex.Message); } }
/// <summary> /// Setups the wireless network. /// </summary> /// <param name="adapterName">Name of the adapter.</param> /// <param name="networkSsid">The network ssid.</param> /// <param name="password">The password.</param> /// <param name="countryCode">The 2-letter country code in uppercase. Default is US.</param> /// <returns>True if successful. Otherwise, false.</returns> public bool SetupWirelessNetwork(string adapterName, string networkSsid, string password = null, string countryCode = "US") { // TODO: Get the country where the device is located to set 'country' param in payload var var payload = $"country={countryCode}\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n"; payload += string.IsNullOrEmpty(password) ? $"network={{\n\tssid=\"{networkSsid}\"\n\t}}\n" : $"network={{\n\tssid=\"{networkSsid}\"\n\tpsk=\"{password}\"\n\t}}\n"; try { File.WriteAllText("/etc/wpa_supplicant/wpa_supplicant.conf", payload); ProcessRunner.GetProcessOutputAsync("pkill", "-f wpa_supplicant").Wait(); ProcessRunner.GetProcessOutputAsync("ifdown", adapterName).Wait(); ProcessRunner.GetProcessOutputAsync("ifup", adapterName).Wait(); } catch (Exception ex) { ex.Log(nameof(NetworkSettings)); return(false); } return(true); }
protected NuGetFixture() { Environment = Substitute.For <ICakeEnvironment>(); Environment.WorkingDirectory.Returns("/Working"); Process = Substitute.For <IProcess>(); Process.GetExitCode().Returns(0); ProcessRunner = Substitute.For <IProcessRunner>(); ProcessRunner.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>()).Returns(Process); NuGetToolResolver = Substitute.For <IToolResolver>(); NuGetToolResolver.Name.Returns("NuGet"); Log = Substitute.For <ICakeLog>(); FileSystem = new FakeFileSystem(true); // By default, there is a default tool. NuGetToolResolver.ResolveToolPath().Returns("/Working/tools/NuGet.exe"); FileSystem.GetCreatedFile("/Working/tools/NuGet.exe"); // Set standard output. Process.GetStandardOutput().Returns(new string[0]); }
public void Shutdown(WebData webData, bool?wholeSystem = null) { if (true == wholeSystem) { string command; string parameters; switch (Platform.Type) { case PlatformType.Windows: { command = "shutdown"; parameters = $"/s /t 60 /f /d u:00:00 /c \"JukeBox Shutdown Command Recevied by {webData.Session.GetUser()}\""; break; } case PlatformType.Linux: { command = "shutdown"; parameters = $"-h +1 \"JukeBox Shutdown Command Recevied by {webData.Session.GetUser()}\""; break; } default: throw new NotSupportedException("This platform does not support shutdown wholeSystem!"); } var result = ProcessRunner.Run(command, parameters, 10000); if (result.ExitCode == 0) { webData.Result.AddMessage(webData.Method, "System will shutdown in 60s..."); } else { throw new WebServerException(WebError.InternalServerError, result.Combined); } } webData.Result.AddMessage(webData.Method, "JukeBox will shutdown..."); program.ServiceParameters.CommitShutdown(); }
//public WindowsRemoteManagerExecutive() : base( // new YandexDiskCommunicator(ConstantValues.ConfigurationDefaultInfo.YandexDiskToken, ConstantValues.ConfigurationDefaultInfo.YandexDiskFolder), // new LocalLogger(), // new LocalCacheService() // ) //{ // this.ID = Handle.GetMacAddress().Replace("-", ""); // this.BaseFolder = @$"C:\Users\{Environment.UserName}\appdata\WRME"; //} private CommandExecutionResult ExecuteBat(Command command) { string BatContent = ""; foreach (string Instruction in command.Instructions) { if (Instruction.StartsWith("{")) { BatContent = BatContent + '\n' + Instruction.Replace("{", "").Replace("}", ""); } else if (Instruction.EndsWith("}") || Instruction.EndsWith("}\r")) { BatContent = BatContent + '\n' + Instruction.Replace("}", "").Replace("{", ""); break; } else { BatContent = BatContent + '\n' + Instruction; } } string FileName = this.BaseFolder + @"\" + "Command " + this.ID.ToString() + " " + command.ID.ToString() + ".bat"; if (File.Exists(FileName)) { File.Delete(FileName); } File.AppendAllText(FileName, BatContent); var result = ProcessRunner.ExecuteCMDCommand(FileName); File.Delete(FileName); return(new CommandExecutionResult { GivenCommandID = command.ID, Output = result }); }
private bool RunFfprobe(int index) { var path = PathHelper.ResolveAssetPath(TestFile); bool result; using (ProcessRunner runner = new ProcessRunner(AppConfigHelper.FfprobeExe)) { runner.WaitForExitMilliseconds = 5_000; runner.WaitForExit = true; result = false; try { runner.Run( $@"-sexagesimal -print_format json -show_error -show_streams -show_format ""{path}""", this.TestOutputDirectory.FullName); result = true; } catch { result = false; } finally { Assert.IsTrue( runner.StandardOutput.Length > 1200, $"Expected stdout to at least include ffmpeg header but it was only {runner.StandardOutput.Length} chars. StdOut:\n{runner.StandardOutput}"); Assert.IsTrue( runner.ErrorOutput.Length > 1300, $"Expected stderr to at least include ffmpeg header but it was only {runner.ErrorOutput.Length} chars. StdErr:\n{runner.ErrorOutput}"); Assert.AreEqual(0, runner.ExitCode); } } return(result); }
public void TestStdOutput() { using (ProcessRunner runner = new ProcessRunner("cmd.exe")) { StringWriter wtr = new StringWriter(); StringWriter err = new StringWriter(); ProcessOutputEventHandler handler = delegate(object o, ProcessOutputEventArgs e) { if (e.Error) { err.WriteLine(e.Data); } else { wtr.WriteLine(e.Data); } }; runner.OutputReceived += handler; Assert.AreEqual(0, runner.Run("/C", "dir", "/b", "/on", "/ad-h-s", "c:\\")); Assert.AreEqual(String.Empty, err.ToString()); StringReader rdr = new StringReader(wtr.ToString()); List <DirectoryInfo> rootdirs = new List <DirectoryInfo>(new DirectoryInfo("C:\\").GetDirectories()); rootdirs.Sort(delegate(DirectoryInfo x, DirectoryInfo y) { return(StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name)); }); foreach (DirectoryInfo di in rootdirs) { if ((di.Attributes & (FileAttributes.Hidden | FileAttributes.System)) != 0) { continue; } Assert.AreEqual(di.Name, rdr.ReadLine()); } Assert.AreEqual(null, rdr.ReadLine()); } }
public void ProcRunner_FailsOnTimeout() { // Arrange // Calling TIMEOUT can fail on some OSes (e.g. Windows 7) with the error // "Input redirection is not supported, exiting the process immediately." // Alternatives such as // pinging a non-existent address with a timeout were not reliable. var exeName = TestUtils.WriteBatchFileForTest(TestContext, @"waitfor /t 2 somethingThatNeverHappen @echo Hello world "); var logger = new TestLogger(); var args = new ProcessRunnerArguments(exeName, true) { TimeoutInMilliseconds = 100 }; var runner = new ProcessRunner(logger); var timer = Stopwatch.StartNew(); // Act var success = runner.Execute(args); // Assert timer.Stop(); // Sanity check that the process actually timed out logger.LogInfo("Test output: test ran for {0}ms", timer.ElapsedMilliseconds); // TODO: the following line throws regularly on the CI machines (elapsed time is around 97ms); // Assert.IsTrue(timer.ElapsedMilliseconds >= 100, "Test error: batch process exited too early. Elapsed time(ms): {0}", timer.ElapsedMilliseconds); Assert.IsFalse(success, "Expecting the process to have failed"); Assert.AreEqual(ProcessRunner.ErrorCode, runner.ExitCode, "Unexpected exit code"); logger.AssertMessageNotLogged("Hello world"); logger.AssertWarningsLogged(1); // expecting a warning about the timeout Assert.IsTrue(logger.Warnings.Single().Contains("has been terminated")); }
public static void Run(TypeInfo type, string board = "native") { var dll = type.Assembly.Location; string result = ""; string[] parameters = new string[] { String.Format("{0}", dll), String.Format("-e{0}", type.Name), String.Format("-tPCVS"), "--override", //"--verbose", }; //-tArduino int ret; if (Debugger.IsAttached) { //ret = ECS_Main.Main(parameters); ret = 1; } else { parameters = parameters.Select(x => x.Contains(' ') ? '"' + x + '"' : x).ToArray(); string parameter = string.Join(" ", parameters); ret = ProcessRunner.RunAndStoreOutput( "ESharp", parameter, out result, null /*working dir*/); } if (ret != 0) { throw new Exception("Error Running Test: " + string.Join(" ", parameters) + "\r\n" + result); } }
protected override int Execute() { base.Execute(); if (FromCli && !string.IsNullOrEmpty(PackageIdArgument.ParsedValue)) { var packageId = PackageIdArgument.ParsedValue; var resolvePackageResult = DotNetRunner.ResolvePackage(packageId, SourceOption.ParsedValue, UpdateOption.HasValue(), string.Empty); if (resolvePackageResult.success) { var program = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Path.Combine(DotNetRunner.CliFolderPathCalculator.ToolsShimPath, resolvePackageResult.packageId) : resolvePackageResult.packageId; var run = ProcessRunner.Create(program) .IsGenerator() .WithArgument(Name); foreach (var option in Options) { if (option.HasValue()) { run.WithArgument("--" + option.LongName, option.Value()); } } run.Execute(false); return(1); } Log.Error($"Could not execute {Name} command for this packageId."); return(-1); } return(0); }
public void Push(string packageFilename, CancellationToken token) { var packageName = Path.GetFileName(packageFilename); Output?.Append("Publishing Package ", ConsoleColor.DarkCyan) .Append(packageName, ConsoleColor.Cyan) .AppendLine("...", ConsoleColor.DarkCyan); try { var name = Path.GetFileName(packageFilename); var path = Path.GetDirectoryName(packageFilename); var args = string.Join(" ", "push", $"\"{name}\"", "-NonInteractive", $"-Source \"{SourceUrl}\"", $"-ApiKey \"{ApiKey}\""); var result = ProcessRunner.Run(path, ExeFilename, args, Output); if (result.ExitCode != 0) { throw new ApplicationException($"NuGet Push failed with exit code {result.ExitCode}!"); } Output?.Append("Package ", ConsoleColor.DarkGreen) .Append(packageName, ConsoleColor.Green) .AppendLine(" published successfully.", ConsoleColor.DarkGreen); } catch (Exception error) { Output?.Append("Failed to publish package ", ConsoleColor.DarkRed) .Append(packageName, ConsoleColor.Red) .AppendLine("!", ConsoleColor.DarkRed) .AppendLine(error.UnfoldMessages(), ConsoleColor.DarkYellow); throw; } }
public FakeCakeContext() { testsDir = new DirectoryPath( System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory)); var fileSystem = new FileSystem(); log = new FakeLog(); var runtime = new CakeRuntime(); var platform = new FakePlatform(PlatformFamily.Windows); var environment = new CakeEnvironment(platform, runtime, log); var globber = new Globber(fileSystem, environment); var args = new FakeCakeArguments(); var processRunner = new ProcessRunner(environment, log); var registry = new WindowsRegistry(); var toolRepository = new ToolRepository(environment); var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, new FakeConfiguration()); IToolLocator tools = new ToolLocator(environment, toolRepository, toolResolutionStrategy); context = new CakeContext(fileSystem, environment, globber, log, args, processRunner, registry, tools); context.Environment.WorkingDirectory = testsDir; }
public static async Task UnitTest(IAgentContext context, CancellationToken token) { var args = new[] { "test", "\"Jenkins.Net.Tests\\Jenkins.Net.Tests.csproj\"", "--configuration Release", "--no-build", "--filter Category=unit", }; var info = new ProcessRunInfo { Filename = "dotnet", Arguments = string.Join(" ", args), WorkingDirectory = context.ContentDirectory, }; var runner = new ProcessRunner(context); var result = await runner.RunAsync(info, token); if (result.ExitCode != 0) { throw new ApplicationException($"Unit-Test Failed! [{result.ExitCode}]"); } }
public async void WiresUpStandardIo() { Action <string> outputCallback = null; Action <string> errorCallback = null; ProcessRunner.Run(null).ReturnsForAnyArgs(ExpectedProcess) .AndDoes(call => { var spec = call.Arg <ProcessRunSpec>(); outputCallback = spec.OutputCallback; errorCallback = spec.ErrorCallback; }); await Handler.ExecuteAsync(ExpectedParams); Assert.NotNull(outputCallback); Assert.NotNull(errorCallback); outputCallback("This is STDOUT"); errorCallback("This is STDERR"); ProcessTracker.Received(1).HandleProcessData(ExpectedParams.key, ProcessDataType.STDOUT, "This is STDOUT"); ProcessTracker.Received(1).HandleProcessData(ExpectedParams.key, ProcessDataType.STDERR, "This is STDERR"); }
protected ChocolateyFixture() { Environment = Substitute.For <ICakeEnvironment>(); Environment.WorkingDirectory = "/Working"; Process = Substitute.For <IProcess>(); Process.GetExitCode().Returns(0); ProcessRunner = Substitute.For <IProcessRunner>(); ProcessRunner.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>()).Returns(Process); Globber = Substitute.For <IGlobber>(); ChocolateyToolResolver = Substitute.For <IChocolateyToolResolver>(); Log = Substitute.For <ICakeLog>(); FileSystem = new FakeFileSystem(Environment); // By default, there is a default tool. ChocolateyToolResolver.ResolvePath().Returns("/Working/tools/choco.exe"); FileSystem.CreateFile("/Working/tools/choco.exe"); // Set standard output. Process.GetStandardOutput().Returns(new string[0]); }
private static async Task <ExitCode> UploadNugetPackageAsync( string nugetExePath, string symbolServerUrl, string apiKey, string nugetPackage, ILogger logger, int timeout) { var args = new List <string> { "push", nugetPackage, "-source", symbolServerUrl, apiKey, "-verbosity", "detailed" }; if (timeout > 0) { args.Add("-timeout"); args.Add(timeout.ToString(CultureInfo.InvariantCulture)); } ExitCode exitCode = await ProcessRunner.ExecuteAsync( nugetExePath, arguments : args, standardOutLog : logger.Write, standardErrorAction : logger.WriteError, toolAction : logger.Write); return(exitCode); }
public void Test() { var project = Path.GetFullPath(Path.Combine(SourceDirectory, @"..\MyConsole\MyConsole.csproj")); var publishDir = Path.GetFullPath(Path.Combine(SourceDirectory, @"..\MyConsole\publish")); IoHelpers.PurgeDirectory(publishDir); var includesDir = Path.GetFullPath(Path.Combine(SourceDirectory, @"..\includes")); Directory.CreateDirectory(includesDir); var dictionary = new Dictionary <string, string> { { "Default", "Default" }, { "Trimmed", "Trimmed" }, { "Fdd", "Framework Dependent" }, { "SingleFile", "Single File" }, { "SingleFileFdd", "Single File and Framework Dependent" }, { "SingleFileTrimmed", "Single File, Framework Dependent, and Trimmed" } }; foreach (var profile in dictionary) { var output = ProcessRunner.StartDotNet("dotnet", $"publish {project} -c Release /p:PublishProfile={profile.Key}"); WriteLine(output); Assert.True(Directory.Exists(Path.Combine(publishDir, profile.Key))); } foreach (var profile in dictionary) { var profileDir = Path.GetFullPath(Path.Combine(publishDir, profile.Key)); WriteDoco(includesDir, profile.Key, profileDir); var exePath = Path.Combine(profileDir, "MyConsole.exe"); var output = ProcessRunner.StartDotNet(exePath, ""); Assert.Contains("Hello World", output); Assert.Contains("SettingValue", output); } }
/// <summary> /// Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again. /// </summary> /// <param name="controllerAddress">The mac address of the controller will be used.</param> /// <param name="deviceAddress">The mac address of the device will be added to the trust list devices.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns true or false if the operation was successful. /// </returns> /// <exception cref="BluetoothErrorException">Failed to add to trust devices list:.</exception> public async Task <bool> Trust( string controllerAddress, string deviceAddress, CancellationToken cancellationToken = default) { try { // Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes. await ProcessRunner .GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken) .ConfigureAwait(false); // Makes the controller visible to other devices. await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken) .ConfigureAwait(false); // Readies the controller for pairing. Remember that you have three minutes after running this command to pair. await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken) .ConfigureAwait(false); // Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again. var result = await ProcessRunner .GetProcessOutputAsync(BcCommand, $"trust {deviceAddress}", null, cancellationToken) .ConfigureAwait(false); // Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole. await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken) .ConfigureAwait(false); return(result.Contains("Trusted: yes")); } catch (Exception ex) { throw new BluetoothErrorException($"Failed to add to trust devices list: {ex.Message}"); } }
private async Task RunDebugDiagAnalysis(DumpMetainfo dumpInfo, DirectoryInfo workingDir, string dumpFilePath) { //--dump = "C:\superdump\data\dumps\hno3391\iwb0664\iwb0664.dmp"--out= "C:\superdump\data\dumps\hno3391\iwb0664\debugdiagout.mht"--symbolPath = "cache*c:\localsymbols;http://msdl.microsoft.com/download/symbols"--overwrite string reportFilePath = Path.Combine(pathHelper.GetDumpDirectory(dumpInfo.Id), "DebugDiagAnalysis.mht"); string debugDiagExe = "SuperDump.DebugDiag.exe"; var tracer = dynatraceSdk.TraceOutgoingRemoteCall("Analyze", debugDiagExe, debugDiagExe, ChannelType.OTHER, debugDiagExe); try { await tracer.TraceAsync(async() => { using (var process = await ProcessRunner.Run(debugDiagExe, workingDir, $"--dump=\"{dumpFilePath}\"", $"--out=\"{reportFilePath}\"", "--overwrite", $"--tracetag \"{tracer.GetDynatraceStringTag()}\"" )) { string log = $"debugDiagExe exited with error code {process.ExitCode}" + $"{Environment.NewLine}{Environment.NewLine}stdout:{Environment.NewLine}{process.StdOut}" + $"{Environment.NewLine}{Environment.NewLine}stderr:{Environment.NewLine}{process.StdErr}"; Console.WriteLine(log); File.WriteAllText(Path.Combine(pathHelper.GetDumpDirectory(dumpInfo.Id), "superdump.debugdiag.log"), log); dumpRepo.AddFile(dumpInfo.Id, "DebugDiagAnalysis.mht", SDFileType.DebugDiagResult); } }); } catch (ProcessRunnerException e) { if (e.InnerException is FileNotFoundException) { Console.Error.WriteLine($"{debugDiagExe} not found. Check BinPath setting in appsettings.json."); } else { Console.Error.WriteLine($"Error during DebugDiag analyis: {e}"); } // do not abort analysis. } }
static int Main(string[] args) { if (!FindProgram()) { Console.Error.WriteLine("Cannot find Inno Setup Compiler!"); return(1); } try { //check if --debug flag is set -> skip this setup if (args.Any(a => a.ToLower() == "--debug")) { return(0); } //remove all flags args = args.Where(a => !a.StartsWith("--")).ToArray(); //call inno ProcessStartInfo si = new ProcessStartInfo(iscc, '"' + string.Join('"' + " " + '"', args) + '"'); si.UseShellExecute = false; si.RedirectStandardInput = true; si.RedirectStandardOutput = true; var result = ProcessRunner.Run(si); string str = result.Combined; while (str.Contains("\r\n\r\n")) { str = str.Replace("\r\n\r\n", "\r\n"); } Console.WriteLine(str); return(result.ExitCode); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); return(2); } }
public /* for test purposes */ static bool ExecuteJavaRunner(AnalysisConfig config, IEnumerable <string> userCmdLineArguments, ILogger logger, string exeFileName, string propertiesFileName) { Debug.Assert(File.Exists(exeFileName), "The specified exe file does not exist: " + exeFileName); Debug.Assert(File.Exists(propertiesFileName), "The specified properties file does not exist: " + propertiesFileName); IgnoreSonarRunnerHome(logger); IEnumerable <string> allCmdLineArgs = GetAllCmdLineArgs(propertiesFileName, userCmdLineArguments, config); IDictionary <string, string> envVarsDictionary = GetAdditionalEnvVariables(logger); Debug.Assert(envVarsDictionary != null); logger.LogInfo(Resources.MSG_CallingSonarRunner); ProcessRunnerArguments runnerArgs = new ProcessRunnerArguments(exeFileName, logger) { CmdLineArgs = allCmdLineArgs, WorkingDirectory = Path.GetDirectoryName(exeFileName), EnvironmentVariables = envVarsDictionary }; ProcessRunner runner = new ProcessRunner(); bool success = runner.Execute(runnerArgs); success = success && !runner.ErrorsLogged; if (success) { logger.LogInfo(Resources.MSG_SonarRunnerCompleted); } else { logger.LogError(Resources.ERR_SonarRunnerExecutionFailed); } return(success); }
public MSTestRunnerFixture(FilePath toolPath = null, bool defaultToolExist = true) { ToolPath = "/ProgramFilesX86/Microsoft Visual Studio 12.0/Common7/IDE/mstest.exe"; Process = Substitute.For <IProcess>(); Process.GetExitCode().Returns(0); ProcessRunner = Substitute.For <IProcessRunner>(); ProcessRunner.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>()).Returns(Process); Globber = Substitute.For <IGlobber>(); Environment = Substitute.For <ICakeEnvironment>(); Environment.WorkingDirectory = "/Working"; Environment.GetSpecialPath(SpecialPath.ProgramFilesX86).Returns("/ProgramFilesX86"); FileSystem = Substitute.For <IFileSystem>(); FileSystem.Exist(Arg.Is <FilePath>(p => p.FullPath.Equals(ToolPath.FullPath))).Returns(defaultToolExist); if (toolPath != null) { FileSystem.Exist(Arg.Is <FilePath>(a => a.FullPath == toolPath.FullPath)).Returns(true); } }