5

我编写了一个我想测试的命令行工具(我不想从命令行运行单元测试)。我想将一组特定的输入选项映射到特定的输出。我还没有找到任何现有的工具。该应用程序只是一个二进制文件,可以用任何语言编写,但它接受 POSIX 选项并写入标准输出。

类似于以下内容:

  • 对于每组已知的输入选项:
    1. 使用指定的输入启动应用程序。
    2. 管道输出到文件。
    3. 将输出与存储的(期望的)输出进行比较。
    4. 如果 diff 不为空,则记录错误。

(顺便说一句,这就是你所说的集成测试而不是单元测试吗?)

编辑:我知道我将如何为此编写自己的工具,我不需要代码帮助。我想知道的是如果这已经完成了。

4

5 回答 5

6

DejaGnu是一个成熟且有点标准的框架,用于为 CLI 程序编写测试套件。

这是从本教程中获取的示例测试:

# send a string to the running program being tested:
send "echo Hello world!\n"

# inspect the output and determine whether the test passes or fails:
expect {
    -re "Hello world.*$prompt $" {
        pass "Echo test"
    }
    -re "$prompt $" {
        fail "Echo test"
    }
    timeout {
        fail "(timeout) Echo test"
    }
}

从长远来看,使用这样一个完善的框架可能比你自己想出的任何东西都要好,除非你的需求非常简单。

于 2013-02-15T22:27:19.333 回答
4

您正在寻找 BATS(Bash 自动测试系统): https ://github.com/bats-core/bats-core

从文档:

example.bats contains
#!/usr/bin/env bats

@test "addition using bc" {
  result="$(echo 2+2 | bc)"
  [ "$result" -eq 4 ]
}  

@test "addition using dc" {
  result="$(echo 2 2+p | dc)"
  [ "$result" -eq 4 ]
}


$ bats example.bats

 ✓ addition using bc
 ✓ addition using dc

2 tests, 0 failures

于 2015-12-29T01:50:14.980 回答
0

好吧,我认为每种语言都应该有一种执行外部进程的方法。

在 C# 中,您可以执行以下操作:

var p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\file-to-execute.exe");
... //You can set parameters here, etc.
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.Start();

//To read the standard output:
var output = p.StandardOutput.ReadToEnd();

我从来不用写标准输入,但我相信也可以通过访问来完成p.StandardInput。这个想法是将两个输入都视为Stream对象,因为它们就是这样。

在 Python 中有subprocess模块。根据其文档:

subprocess 模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。

在为几个月前编写的编译器的代码生成部分编写单元测试时,我必须这样做:在我的编译器中编写单元测试(生成 IL)

于 2013-02-01T10:30:37.693 回答
0

We wrote should, a single-file Python program to test any CLI tool. The default usage is to check that a line of the output contains some pattern. From the docs:

# A .should file launches any command it encounters.
echo "hello, world"

# Lines containing a `:` are test lines.
# The `test expression` is what is found at the right of the `:`.
# Here 'world' should be found on stdout, at least in one line.
:world

# What is at the left of the `:` are modifiers.
# One can specify the exact number of lines where the test expression has to appear.
# 'moon' should not be found on stdout.
0:moon

Should can check occurrences counts, look for regular expressions, use variables, filter tests, parse json data, and check exit codes.

于 2020-07-09T23:09:09.830 回答
-3

当然,它已经完成了数千次。但是编写一个工具来运行简单的 shell 脚本或批处理文件就像你建议的那样是一项微不足道的任务,几乎不值得尝试变成一个通用工具。

于 2013-02-03T16:44:13.557 回答