如何在bash中测试程序? (功能测试)

时间:2019-09-27 07:59:52

标签: linux bash testing automated-tests

我用C编写了一个名为gcd的程序,该程序返回我调用的最大公约数:

$ ./gcd 42 36
6

我可以使用以下命令测试这些输入:

#!/bin/bash 

[[ $(./a.out 42 36) == "6" ]] || exit 1
[[ $(./a.out 42 11) == "1" ]] || exit 1

不幸的是,我没有诸如这样的摘要

ran 11 tests, 0 failures, 11 successful tests

有没有非常简单的模板/框架可以在程序级别进行此类测试(不是单元测试)?

1 个答案:

答案 0 :(得分:1)

我会执行以下操作(可能有点破解吧?)

#!/bin/bash

declare -A messages
declare -A statuses

[[ 0 -eq 0 ]] && statuses["test_name_here"]=0 || {
    messages["test_name_here"]="Failed to divide 1023/123";
    statuses["test_name_here"]=1
}
[[  0 -eq 1 ]] && statuses["test_name2_here"]=0 || {
    messages["test_name2_here"]="Failed to divide asd/123";
    statuses["test_name2_here"]=1
}

exit_code=0
pass=0
fail=0

# Iterate statuses by key!
for i in "${!statuses[@]}"
do
  echo -n "$i - "
  if [ ${statuses[$i]} -eq 0 ]; then
      echo "PASS"
      pass=$((pass + 1))
  else
      echo "FAIL message=${messages[$i]}"
      exit_code=1
      fail=$((fail + 1))
  fi
done

echo "Passed $pass, Failed $fail"
exit $exit_code

在此脚本中,您可以运行测试,命名测试并跟踪测试的成功或失败。最后,我打印统计信息并使用正确的代码退出(如果任何测试失败,则为= 0)。输出:

$ ~/tmp/test.sh
test_name_here - PASS
test_name2_here - FAIL message=Failed to divide asd/123
Passed 1, Failed 1
相关问题