我正在开发一个项目,涉及连接到远程服务器,等待响应,然后根据该响应执行操作.我们抓住了几个不同的例外,并根据捕获的异常行为不同.例如:
def myMethod(address, timeout=20):
try:
response = requests.head(address, timeout=timeout)
except requests.exceptions.Timeout:
# do something special
except requests.exceptions.ConnectionError:
# do something special
except requests.exceptions.HTTPError:
# do something special
else:
if response.status_code != requests.codes.ok:
# do something special
return successfulConnection.SUCCESS
为了测试这个,我们写了一个如下的测试
class TestMyMethod(unittest.TestCase):
def test_good_connection(self):
config = {
'head.return_value': type('MockResponse', (), {'status_code': requests.codes.ok}),
'codes.ok': requests.codes.ok
}
with mock.patch('path.to.my.package.requests', **config):
self.assertEqual(
mypackage.myMethod('some_address',
mypackage.successfulConnection.SUCCESS
)
def test_bad_connection(self):
config = {
'head.side_effect': requests.exceptions.ConnectionError,
'requests.exceptions.ConnectionError': requests.exceptions.ConnectionError
}
with mock.patch('path.to.my.package.requests', **config):
self.assertEqual(
mypackage.myMethod('some_address',
mypackage.successfulConnection.FAILURE
)
如果我直接运行函数,一切都会如预期的那样发生.我甚至通过将try request.exceptions.ConnectionError添加到函数的try子句来测试.但是当我运行单元测试时,我得到了
ERROR: test_bad_connection (test.test_file.TestMyMethod)
----------------------------------------------------------------
Traceback (most recent call last):
File "path/to/sourcefile", line ###, in myMethod
respone = requests.head(address, timeout=timeout)
File "path/to/unittest/mock", line 846, in __call__
return _mock_self.mock_call(*args, **kwargs)
File "path/to/unittest/mock", line 901, in _mock_call
raise effect
my.package.requests.exceptions.ConnectionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Path/to/my/test", line ##, in test_bad_connection
mypackage.myMethod('some_address',
File "Path/to/package", line ##, in myMethod
except requests.exceptions.ConnectionError:
TypeError: catching classes that do not inherit from BaseException is not allowed
我试图改变我正在修补BaseException异常我有一个或多或少相同的错误.
我已经读了https://stackoverflow.com/a/18163759/3076272,所以我认为这是一个坏的__del__钩子,但我不知道在哪里寻找它,甚至可以在同一时间做甚么.我也是unittest.mock.patch()的新手,所以很有可能我也在做错事.
这是一个Fusion360加载项,所以它使用Fusion 360的Python 3.3的封装版本 – 据我所知,这是一个香草版本(即他们不会自己滚动),但我并不乐观.