gpt4 book ai didi

bats-core - 如何使用 bat 测试 `read -p`

转载 作者:行者123 更新时间:2023-12-02 20:25:14 30 4
gpt4 key购买 nike

我有一个要获取的实用程序脚本,其中包含两个提示用户输入的函数; anykeyyesno

如何测试提示?提示文本不会显示在 $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 函数很简单:

warn() { printf '%s\n' "$*">&2; }

最佳答案

对我来说似乎有用的是提供足够的答案以跳出循环:

@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]}" == '' ]]
}

关于bats-core - 如何使用 bat 测试 `read -p`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162304/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com