简体   繁体   English

requests.post 的单元测试没有响应

[英]Unittests for requests.post with no response

I am wanting to write a unittest for a very simple function that has no response.我想为一个没有响应的非常简单的 function 编写单元测试。

def post_this(url, data, headers):
    requests.post(url, json=data, headers=headers)

Normally I would write unittests for something like this using the response = expected response.通常我会使用 response = expected response 为这样的事情编写单元测试。 Or the 200 status code to show that the request was a success.或者 200 状态码表示请求成功。

However, in this case neither of these are possible due to no response being given from the function.但是,在这种情况下,由于 function 没有给出任何响应,因此这两种情况都不可行。

I want to mock a unittest for the requests.post method - assert_called_once_with.我想模拟 requests.post 方法的单元测试 - assert_called_once_with。 But I can't get this to work.但我无法让它发挥作用。

Any help I would be very grateful.任何帮助我将不胜感激。

Thanks!谢谢!

If I have understood the question, I suppose that the following code could be an answer to it:如果我理解了这个问题,我想下面的代码可能是它的答案:

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()

As you can see in the code it is enough to use patch for requests.post and assert_called_once_with() (as you suggest in your question) on the mock object.正如您在代码中看到的那样,在模拟 object 上使用requests.postassert_called_once_with()patch (如您在问题中所建议的那样)就足够了。

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

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