仅通过状态代码模拟了请求抛出错误
我正在编写一些单元测试,在其中嘲笑向另一个服务的请求。这是我正在测试的方法。
def ping_camera(self, camera):
retry_ping = Retry(
total=3,
status_forcelist=[404, 429, 500, 502, 503, 504],
method_whitelist=["GET"],
backoff_factor=1,
)
adapter = HTTPAdapter(max_retries=retry_ping)
http = requests.Session()
http.mount("http://", adapter)
try:
response = http.get("http://{}".format(camera.ip_address), timeout=3)
response.raise_for_status()
except Exception as e:
camera.camera_status = False
camera.save()
else:
camera.camera_status = True
camera.save()
这是我的测试之一。
@patch.object(Session, "get")
def test_expects_true_camera_status_to_return_false_status(self, mock):
# Arrange
mock.side_effect = Exception
# Act
check_cams = CheckCameras()
check_cams.ping_camera(self.camera)
# Assert
self.assertFalse(self.camera.camera_status)
请注意,为了有例外,我需要添加mock.side_effect =异常
。我来自Laravel世界,其中只需要指定响应状态,如果返回不良的响应,将提出例外。
我什至可以指定一个良好的响应,并且仍然触发了这样的例外,所以
mock.return_value.status_code = 200
mock.side_effect = Exception
这只是一个python测试的怪癖,还是我可以单独根据响应状态代码提出例外?
这意味着如果我添加mock.return_value.status_code = 500
我将获得一个异常,并点击我代码块的部分。
I'm writing some unit tests where I mock out requests to another service. Here's the method I'm testing.
def ping_camera(self, camera):
retry_ping = Retry(
total=3,
status_forcelist=[404, 429, 500, 502, 503, 504],
method_whitelist=["GET"],
backoff_factor=1,
)
adapter = HTTPAdapter(max_retries=retry_ping)
http = requests.Session()
http.mount("http://", adapter)
try:
response = http.get("http://{}".format(camera.ip_address), timeout=3)
response.raise_for_status()
except Exception as e:
camera.camera_status = False
camera.save()
else:
camera.camera_status = True
camera.save()
And here's one of my tests.
@patch.object(Session, "get")
def test_expects_true_camera_status_to_return_false_status(self, mock):
# Arrange
mock.side_effect = Exception
# Act
check_cams = CheckCameras()
check_cams.ping_camera(self.camera)
# Assert
self.assertFalse(self.camera.camera_status)
Note that in order to have an exception raised, I need to add mock.side_effect = Exception
. I come from the Laravel world where only the response status needs to be specified and if a bad response is returned, an exception will be raised.
I can even specify a good response, and still trigger an exception like so
mock.return_value.status_code = 200
mock.side_effect = Exception
Is this just a quirk of a Python testing, or can I have exceptions raised based off the response status code alone?
Meaning if I add mock.return_value.status_code = 500
I'll get an exception raised and hit the except
portion of my code block.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论