如何在python中对POST方法进行单元测试? [英] How to unit test a POST method in python?
问题描述
我有一个将包含JSON的POST发送到Elasticsearch实例的方法.我正在尝试编写一个单元测试,以验证发送的JSON的内容,但是我不确定该怎么做.我应该在python中创建本地服务器并让其验证POST或其他内容吗?我目前有这个:
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
推荐答案
创建本地服务器是一个过大的杀伤力,您可以做的是使用unitest库修补post()
方法,以便将数据发送到内部断言使用补丁方法的方法是链接 https://docs.python. org/3/library/unittest.mock-examples.html .您应该查看 27.6.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
示例:
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
下面的完整示例
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()
方法assert_called_with
检查是否使用在调用中指定的参数精确地调用了修补的方法.在这种情况下,它为True
Method assert_called_with
checks if the patched method was called exactly with the parameters specified in its invocation. In this case it is True
将其更改为例如
mock_post.assert_called_with("www.someurl.com", data=json.dumps(info))
会给:
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'})
您还可以使用mock_post
对象检查单个参数,请查看上面的链接,以获取MagicMock
可以做什么的完整规格
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
EDIT2
最近发现了这个用于单元测试的小库requests
Recently found out about this little library for unit testing requests
https://github.com/getsentry/responses
这篇关于如何在python中对POST方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!