You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest正确测试Click CLI中ClickException是否被抛出

问题原因

Click 框架内部会自动捕获命令抛出的 ClickException,将其转换为退出码为 1 的 SystemExit 异常,因此你直接在 runner.invoke 外层捕获 ClickException 会失败。

解决方案

方法1:校验runner.invoke返回的Result对象(官方推荐)

CliRunner.invoke 执行后返回的Result对象已经内置了执行结果、异常、输出内容等所有信息,直接校验对应属性即可,无需手动捕获异常:

def test_not_in_folder():
    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(cli.my_function)
        # 校验命令异常退出
        assert result.exit_code == 1
        # 校验抛出的异常类型符合预期
        assert isinstance(result.exception, ClickException)
        # 可选:校验异常提示输出符合预期
        assert "You aren't in the right folder" in result.output

方法2:直接调用命令函数(仅校验函数逻辑)

如果不需要测试CLI路由、参数解析等链路,只验证函数本身的异常抛出逻辑,可以直接调用函数,此时可以正常捕获ClickException:

def test_not_in_folder():
    with pytest.raises(ClickException, match="You aren't in the right folder"):
        my_function()

内容的提问来源于stack exchange,提问作者ConorBaumgart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:54:05