简体   繁体   English

如何在python中对POST方法进行单元测试?

[英]How to unit test a POST method in python?

I have a method that sends a POST containing a JSON to an Elasticsearch instance. 我有一个将包含JSON的POST发送到Elasticsearch实例的方法。 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. 我正在尝试编写一个单元测试来验证发送的JSON的内容,但是我不确定该如何进行。 Should I create a local server in python and have it verify the contents of the POST or something else? 我应该在python中创建本地服务器并让其验证POST或其他内容吗? 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

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 . 创建本地服务器将是一个过大的杀伤力,您可以做的是使用unitest库修补post()方法,以便它使用修补方法将数据发送到内部断言方法,这里是链接https://docs.python.org /3/library/unittest.mock-examples.html You should look at section 27.6.2. 您应该查看第27.6.2 Patch Decorators 贴片装饰器

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'})
        #Some checks done on mock_post object

Full working example below EDIT: 下面的完整工作示例为EDIT:

import json

from unittest import TestCase
from unittest.mock import patch

import requests


class TestAnalytics(TestCase):

    @patch('requests.post')
    def test_post(self, mock_post):
        info = {"test1": "value1", "test2": "value2"}
        resp = requests.post("www.someurl.com", data=json.dumps(info), headers={'Content-Type': 'application/json'})
        mock_post.assert_called_with("www.someurl.com", data=json.dumps(info), headers={'Content-Type': 'application/json'})


TestAnalytics().test_post()

Method assert_called_with checks if the patched method was called exactly with the parameters specified in its invocation. 方法assert_called_with检查是否使用调用中指定的参数精确调用了打补丁的方法。 In this case it is True 在这种情况下,它是True

Changing it to for example: 更改为例如:

mock_post.assert_called_with("www.someurl.com", data=json.dumps(info))

Will give: 会给:

AssertionError: Expected call: post('www.someurl.com', data='{"test1": "value1", "test2": "value2"}')
Actual call: post('www.someurl.com', data='{"test1": "value1", "test2": "value2"}', headers={'Content-Type': 'application/json'})

You can also use the mock_post object to check indvidiual parametrs please check the link above for the full specs of what MagicMock can do 您还可以使用mock_post对象检查单个参数,请查看上面的链接以了解MagicMock可以做什么的完整规格

EDIT2 EDIT2

Recently found out about this little library for unit testing requests 最近发现了单元测试的这个小程序requests

https://github.com/getsentry/responses https://github.com/getsentry/responses

如果要验证发送的JSON,则应尝试json.loads() ,如果您传递的输入不能被解码为JSON,则会抛出ValueError。

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

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