How to unit test a POST method in python?

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to unit test a POST method in python?



I have a method that sends a POST containing a JSON to an Elasticsearch instance. I am trying to write a unit test that verify the contents of the sent JSON, but I am not sure how to go about that. Should I create a local server in python and have it verify the contents of the POST or something else? I currently have this:


class TestAnalytics(BaseTest):

def test_post(self):
info = {"test1": "value1", "test2": "value2"}
resp = requests.post(config.tool_repo_urls['es_url'], data=json.dumps(info), headers={'Content-Type': 'application/json'})
assert_equal(resp.status_code, 200) # verify valid response code





Create a unit test to POST and check the result of the POST based on the returned value from the API and then run a GET to confirm the contents match what you POSTed?
– dfundako
42 mins ago




2 Answers
2



Creating a local server would be an overkill, what you can do is use unitest library to patch the post() method so it sends the data to your internal assertion method using patch method here is the link https://docs.python.org/3/library/unittest.mock-examples.html. You should look at section 27.6.2. Patch Decorators


post()



Example:


class TestAnalytics(BaseTest):

@patch('requests.post')
def test_post(self,mock_post):
info = {"test1": "value1", "test2": "value2"}
resp = requests.post(config.tool_repo_urls['es_url'], data=json.dumps(info), headers={'Content-Type': 'application/json'})
#Something like assert_equal(mock.assert_called_with,your_Expected_value )



If you want to verify the sent JSON you should try json.loads(), which will throw a ValueError if the input you pass can't be decoded as JSON.


json.loads()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

9ggaRtGh
zzvJNURZI zAj3L r SmMB,C 0MlW8xu sW2XUlc Tyt3h7hm2Qy4C8h1bjwC2NZ4sXlCh

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham