简体   繁体   English

如何使用pytest测试try/except块的异常

[英]How to test the exception of try/except block using pytest

How can I properly test if the correct code has executed once an exception has been triggered in a try/except block?一旦在 try/except 块中触发异常,如何正确测试是否执行了正确的代码?

import pytest


def my_func(string):
    try:
        assert string == "pass"
        print("String is `pass`")
    except AssertionError:
        print("String is not 'pass'")



def test_my_func():
    with pytest.raises(AssertionError) as exc_info:
        my_func("fail")

    assert str(exc_info.value) == "String is not 'pass'"

Clearly, this test fails with Failed: DID NOT RAISE <class 'AssertionError'> as I caught the error in the try/except block.很明显,这个测试失败了Failed: DID NOT RAISE <class 'AssertionError'>因为我在 try/except 块中发现了错误。 But how can/should I test if the correct phrase has been printed?但是我如何/应该如何测试是否打印了正确的短语? This could especially be useful if you have more than one possible except block.如果你有一个以上的可能,这可能尤其是有用的except块。

You can use the capsys fixture to capture standard output and then make assertions with it:您可以使用capsys固定装置捕获标准输出,然后使用它进行断言:

def my_func(string):
    try:
        assert string == "pass"
        print("String is `pass`")
    except AssertionError:
        print("String is not 'pass'")



def test_my_func(capsys):
    my_func("fail")
    captured = capsys.readouterr()
    assert captured.out == "String is not 'pass'\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 pytest 测试 try/except 块并涵盖所有异常 - How to test try/except block with pytest and cover all exceptions 使用 Pytest 测试 Asyncio:如何通过 mocking 事件循环测试 try-except 块? - Testing Asyncio with Pytest: How to test a try-except block by mocking the event loop? 测试 Except 块,模拟 function 的返回是一个异常 python pytest - Test the Except Block, Mock the return of a function be an exception python pytest 单元测试期间未在try-except块中捕获异常 - Exception not being caught in try-except block during unit test Try and except 块不运行异常 - Try and except block not running the exception 如何在python pytest单元测试中覆盖try-except的除外部分 - How to cover the except portion of a try-except in a python pytest unit test Django / Python单元测试:如何强制Try / Except块的异常 - Django/Python unittesting: How to Force Exception of Try/Except Block 在Python中尝试除了块 - 如何理解异常在哪里? - Large try except block in Python - how to understand where was an exception? 如何在 unittest 中断言在 try except 块中捕获异常? - How to assertRaises in unittest an exception caught in try except block? 如何在try / except块中正确引发异常 - How to raise exception within a try/except block properly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM