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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With