Bash----
Bash----

Reputation: 95

Unittests for requests.post with no response

I am wanting to write a unittest for a very simple function that has no response.

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. Or the 200 status code to show that the request was a success.

However, in this case neither of these are possible due to no response being given from the function.

I want to mock a unittest for the requests.post method - assert_called_once_with. But I can't get this to work.

Any help I would be very grateful.

Thanks!

Upvotes: 1

Views: 661

Answers (1)

User051209
User051209

Reputation: 2568

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.

Upvotes: 1

Related Questions