Test Suite in Flask with MongoEngine
Asked Answered
S

1

5

I have a small app in Flask which I want to accompany with tests. I have used Django tests before, and I'm just getting to grips with the lower level functionality in Flask.

My tests currently look like this:

import unittest
from config import app
from mongoengine import connect
from my_app.models import User

class TestCase(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        app.config["MONGODB_DB"] = 'xxx'
        connect(
            'xxx',
            username='heroku',
            password='xxx',
            host='xxx',
            port=xxx
        )
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_create_user(self):
        u = User(username='john', email='[email protected]')
        u.save()

I know that this is wrong, because the test passes but I have added an entry into the database. How should I test the creation of a User without polluting the database? I had assumed that app.config['TESTING'] had some significance here.

Stimulant answered 14/5, 2013 at 22:53 Comment(0)
E
9

There are two approaches I know of:

1. Separate Test Database

This is something that Django does automatically for unittesting. It simply uses a separate database for testing that it clears before and after every test run. You could implement something like this manually.

2. Use Mocking to avoid actually using the database

This is the more preferred method for most situations. You use mocking to simulate various functions so that the tests don't actually create/edit/delete information in a real database. This is better for multiple reasons, most notably for performance/speed of your unit tests.

Enrique answered 15/5, 2013 at 4:23 Comment(3)
Great. I was coming to this conclusion - I have been used to Djago providing the 'magic'. Are there any good mocking libraries out there for Flask?Stimulant
You can use any python mock library (for example mock), but for database better find some package thats already mocking mongoengine or pymongo. Look at another question: https://mcmap.net/q/703510/-use-mock-mongodb-server-for-unit-test.Ludly
Mocking a better solution? You must be joking. Mocking is fantastic to avoid API calls, speed up testing (single-layer testing) and tons of stuff, but using it to avoid creating stuff in the DB is like test-driving a car without sitting on it. No. Solution 1 the right one in this case.Torture

© 2022 - 2024 — McMap. All rights reserved.