Search code examples
mongodbmockingpymongopython-unittestpython-unittest.mock

How to mock mongodb with unites Flask


I want to mock mongo in order to make some unit test with unittest for Flask. The doc about this is so huge and I don't really understand how to make it.

I want to test a POST method with the following data:

from unittest import TestCase, main as unittest_main, mock
from bson.objectid import ObjectId
from app import app


sample_user = {
    'Id': ObjectId('5d55cffc4a3d4031f42827a3'),
    'Username': 'LeTest',
    'Mail': '[email protected]',
    'password': 'test123',
    'Qrcode': 'TODO'
}

Can you explain me how I can test if the sample_user where added to my mongo collection ? Thx !


Solution

  • I found the answer:

    Here you have my code in order to mock mongoDB Data with Flask

        def test_post_food(self):
        # Mock the food value in ./api.food.py
        with unittest.mock.patch('api.food.food') as MockFood:
            # Force the return value of food.insert_one(json) to sample_food
            MockFood.insert_one.return_value = sample_food
            with self.client.post("/api/addFood", json=sample_food[0]) as res:
                # Check if food.insert_one(json) was called
                MockFood.insert_one.assert_called()
                self.assertEqual(res.status_code, 200)
                self.assertEqual(res.data, b'{"Response":"Food was added"}\n')
    
    
    sample_food = [{
    "_id": {
        "$oid": "619e8f45ee462d6d876bbdbc"
    },
    'Utilisateur': "999",
    'Nom': 'Danette Vanille',
    'Marque': 'Danone',
    'Quantite': 4,
    'ingredients': [
        'lait entier',
        'lait écrémé reconstitué à base de lait en poudre',
        'sucre',
        'crème',
        'lait écrémé concentré ou en poudre',
        'épaississants (amidon modifié, carraghénanes)',
        'perméat de petit lait (lactosérum) en poudre',
        'amidon',
        'arôme (lait)',
        'colorant (bêta-carotène)'
    ],
    'Date': '20/12/2021',
    'Valeurs': {
        'Energie': '107 kcal',
        'Matières grasses': '3,0g',
        'Glucides': '17,1g',
        'Proteines': '3g',
        'Sel': '0,14g'
    },
    'Poids': '125g',
    'Lieu': 'Frigo',
    'Category': "Produit laitiers"
    

    }]