[Django]-Testing django with mongoengine

1๐Ÿ‘

1. Define custom DiscoverRunner for NoSQLTests

For example in yourapp/tests.py

from django.test.runner import DiscoverRunner

class NoSQLTestRunner(DiscoverRunner):
    def setup_databases(self, **kwargs):
        pass
    def teardown_databases(self, old_config, **kwargs):
        pass

2. Define custom TestCase class for NoSQLTests.

For example in yourapp/tests.py

from django.test import TestCase

class NoSQLTestCase(TestCase):
    def _fixture_setup(self):
        pass
    def _fixture_teardown(self):
        pass

3. Change default TEST_RUNNER in your settings.py

TEST_RUNNER = 'yourapp.tests.NoSQLTestRunner'

4. Write tests

Tests that not require database:

class YourTest(NoSQLTestCase):

    def test_foo(self):
        to_compare = 'foo'
        assumed = 'foo'
        self.assertEqual(to_compare, assumed)

Tests that require database, use mocking:

https://docs.mongoengine.org/guide/mongomock.html

Step by step

  1. Install mongomock pip install mongomock
  2. Write test:
from mongoengine import connect, disconnect, Document, StringField

class Foo(Document):
    content = StringField()

class TestFoo(NoSQLTestCase):

    @classmethod
    def setUpClass(cls):
        connect('mongoenginetest', host='mongomock://localhost', alias='testdb')

    @classmethod
    def tearDownClass(cls):
       disconnect(alias='testdb)

    def test_thing(self):
        foo = Foo(content='bar')
        foo.save()

        fresh_foo = Foo.objects().first()
        assert fresh_foo.content ==  'bar'
๐Ÿ‘คViljami

-2๐Ÿ‘

Testing of django while using mongodb can be done by creating a custom testcase in which setUp function connects to the mongodb using mongoengine and tearDown will drop the testing database and disconnects.

from django.test import TestCase
import mongoengine

class MongoTestCase(TestCase):
    def setUp(self):
        mongoengine.connection.disconnect()
        mongoengine.connect(
            host=settings.MONGO['host'],
            port=settings.MONGO['port'],
            db=settings.MONGO['db'],
            username=settings.MONGO['username'],
            password=settings.MONGO['password']
           )
        super().setUpClass()

    def tearDown(self):
        from mongoengine.connection import get_connection, disconnect
        connection = get_connection()
        connection.drop_database(settings.MONGO['db'])
        disconnect()
        super().tearDownClass()

Then you can use this test case in your tests. For ex assuming we have a model named โ€˜Appโ€™

from models import App

class AppCreationTest(MongoTestCase):
  def test(self):
    app = App(name="first_app")
    app.save()
    assert App.objects.first().name == app.name

You can run these tests by python manage.py test

Here is a small gist for your reference

๐Ÿ‘คhulksmash

Leave a comment