如何在Python / Django中测试引发的异常?

时间:2019-12-19 13:50:53

标签: python django unit-testing exception

我有一个Django项目,其中有一个要测试的功能。简化后,该函数如下所示:

class InvalidUrlError(Exception):
    pass

def get_info_from_url(url):
    try:
        return url.split(':')[1].split('/')[0]
    except Exception:
        raise InvalidUrlError(f"Invalid url: {url}")

我的测试如下:

class ToolsTestCase(TestCase):
    def test_get_info_from_url_wrong_formatted_url(self):
        self.assertRaises(InvalidUrlError, get_info_from_url("https://acc.images.data.ourcompany.com/"))

虽然运行它,但得到以下输出:

$ ./manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....E
======================================================================
ERROR: test_get_info_from_url_wrong_formatted_url (checker.tests.ToolsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/kramer65/repos/auth-proxy/app/checker/tools.py", line 10, in get_info_from_url
    return url.split(':')[1].split('/')[0]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/kramer65/repos/auth-proxy/app/checker/tests.py", line 57, in test_get_info_from_url_wrong_formatted_url
    self.assertRaises(InvalidUrlError, get_info_from_url("https://acc.images.data.ourcompany.com/"))
  File "/home/kramer65/repos/auth-proxy/app/checker/tools.py", line 15, in get_info_from_url
    raise InvalidUrlError(f"Invalid url: {url}")
checker.tools.InvalidUrlError: Invalid url: https://acc.images.data.ourcompany.com/

----------------------------------------------------------------------
Ran 5 tests in 0.037s

FAILED (errors=1)
Destroying test database for alias 'default'...

为什么它引发异常,而不是通过测试?我认为我在另一项测试中做了类似的事情,效果很好。

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:4)

您需要传递可调用对象,而不是调用函数本身。 Unittest docs for assertRaises

因此将其更改为:

class ToolsTestCase(TestCase):
    def test_get_info_from_url_wrong_formatted_url(self):
        self.assertRaises(InvalidUrlError, get_info_from_url, "https://acc.images.data.ourcompany.com/")

其他选择是使用assertRaises作为上下文管理器,如下所示:

class ToolsTestCase(TestCase):
    def test_get_info_from_url_wrong_formatted_url(self):
        with self.assertRaises(InvalidUrlError):
            get_info_from_url("https://acc.images.data.ourcompany.com/")