0

我正在为我们的 QA 组制定自动化策略,并且需要能够捕获脚本和 EXE 文件的输出。当我将此代码作为控制台应用程序运行时,我能够成功捕获 plink.exe 的输出:

class Program
{
    static void Main(string[] args)
    {
        Process process = new Process();
        process.StartInfo.FileName = @"C:\Tools\plink.exe";
        process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

        string output = process.StandardOutput.ReadToEnd();
        process.WaitForExit();

        output = output.Trim().ToLower(); // Output is successfully captured here

        if (output == "pass")
        {
            Console.WriteLine("Passed!");
        }
    }
}

执行此命令大约需要一分钟,我成功地将结果捕获到输出变量。

但是,当我将相同的代码编译为 DLL 并通过 NUnit 运行时,代码会立即完成并以 output == NULL 的值失败:

[TestFixture]
public class InstallTest
{
    [Test]
    public void InstallAgentNix()
    {
        Process process = new Process();
        process.StartInfo.FileName = @"C:\Tools\plink.exe";
        process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

        string output = process.StandardOutput.ReadToEnd();

        process.WaitForExit();

        output = output.Trim().ToLower();

        Assert.AreEqual("pass", output, "Agent did not get installed");
    }
}

我已将问题范围缩小到一行string output = process.StandardOutput.ReadToEnd()。如果我注释掉这一行,执行时间大约是一分钟,并且操作在远程机器上成功执行(test.sh 在远程 Linux 机器上执行)。

我希望我遗漏了一些简单的东西——我不想找到不同的测试工具。

它看起来类似于此处的(未解决的)问题:为什么在使用控制台应用程序进行测试时,在 DLL 文件中启动的进程可以工作,但在被另一个 DLL 文件调用时却不行?

4

2 回答 2

1

OK, it took me all night but I figured it out. I have to RedirectStandardInput in addition to redirecting standard output for this to work.

Here is the fixed code that works in a DLL file. As an FYI, this fix resolves the problem in a Windows Forms application as well:

[TestFixture]
public class InstallTest
{
    [Test]
    public void InstallAgentNix()
    {
        Process process = new Process();
        process.StartInfo.FileName = @"C:\Tools\plink.exe";
        process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.Start();

        string output = process.StandardOutput.ReadToEnd();

        process.WaitForExit();

        output = output.Trim().ToLower();

        Assert.AreEqual("pass", output, "Agent did not get installed");
    }
}
于 2011-12-02T17:06:25.177 回答
0

正如您自己发现的那样,添加该行

process.StartInfo.RedirectStandardOutput = true;

解决问题。NUnit 必须设置另一个级别的间接。感谢您自己的回答,使我免于痛苦的调查。

虽然我不认为问题来自 DLL 文件/EXE 文件之间的差异,因为我在编译为控制台应用程序的测试项目中遇到了这个问题。

于 2013-08-30T16:20:06.317 回答