django unit tests without a db

前端 未结 11 1506
醉梦人生
醉梦人生 2020-11-29 16:11

Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn\'t require the db to set up. And while it is fast to setu

11条回答
  •  长情又很酷
    2020-11-29 16:53

    You can subclass DjangoTestSuiteRunner and override setup_databases and teardown_databases methods to pass.

    Create a new settings file and set TEST_RUNNER to the new class you just created. Then when you're running your test, specify your new settings file with --settings flag.

    Here is what I did:

    Create a custom test suit runner similar to this:

    from django.test.simple import DjangoTestSuiteRunner
    
    class NoDbTestRunner(DjangoTestSuiteRunner):
      """ A test runner to test without database creation """
    
      def setup_databases(self, **kwargs):
        """ Override the database creation defined in parent class """
        pass
    
      def teardown_databases(self, old_config, **kwargs):
        """ Override the database teardown defined in parent class """
        pass
    

    Create a custom settings:

    from mysite.settings import *
    
    # Test runner with no database creation
    TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'
    

    When you're running your tests, run it like the following with --settings flag set to your new settings file:

    python manage.py test myapp --settings='no_db_settings'
    

    UPDATE: April/2018

    Since Django 1.8, the module django.test.simple.DjangoTestSuiteRunner were moved to 'django.test.runner.DiscoverRunner'.

    For more info check official doc section about custom test runners.

提交回复
热议问题