Models inside tests - Django 1.7 issue

让人想犯罪 __ 提交于 2019-12-04 23:32:02

There is a ticket requesting a way to do test-only models here

As a workaround, you can decouple your tests.py and make it an app.

tests
|--migrations
|--__init__.py
|--models.py
|--tests.py

You will end up with something like this:

myapp
|-migrations
|-tests
|--migrations
|--__init__.py
|--models.py
|--tests.py
|-__init__.py
|-models.py
|-views.py

Then you should add it to your INSTALLED_APPS

INSTALLED_APPS = (
    # ...
    'myapp',
    'myapp.tests',
)

You probably don't want to install myapp.tests in production, so you can keep separate settings files. Something like this:

INSTALLED_APPS = (
    # ...
    'myapp',
)

try:
    from local_settings import *
except ImportError:
    pass

Or better yet, create a test runner and install your tests there.

Last but not least, remember to run python manage.py makemigrations

Here's a workaround that seems to work. Trick the migration framework into thinking that there are no migrations for your app. In settings.py:

if 'test' in sys.argv:
    # Only during unittests...

    # myapp uses a test-only model, which won't be loaded if we only load
    # our real migration files, so point to a nonexistent one, which will make
    # the test runner fall back to 'syncdb' behavior.
    MIGRATION_MODULES = {
        'myapp': 'myapp.migrations_not_used_in_tests'
    }

I found the idea on the first post in ths Django dev mailing list thread, and it's also currently being used in Django itself, but it may not work in future versions of Django where migrations are required and the "syncdb fallback" is removed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!