【问题标题】:Is there a way to bail from a bats test?有没有办法从蝙蝠测试中保释出来?
【发布时间】:2018-10-04 02:25:10
【问题描述】:

有没有办法摆脱整个测试文件?整个测试套件?

类似的东西

@test 'dependent pgm unzip' {
  command -v unzip || BAIL 'missing dependency unzip, bailing out'
}

编辑:

我可以做类似的事情

#!/usr/bin/env bats

if [[ -z "$(type -t unzip)" ]]; then
  echo "Missing dep unzip"
  exit 1
fi

@test ...

这对于在测试开始时运行检查非常有效,只是它不会作为报告的一部分输出。

但是,如果我想确定一个来源脚本是否正确定义了一个函数,如果不是,则放弃,添加这种测试会阻止生成任何类型的报告。不显示成功的测试。

【问题讨论】:

  • 只是为了确保我明白你在问什么,你想知道 3 件事吗? 1. 如何中止单个测试文件的剩余部分 2. 如何中止所有测试文件的剩余部分 3. 如何输出中止消息以及其他测试输出(即成功的测试)。对吗?
  • 是的,没错。

标签: bats-core


【解决方案1】:

TL;DR

  • 要查看中止消息,请使用>&2 将全局范围内的消息重定向到stderr
  • 要在失败后中止所有文件,请在全局范围内使用exit 1
  • 要仅中止单个文件,请创建一个 setup 函数,该函数使用 skip 仅中止该文件中的测试。
  • 要使单个文件中的测试失败,请创建一个 setup 函数,该函数使用 return 1 使该文件中的测试失败。

更详细的答案

中止所有个文件

你的第二个例子几乎在那里。诀窍是将输出重定向到stderr1

在全局范围内使用 exitreturn 1 将停止整个测试套件。

#!/usr/bin/env bats

if [[ -z "$(type -t unzip)" ]]; then
  echo "Missing dep unzip" >&2
  return 1
fi

@test ...

缺点是中止文件中和之后的任何测试都将运行,即使这些测试通过了。

中止单个文件

一个更细粒度的解决方案是添加一个setup2 函数,如果依赖项不存在,该函数将skip3

由于setup 函数在定义它的文件中的每个测试之前被调用, 如果缺少依赖项,将跳过该文件中的所有测试。

#!/usr/bin/env bats

setup(){
    if [[ -z "$(type -t unzip)" ]]; then
        skip "Missing dep unzip"
    fi
}

@test ...

失败而不是跳过

也有可能失败具有未满足依赖性的测试。使用return 1 来自测试的setup 函数将使该文件中的所有测试失败:

#!/usr/bin/env bats

setup(){
    if [[ -z "$(type -t unzip)" ]]; then
        echo "Missing dep unzip"
        return 1
    fi
}

@test ...

由于消息输出不在全局范围内,因此不必将其重定向到sdterr(尽管这也可以)。

脚注

  1. the page about Bats-Evaluation-Process in the wiki 的底部和手册中提到了这一点(如果你运行man 7 bats):

     CODE OUTSIDE OF TEST CASES
    
         You can include code in your test file outside of @test functions.
         For example, this may be  useful  if  you  want  to check for
         dependencies and fail immediately if they´re not present. However,
         any output that you print in code outside of @test, setup or teardown
         functions must be redirected to stderr (>&2). Otherwise, the output
         may cause Bats to fail by polluting the TAP stream on stdout.
    
  2. 有关setup的详细信息,请参阅https://github.com/bats-core/bats-core#setup-and-teardown-pre--and-post-test-hooks

  3. 有关skip 的详细信息,请参阅https://github.com/bats-core/bats-core#skip-easily-skip-tests

【讨论】:

  • 谢谢。这很有帮助。
  • 一个极好的答案。
猜你喜欢
  • 2022-08-02
  • 2012-07-04
  • 2017-06-19
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
相关资源
最近更新 更多