如何使用 bats 测试 read -p

How to test `read -p` using bats

我有一个要获取的实用程序脚本,其中包含两个提示用户输入的函数; 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]}" == '' ]]
}