django unit tests without a db

前端 未结 11 1513
醉梦人生
醉梦人生 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

    When using the nose test runner (django-nose), you can do something like this:

    my_project/lib/nodb_test_runner.py:

    from django_nose import NoseTestSuiteRunner
    
    
    class NoDbTestRunner(NoseTestSuiteRunner):
        """
        A test runner to test without database creation/deletion
        Used for integration tests
        """
        def setup_databases(self, **kwargs):
            pass
    
        def teardown_databases(self, old_config, **kwargs):
            pass
    

    In your settings.py you can specify the test runner there, i.e.

    TEST_RUNNER = 'lib.nodb_test_runner.NoDbTestRunner' . # Was 'django_nose.NoseTestSuiteRunner'

    OR

    I wanted it for running specific tests only, so I run it like so:

    python manage.py test integration_tests/integration_*  --noinput --testrunner=lib.nodb_test_runner.NoDbTestRunner
    

提交回复
热议问题