bash - 在 bash 中测试程序

标签 bash

我用 C++ 写了一个程序,现在我有一个二进制文件。我还生成了一堆用于测试的测试。现在我想用 bash 自动化测试过程。我想在我的二进制文件的一次执行中保存三件事:

  1. 执行时间
  2. 退出代码
  3. 程序的输出

现在我正在处理一个脚本,该脚本仅测试二进制文件是否完成其工作并返回 0,并且不保存我上面提到的任何信息。我的脚本看起来像这样

#!/bin/bash

if [ "$#" -ne 2 ]; then
    echo "Usage: testScript <binary> <dir_with_tests>"
    exit 1
fi

binary="$1"
testsDir="$2"

for test in $(find $testsDir -name '*.txt'); do
    testname=$(basename $test)

    encodedTmp=$(mktemp /tmp/encoded_$testname)
    decodedTmp=$(mktemp /tmp/decoded_$testname)

    printf 'testing on %s...\n' "$testname"

    if ! "$binary" -c -f $test -o $encodedTmp > /dev/null; then
        echo 'encoder failed'
        rm "$encodedTmp"
        rm "$decodedTmp"
        continue
    fi

    if ! "$binary" -u -f $encodedTmp -o $decodedTmp > /dev/null; then
        echo 'decoder failed'
        rm "$encodedTmp"
        rm "$decodedTmp"
        continue
    fi

    if ! diff "$test" "$decodedTmp" > /dev/null ; then
        echo "result differs with input"
    else
        echo "$testname passed"
    fi

    rm "$encodedTmp"
    rm "$decodedTmp"
done

我想将 $binary 的输出保存在一个变量中,而不是将其发送到 /dev/null。我还想使用 time bash 函数来节省时间

最佳答案

当您要求将输出保存在 shell 变量中时,我尝试在不使用输出重定向的情况下回答这个问题——输出重定向将输出保存在(临时)文本文件中(然后必须清理)。

保存命令输出

你可以替换这一行

if ! "$binary" -c -f $test -o $encodedTmp > /dev/null; then

if ! output=$("$binary" -c -f $test -o $encodedTmp); then

使用命令替换将 $binary 的程序输出保存在 shell 变量中。命令替换(结合 shell 变量赋值)还允许将程序的退出代码传递给调用 shell,因此条件 if 语句将继续检查 $binary 是否已执行没有错误。

您可以通过运行echo "$output" 查看程序输出。

节省时间

如果没有更复杂的进程间通信形式,作为另一个 shell 的子进程的 shell 就无法更改变量或其父进程的环境,因此这是我可以节省时间的唯一方法程序输出是将它们组合在一个变量中:

if ! time-output=$(time "$binary" -c -f $test -o $encodedTmp) 2>&1); then

由于 time 将其分析信息打印到 stderr,我使用括号运算符在子 shell 中运行命令,其 stderr 可以重定向到标准输出。可以通过运行 echo "$time-output" 查看编程输出和时间输出,它应该返回类似于以下内容的内容:

<program output>
<blank line>
real    0m0.041s
user    0m0.000s
sys     0m0.046s

关于bash - 在 bash 中测试程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036282/

相关文章:

linux - bash 空字符串比较问题

linux - 如何从当前引用时间开始计算时间

linux - bash 中数字数组中的数学运算..?

bash - 使用 awk 从 dig -x 的输出中获取 IP 地址和名称

bash - 如何在ubuntu中回显斜线

bash - 为什么 for-in 循环不打印我想要的内容?

python - 管道长时间运行的进程

java - 从 java 运行 Bash 不起作用

regex - 在 bash/sed 中,如何匹配小写字母后跟大写字母?

bash 3.2.57 (macOS) 中的字符串连接