lundi 16 novembre 2020

How to test and mock mongodb with flask?

I'm trying to do a test of an endpoint post, which sends information in json to a mongo database.

How do I perform a unit test in this case? How can I mock mongo to have a momentary database?

Below is my code. Note that if I don't have the mongo connected, I get the error that it was not possible to send the data, which is notorious. My question is, how can I perform this test by mocking the 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()

Thanks,

Aucun commentaire:

Enregistrer un commentaire