在尝试测试一种检查GitLab服务器是否运行5秒的方法时,我在检测错误消息时遇到了一些困难。
功能检查GitLab服务器状态
check_for_n_seconds_if_gitlab_server_is_running() {
duration=$1
echo "duration=$duration"
running="false"
if [ "$running" == "false" ]; then
echo "ERROR, did not find the GitLab server running within $duration seconds!"
exit 1
fi
}测试代码
#!./test/libs/bats/bin/bats
load 'libs/bats-support/load'
load 'libs/bats-assert/load'
load 'libs/bats-file/load'
source src/helper.sh
@test "If error is thrown if the GitLab server is not running within 5 seconds after uninstallation." {
# run the tested method
check_for_n_seconds_if_gitlab_server_is_running 4
assert_failure
assert_output --partial "ERROR, did not find the GitLab server running within 4 seconds!"
}预期行为
我希望测试能够通过,因为exit 1已经到达,而且我认为它会导致失败。
观察到的行为
当包含出口1时,测试失败,测试的输出为:
如果卸载后5秒内没有运行
服务器,则引发GitLab✗错误。
当exit 1被注释掉时,测试失败,测试的输出是:
✗ If error is thrown if the GitLab server is not running within 5 seconds after uninstallation.
(from function `assert_failure' in file test/libs/bats-assert/src/assert.bash, line 140,
in test file test/long_test_helper.bats, line 17)
`assert_failure' failed
duration=4
ERROR, did not find the GitLab server running within 4 seconds!
-- command succeeded, but it was expected to fail --
output :
--问题
如何确保测试检测抛出的错误?/如何抛出error/exit 1命令以确保assert_failure测试通过?
发布于 2021-08-19 18:49:21
问题是,我试图从测试函数中运行一个函数,而不是从单独的bash运行。我是通过复制另一个使用run bash -c命令的工作示例来发现的,该命令在相同的函数上的行为确实与预期的一样。因此,在实践中,以下工作:
测试代码
#!./test/libs/bats/bin/bats
load 'libs/bats-support/load'
load 'libs/bats-assert/load'
load 'libs/bats-file/load'
@test "If error is thrown if the GitLab server is not running within 5 seconds after uninstallation." {
run bash -c "source src/helper.sh && check_for_n_seconds_if_gitlab_server_is_running"
assert_failure
assert_output --partial "ERROR, did not find the GitLab server running within 4 seconds!"
}测试功能代码
check_for_n_seconds_if_gitlab_server_is_running() {
duration=$1
echo "duration=$duration"
running="false"
if [ "$running" == "false" ]; then
echo "ERROR, did not find the GitLab server running within $duration seconds!"
exit 1
fi
}预期行为
通过通过run bash -c命令调用函数,测试通过:
如果卸载后5秒内没有运行
服务器,则引发GitLab✓错误。
1次测试,0次失败
备注
如果有人能够包含一个不通过单独的run bash -c命令调用函数而工作的MWE,但直接从测试函数中调用该函数,请将其作为单独的答案发布。
https://stackoverflow.com/questions/68853013
复制相似问题