如何使用pytest测试异常和错误?

oro*_*ome 3 python error-handling exception-handling pytest python-2.7

我在我的Python代码中有函数来响应某些条件引发异常,并且想确认它们在我的pytest脚本中表现得如预期.

目前我有

def test_something():
    try:
        my_func(good_args)
        assert True
    except MyError as e:
        assert False
    try:
        my_func(bad_args)
        assert False
    except MyError as e:
        assert e.message == "My expected message for bad args"
Run Code Online (Sandbox Code Playgroud)

但这看起来很麻烦(需要对每个案例重复).

有没有办法使用Python测试异常和错误,或者这样做的首选模式?

def test_something():
    with pytest.raises(TypeError) as e:
        my_func(bad_args)
        assert e.message == "My expected message for bad args"
Run Code Online (Sandbox Code Playgroud)

不起作用(即使我用断言替换它也会通过assert False).

Dam*_*gro 10

这条路:

with pytest.raises(<YourException>) as exc_info:
    <your code that should raise YourException>

exception_raised = exc_info.value
<do asserts here>
Run Code Online (Sandbox Code Playgroud)

  • Pytest 从那时起就开始发展。我发现这更优雅,更完整:/sf/answers/3959867341/ (6认同)