django unit tests without a db

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

    Updated: also see this answer for using a third-party tool pytest.


    @Cesar is right. After accidentally running ./manage.py test --settings=no_db_settings, without specifying an app name, my development database was wiped out.

    For a safer manner, use the same NoDbTestRunner, but in conjunction with the following mysite/no_db_settings.py:

    from mysite.settings import *
    
    # Test runner with no database creation
    TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'
    
    # Use an alternative database as a safeguard against accidents
    DATABASES['default']['NAME'] = '_test_mysite_db'
    

    You need to create a database called _test_mysite_db using an external database tool. Then run the following command to create the corresponding tables:

    ./manage.py syncdb --settings=mysite.no_db_settings
    

    If you're using South, also run the following command:

    ./manage.py migrate --settings=mysite.no_db_settings
    

    OK!

    You can now run unit tests blazingly fast (and safe) by:

    ./manage.py test myapp --settings=mysite.no_db_settings
    

提交回复
热议问题