一个api模拟工具
PyMoq的Python项目详细描述
pymoq是模拟http服务的工具。
安装
pip install PyMoq
用法
默认情况下,Pymoq运行在8080 TCP端口上,可以对其进行更改:
mock = pymoq.Mock(port=8090)
存根可以通过设置路径和http方法创建(get是默认设置)。
mock.create_stub('/books', method='post')
可以将路径设置为regex。
mock.create_stub('/books/[0-9]+', method='put')
对于每个存根,可以使用头和http状态代码配置响应。 标题必须是以标题名为关键字的字典。
mock.create_stub('/books', method='post').response('...', headers={'name': 'value'}, http_status=201)
示例测试
import unittest import requests from pymoq import pymoq class ExampleUsageTestCase(unittest.TestCase): def test_direct_usage(self): content = '{"author": "John Doe", "title": "Lorem ipsum dolor sit amet", "id": 1}' headers = { 'content-type': 'application/json; charset=utf-8', 'location': 'http://localhost:8090/books/1' } mock = pymoq.Mock(port=8090) mock.create_stub('/books', method='post').response(content, headers=headers, http_status=201) with mock.run(): response = requests.post('http://localhost:8090/books', data={"author": "John Doe", "title": "Lorem ipsum dolor sit amet"}) self.assertEqual(response.status_code, 201) self.assertEqual(response.headers['content-type'], 'application/json; charset=utf-8') self.assertEqual(response.headers['location'], 'http://localhost:8090/books/1') self.assertEqual(response.text, content)
使用json文件配置
mock可以用json文件配置。文件应该如下所示:
[{ "request": { "url": "/books", "method": "post" }, "response": { "content": {"author": "John Doe", "title": "Lorem ipsum dolor sit amet", "id": 1}, "headers": { "content-type": "application/json; charset=utf-8", "location": "http://localhost:8080/books/1" }, "httpStatus": 201 } }]
示例测试
import unittest import requests from pymoq import pymoq class JsonConfigTestCase(unittest.TestCase): def test_load_config_from_file(self): mock = pymoq.Mock() mock.load('config.json') with mock.run(): response = requests.post('http://localhost:8080/books', data={"author": "John Doe", "title": "Lorem ipsum dolor sit amet"}) self.assertEqual(response.status_code, 201) self.assertEqual(response.headers['content-type'], 'application/json; charset=utf-8') self.assertEqual(response.headers['location'], 'http://localhost:8080/books/1') content = response.json() self.assertEqual(content['author'], 'John Doe') self.assertEqual(content['title'], 'Lorem ipsum dolor sit amet') self.assertEqual(content['id'], 1)
请求验证
pymoq可用于验证请求。
示例测试
import unittest import requests from pymoq import pymoq class RequestVerificationTestCase(unittest.TestCase): def test_request(self): mock = pymoq.Mock() stub = mock.create_stub('/books', method='post') with mock.run(): requests.post('http://localhost:8080/books', json={'firstName': 'John', 'lastName': 'Doe'} headers={'content-type': 'application/json'}) stub.assert_requested_once() stub.assert_requested_with_header('content-type', 'application/json') stub.assert_requested_body_contains('Doe')