Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Suite in Flask with MongoEngine

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.

like image 984
Darwin Tech Avatar asked May 14 '13 22:05

Darwin Tech


1 Answers

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.

like image 196
computmaxer Avatar answered Nov 14 '22 21:11

computmaxer