【发布时间】:2021-11-15 16:11:28
【问题描述】:
我正在使用 Click 编写 CLI 并使用 pytest 进行测试。我有一个生成异常并引发我想测试的 ClickException 的命令:
@main.command(name="my-function")
def my_function():
try:
find_file()
except FileNotFoundError:
raise ClickException("You aren't in the right folder")
现在我要做的是编写一个测试来确保引发该异常。这是我写的测试,但失败了:
def test_not_in_folder():
runner = CliRunner()
with runner.isolated_filesystem():
with pytest.raises(ClickException):
runner.invoke(cli.my_function, catch_exceptions=False)
这个测试应该做的是运行我的函数并观察 ClickException 异常。如果引发该异常,则测试将通过。但是,当我运行 pytest 时,我得到 'Failed: DID NOT RAISE
我注意到的是,如果我打印出 'runner.invoke(cli.my_function)',我的命令返回的是 '
所以我的问题是:如何使用 pytest 正确验证 ClickException 是否被触发?
【问题讨论】:
标签: python pytest python-click