断言失败

时间:2012-01-22 15:09:09

标签: python unit-testing python-requests

我正在尝试编写一个单元测试,以确保在必要时引发HTTPException。这是测试:

import unittest  
from requests import HTTPError
import pyport

 # Code omitted...
 def test_bad_item_type(self):
     """A bad item type should raise a HTTPError"""
     test_type = 'bad'
     test_id = 1986134
     self.assertRaises(HTTPError, pyport.get_item(test_type, test_id))

产生以下内容:

ERROR: test_bad_item_type (__main__.TestPyportFunctions) A bad item
type should raise requests.HTTPError
---------------------------------------------------------------------- 
Traceback (most   recent call last):   File "./tests.py", line 65, in
test_bad_item_type
    self.assertRaises(HTTPError, pyport.get_item(test_type, test_id))   File    "/home/sean/workspace/pyport/pyport.py", line 54, in get_item
    response.raise_for_status()   File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 741, fin raise_for_status
    raise HTTPError('%s Client Error' % self.status_code) HTTPError: 404 Client Error

引发了异常,但测试未捕获到异常。这类似于this question中发生的情况,但它并不完全相同。有人能告诉我我错过了什么吗?

2 个答案:

答案 0 :(得分:7)

应该是:

self.assertRaises(HTTPError, pyport.get_item, test_type, test_id)

查看assertRaises的签名:

assertRaises(exception, callable, *args, **kwds)

这是以这种方式定义的,因为如果按照自己的方式执行,Python解释器首先调用pyport.get_item(test_type, test_id),然后将其结果传递给assertRaises。结果是assertRaises根本没有被调用,并且没有捕获异常。现在,如果assertRaises可以访问函数及其参数,它可以调用函数本身并捕获相应的异常。

答案 1 :(得分:1)

如果您使用的是Python 2.7或更高版本,那么您使用的是backported unittest2模块而不是unittest,那么在使用assertRaises作为上下文管理器时,可以避免编写奇怪的语法:< / p>

with self.assertRaises(HTTPError):
    pyport.get_item(test_type, test_id)

http://docs.python.org/library/unittest.html#basic-example

相关问题