我有一个来源的实用程序脚本,其中包含两个提示用户输入的函数; anykey
和yesno
。
如何测试提示?提示文字未显示在$output
。
另外,如何强制yesno
中的while循环突破测试中的while循环?
function anykey() { read -n 1 -r -s -p "${1:-Press any key to continue ...}"; }
function yesno() {
local -u yn
while true; do
# shellcheck disable=SC2162
read -N1 -p "${1:-Yes or no?} " yn
case $yn in
Y | N)
printf '%s' "$yn"
return
;;
Q)
warn 'Exiting...'
exit 1
;;
*)
warn 'Please enter a Y or a N'
;;
esac
done
}
我的utility.bats
文件中有以下内容:
#------------------------------------------------------------
# test yesno
if [[ -z "$(type -t yesno)" ]]; then
echo "yesno not defined after sourcing utility" >&2
exit 1
fi
@test 'yesno function exists' {
run type -t yesno
[ "$output" == 'function' ]
}
@test 'yesno accepts y' {
run yesno <<< 'y'
[[ "$status" == 0 ]]
[[ "$output" == 'Y' ]]
}
@test 'yesno accepts Y' {
run yesno <<< 'Y'
[[ "$status" == 0 ]]
[[ "$output" == 'Y' ]]
}
@test 'yesno accepts n' {
run yesno <<< 'n'
[[ "$status" == 0 ]]
[[ "$output" == 'N' ]]
}
@test 'yesno accepts N' {
run yesno <<< 'N'
[[ "$status" == 0 ]]
[[ "$output" == 'N' ]]
}
@test 'yesno accepts q' {
run yesno <<< 'q'
[[ "$status" == 1 ]]
[[ "$output" == 'Exiting...' ]]
}
@test 'yesno accepts Q' {
run yesno <<< 'Q'
[[ "$status" == 1 ]]
[[ "$output" == 'Exiting...' ]]
}
@test 'yesno rejects x' {
run yesno <<< 'x'
[[ "$output" == 'Please enter a Y or a N' ]]
}
除了最后一个yesno rejects x
之外的所有测试似乎都正常工作。由于while true
循环,最后一个挂起。如何在测试中模拟多个键盘输入?
编辑:警告功能很简单:
warn() { printf '%s\n' "$*" >&2; }
答案 0 :(得分:1)
似乎对我有用的只是提供足够的答案以摆脱循环:
@test 'yesno rejects x, then accepts N' {
run yesno <<< "xN"
[[ "${lines[0]}" == 'Please enter a Y or a N' ]]
[[ "${lines[1]}" == 'N' ]]
[[ "${lines[3]}" == '' ]]
}
@test 'yesno rejects x and space, then accepts Y' {
run yesno <<< 'x Y'
[[ "${lines[0]}" == 'Please enter a Y or a N' ]]
[[ "${lines[1]}" == 'Please enter a Y or a N' ]]
[[ "${lines[2]}" == 'Y' ]]
[[ "${lines[3]}" == '' ]]
}