python baseexception_python – 不能捕获嘲讽的异常,因为它不会继承BaseException

我正在开发一个项目,涉及连接到远程服务器,等待响应,然后根据该响应执行操作.我们抓住了几个不同的例外,并根据捕获的异常行为不同.例如:

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的封装版本 – 据我所知,这是一个香草版本(即他们不会自己滚动),但我并不乐观.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值