Python 如何用烧瓶测试和模拟mongodb?
我正在尝试对端点post进行测试,它将json格式的信息发送到mongo数据库 在这种情况下,如何执行单元测试?我如何模拟mongo来拥有一个临时数据库 下面是我的代码。请注意,如果我没有连接mongo,就会出现无法发送数据的错误,这是众所周知的。我的问题是,如何通过模仿mongo来执行此测试Python 如何用烧瓶测试和模拟mongodb?,python,mongodb,unit-testing,flask,testing,Python,Mongodb,Unit Testing,Flask,Testing,我正在尝试对端点post进行测试,它将json格式的信息发送到mongo数据库 在这种情况下,如何执行单元测试?我如何模拟mongo来拥有一个临时数据库 下面是我的代码。请注意,如果我没有连接mongo,就会出现无法发送数据的错误,这是众所周知的。我的问题是,如何通过模仿mongo来执行此测试 import json import unittest from api import app app.testing = True # set our application to testing
import json
import unittest
from api import app
app.testing = True # set our application to testing mode
class TestApi(unittest.TestCase):
with app.test_client() as client:
# send data as POST form to endpoint
sent = {
"test1": 1,
"test2": 1,
"test3": 1
}
mimetype = 'application/json'
headers = {
'Content-Type': mimetype,
}
#fixtures
result = client.post(
'/post/',
data=json.dumps(sent), headers=headers, environ_base={'REMOTE_ADDR': 'locahost'})
def test_check_result_server_have_expected_data(self):
# check result from server with expected data
self.assertEqual(self.result.json, self.sent)
def test_check_content_equals_json(self):
# check content_type == 'application/json'
self.assertEqual(self.result.content_type, self.mimetype)
if __name__ == "__main__":
unittest.main()
我的api以这种方式调用mongo:
@api.route('/post/')
class posting(Resource):
@api.doc(responses={200: 'Success', 500: 'Internal Server Error', 400: 'Bad Request'})
@api.doc(body=fields, description="Uploads data")
@api.expect(fields, validate=True)
def post(self):
try:
mongodb_helper.insert_metric(name="ODD", timestamp=request.json["timestamp"],
metric_type="field1", value=request.json["field1"])
return ("Data saved successfully", 201)
except:
return ("Could not create new data", 500)
谢谢,这里有一个使用
unittest.mock.mock
和补丁
上下文管理器的示例。当然,您需要将“\uuuuu main\uuu.insert\u metric”
替换为更合适的内容
import unittest.mock
# Function to be mocked
def insert_metric(**kwargs):
raise ValueError("this should never get called")
# Function to be tested
def post(data):
insert_metric(
name="ODD", timestamp=data["timestamp"], metric_type="field1", value=data["field1"]
)
# Test case
def test_post():
insert_metric_mock = unittest.mock.MagicMock()
with unittest.mock.patch("__main__.insert_metric", insert_metric_mock):
post({"timestamp": 8, "field1": 9})
print(insert_metric_mock.mock_calls) # for debugging
insert_metric_mock.assert_called_with(
name="ODD", timestamp=8, metric_type="field1", value=9
)
if __name__ == "__main__":
test_post()
这是打印出来的
[call(metric_type='field1', name='ODD', timestamp=8, value=9)]
并且不会引发断言错误。您的应用程序如何连接到MongoDB数据库?在测试时,您必须对其进行检测,以连接到临时数据库。(或者,如果您根本不想将数据保存到数据库中,您可以模拟MongoDB层,不管您如何实现它。)确切地说,我需要模拟MongoDB层。但我的问题是,如何做到这一点?就像模拟任何模块或函数一样–因为您使用的是
unittest
,可能是unittest.patch
中的补丁程序:抱歉,但我还是不明白。由于我的API只向mongo发送数据,我将如何为mongo制作补丁?我用API代码更新了上面的代码。