在Python3中,如何在单元测试中测试异常处理?

jjw*_*ign 3 python python-3.x

我正在为 api 进行几个单元测试。测试使用 @patch 来模拟 api 调用。我希望创建的一些测试应该会触发异常。我如何在单元测试中处理这个问题?

这是我到目前为止所拥有的。Pylint 抱怨 assertTrue() 语句。我确信有更好的方法来处理异常。

@patch('myapi.myapi.requests.request')
def test_auth_failure(self, mock_request):
    # Configure the request mock to return an auth failure
    # Auth/login (/session) failures return status 200, but without a token!
    mock_request.return_value.status_code = 200
    mock_request.return_value.content = json.dumps(self.mock_auth_failure)
    try:
        # Call auth()
        self.api.auth()
        # Exception should have been raised
        self.assertTrue(False)
    except exceptions.HTTPUnauthorized:
        # Exception caught
        self.assertTrue(True)
Run Code Online (Sandbox Code Playgroud)

附加信息:这是从unittest.TestCase 扩展的类中。例子:

 class MyApiTests(unittest.TestCase):
Run Code Online (Sandbox Code Playgroud)

jxr*_*mos 6

如果你使用 pytest 有这样的功能......

import pytest


def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0
Run Code Online (Sandbox Code Playgroud)

https://docs.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions