1

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

如何测试提示?提示文本不显示在$output.

另外,如何强制yesnowhile 循环从测试中跳出 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; }

4

1 回答 1

3

似乎对我有用的只是提供足够的答案来摆脱循环:

@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]}" == '' ]]
}
于 2019-10-02T16:25:13.780 回答