我有一个实用程序脚本,它包含两个提示用户输入的函数;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; }