Created
January 5, 2020 15:42
-
-
Save Saigesp/bb5ec006c1c6a8743202b3c3041c7d61 to your computer and use it in GitHub Desktop.
Custom TestRunner and APITestCase to work with django, mongodb and django rest framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.test.runner import DiscoverRunner | |
from django.conf import settings | |
from mongoengine import connect, disconnect, get_connection | |
from pymongo import MongoClient | |
from rest_framework.test import APITestCase | |
class TestRunner(DiscoverRunner): | |
""" | |
Custom test runner for mongoengine | |
""" | |
def setup_databases(self, **kwargs): | |
db_name = settings.TEST_DBNAME | |
disconnect() | |
connect(db_name) | |
print('Connecting to test database: ' + db_name) | |
return db_name | |
def teardown_databases(self, db_name, **kwargs): | |
if not self.keepdb: | |
conn = MongoClient() | |
conn.drop_database(db_name) | |
print('Dropping test database: ' + db_name) | |
class MongoTestCase(APITestCase): | |
""" | |
Custom APITestCase that clear the database between the tests | |
""" | |
db_name = settings.TEST_DBNAME | |
def _pre_setup(self): | |
disconnect() | |
connect(self.db_name) | |
super(MongoTestCase, self)._pre_setup() | |
def _post_teardown(self): | |
connection = get_connection() | |
connection.drop_database(self.db_name) | |
disconnect() | |
super(MongoTestCase, self)._post_teardown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment