[英]Python requests.post() returns <Response [406]>
[英]Unittests for requests.post with no response
我想为一个没有响应的非常简单的 function 编写单元测试。
def post_this(url, data, headers):
requests.post(url, json=data, headers=headers)
通常我会使用 response = expected response 为这样的事情编写单元测试。 或者 200 状态码表示请求成功。
但是,在这种情况下,由于 function 没有给出任何响应,因此这两种情况都不可行。
我想模拟 requests.post 方法的单元测试 - assert_called_once_with。 但我无法让它发挥作用。
任何帮助我将不胜感激。
谢谢!
如果我理解了这个问题,我想下面的代码可能是它的答案:
import unittest
from unittest.mock import patch
import requests
def post_this(url, data, headers):
requests.post(url, json=data, headers=headers)
class MyTestCase(unittest.TestCase):
def test_post(self):
with patch('requests.post') as mock_post:
post_this('some_url', 'some_data', 'some_headers')
mock_post.assert_called_once_with('some_url', json='some_data', headers='some_headers')
if __name__ == '__main__':
unittest.main()
正如您在代码中看到的那样,在模拟 object 上使用requests.post
和assert_called_once_with()
的patch
(如您在问题中所建议的那样)就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.