mongoengine connect() in settings.py testing problem

后端 未结 4 557
忘掉有多难
忘掉有多难 2021-02-06 04:29

I want to be able to do conditional connect() based on either I started django in testing mode or not.

in my settings.py I use mongoengine connect() method to connect to

4条回答
  •  忘了有多久
    2021-02-06 05:22

    I'm solving this with a custom test runner. Here is an example I based my solution off of: https://github.com/xintron/django-mongorunner/blob/master/mongorunner/testrunner.py

    This has the advantage of providing a fresh database for each of your unit tests.

    class MyTestRunner(DjangoTestSuiteRunner):
    
        mongodb_name = 'testsuite'
    
        def setup_databases(self, **kwargs):
            from mongoengine.connection import connect, disconnect
            disconnect()
            connect(self.mongodb_name)
            print 'Creating mongo test-database ' + self.mongodb_name
            return super(MyTestRunner, self).setup_databases(**kwargs)
    
        def teardown_databases(self, old_config, **kwargs):
            from mongoengine.connection import get_connection, disconnect
            connection = get_connection()
            connection.drop_database(self.mongodb_name)
            print 'Dropping mongo test-database: ' + self.mongodb_name
            disconnect()
            super(MyTestRunner, self).teardown_databases(old_config, **kwargs)
    

提交回复
热议问题