簡體   English   中英

如何用flask測試和模擬mongodb?

[英]How to test and mock mongodb with flask?

我正在嘗試對端點帖子進行測試,它將 json 中的信息發送到 mongo 數據庫。

在這種情況下如何執行單元測試? 我怎樣才能模擬 mongo 擁有一個瞬時數據庫?

下面是我的代碼。 請注意,如果我沒有連接 mongo,我會收到無法發送數據的錯誤,這是臭名昭著的。 我的問題是,如何通過模擬 mongo 來執行此測試?

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.Mockpatch上下文管理器的示例。 您當然需要用更合適的東西替換"__main__.insert_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)]

並且不會引發斷言錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM