【问题标题】:Proper way to test ClickException was raised with pytest?pytest 提出了测试 ClickException 的正确方法?
【发布时间】: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


    【解决方案1】:

    我认为你在正确的轨道上。如果ClickException 没有被捕获,那么find_file 似乎没有抛出错误。我会确保find_file 的设置方式会引发FileNotFoundError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2019-12-12
      • 2017-06-06
      • 1970-01-01
      相关资源
      最近更新 更多