简体   繁体   English

使用side_effect与mock时未调用异常

[英]Exception not called when using side_effect with mock

I have a function in a class called "my_class" in a module called "my_module" that contains this snippet: 我在名为“my_module”的模块中有一个名为“my_class”的类中的函数,该模块包含以下代码段:

try:
  response = self.make_request_response(requests.post, data, endpoint_path)
except requests.exceptions.HTTPError as err:
  if err.response.status_code == requests.codes.conflict:
    logging.info('Conflict error')

And I'm trying to test it like so: 而我正试图像这样测试它:

error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found')
mock_bad = mock.Mock(side_effect=error)
mock_good = mock.Mock()
mock_good.return_value = [{'name': 'foo', 'id': 1}]


upsert = my_module.my_class(some_data)
with mock.patch.object(upsert, 'make_request_response', side_effect=[mock_bad, mock_good]) as mock_response:
    some_function()

What I would expect is for an HTTPError to be raised in the test after I patch it. 我期望的是在我修补它之后在测试中引发HTTPError。 However, when I run the test, an exception is never raised. 但是,当我运行测试时,永远不会引发异常。 "response" is actually set to mock_bad, which contains the desired exception, although it's never raised. “response”实际上设置为mock_bad,它包含所需的异常,尽管它从未被引发过。 Any idea where I'm going wrong here? 知道我哪里错了吗?

You put your exception into the wrong side effect. 你把你的例外置于错误的副作用。 Calling make_request_response() now first returns the mock_bad mock, which by itself won't raise that exception until called. 现在调用make_request_response()首先返回mock_bad模拟,它在调用之前不会引发该异常。

Put the exception in the mock.patch.object() side_effect list: 将异常放在mock.patch.object() side_effect列表中:

error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found')
mock_good = mock.Mock()
mock_good.return_value = [{'name': 'foo', 'id': 1}]


upsert = my_module.my_class(some_data)
with mock.patch.object(upsert, 'make_request_response', side_effect=[error, mock_good]) as mock_response:
    some_function()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM