| 1 |
import contextlib |
| 2 |
import os |
| 3 |
|
| 4 |
import dj_database_url |
| 5 |
import django |
| 6 |
import pytest |
| 7 |
from django.apps import apps |
| 8 |
from django.core import management |
| 9 |
from django.core.management.color import no_style |
| 10 |
from django.db import connection |
| 11 |
|
| 12 |
|
| 13 |
@pytest.fixture |
| 14 |
def reset_sequences(): |
| 15 |
""" |
| 16 |
Reset all database sequences so PKs start from 1. |
| 17 |
|
| 18 |
PostgreSQL sequences are non-transactional and persist across |
| 19 |
TestCase's transaction rollbacks. Apply this fixture to test |
| 20 |
classes that rely on hardcoded PKs to keep them predictable |
| 21 |
regardless of execution order. No-op on SQLite. |
| 22 |
""" |
| 23 |
if connection.vendor != 'postgresql': |
| 24 |
return |
| 25 |
table_names = set(connection.introspection.table_names()) |
| 26 |
models = [m for m in apps.get_models() if m._meta.db_table in table_names] |
| 27 |
sql_list = connection.ops.sequence_reset_sql(no_style(), models) |
| 28 |
if sql_list: |
| 29 |
with connection.cursor() as cursor: |
| 30 |
for sql in sql_list: |
| 31 |
cursor.execute(sql) |
| 32 |
|
| 33 |
|
| 34 |
def pytest_addoption(parser): |
| 35 |
parser.addoption('--staticfiles', action='store_true', default=False, |
| 36 |
help='Run tests with static files collection, using manifest ' |
| 37 |
'staticfiles storage. Used for testing the distribution.') |
| 38 |
|
| 39 |
|
| 40 |
def pytest_configure(config): |
| 41 |
from django.conf import settings |
| 42 |
|
| 43 |
if os.getenv('DATABASE_URL'): |
| 44 |
databases = { |
| 45 |
'default': dj_database_url.config(), |
| 46 |
'secondary': dj_database_url.config(), |
| 47 |
} |
| 48 |
else: |
| 49 |
databases = { |
| 50 |
'default': { |
| 51 |
'ENGINE': 'django.db.backends.sqlite3', |
| 52 |
'NAME': ':memory:' |
| 53 |
}, |
| 54 |
'secondary': { |
| 55 |
'ENGINE': 'django.db.backends.sqlite3', |
| 56 |
'NAME': ':memory:' |
| 57 |
}, |
| 58 |
} |
| 59 |
|
| 60 |
settings.configure( |
| 61 |
DEBUG_PROPAGATE_EXCEPTIONS=True, |
| 62 |
DEFAULT_AUTO_FIELD="django.db.models.AutoField", |
| 63 |
DATABASES=databases, |
| 64 |
SITE_ID=1, |
| 65 |
SECRET_KEY='not very secret in tests', |
| 66 |
USE_I18N=True, |
| 67 |
STATIC_URL='/static/', |
| 68 |
ROOT_URLCONF='tests.urls', |
| 69 |
TEMPLATES=[ |
| 70 |
{ |
| 71 |
'BACKEND': 'django.template.backends.django.DjangoTemplates', |
| 72 |
'APP_DIRS': True, |
| 73 |
'OPTIONS': { |
| 74 |
"debug": True, # We want template errors to raise |
| 75 |
} |
| 76 |
}, |
| 77 |
], |
| 78 |
MIDDLEWARE=( |
| 79 |
'django.middleware.common.CommonMiddleware', |
| 80 |
'django.contrib.sessions.middleware.SessionMiddleware', |
| 81 |
'django.contrib.auth.middleware.AuthenticationMiddleware', |
| 82 |
'django.contrib.messages.middleware.MessageMiddleware', |
| 83 |
), |
| 84 |
INSTALLED_APPS=( |
| 85 |
'django.contrib.admin', |
| 86 |
'django.contrib.auth', |
| 87 |
'django.contrib.contenttypes', |
| 88 |
'django.contrib.sessions', |
| 89 |
'django.contrib.sites', |
| 90 |
'django.contrib.staticfiles', |
| 91 |
'rest_framework', |
| 92 |
'rest_framework.authtoken', |
| 93 |
'tests.authentication', |
| 94 |
'tests.generic_relations', |
| 95 |
'tests.importable', |
| 96 |
'tests', |
| 97 |
), |
| 98 |
PASSWORD_HASHERS=( |
| 99 |
'django.contrib.auth.hashers.MD5PasswordHasher', |
| 100 |
), |
| 101 |
) |
| 102 |
|
| 103 |
# Add django.contrib.postgres when using a PostgreSQL database |
| 104 |
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql': |
| 105 |
settings.INSTALLED_APPS += ( |
| 106 |
'django.contrib.postgres', |
| 107 |
) |
| 108 |
|
| 109 |
# guardian is optional |
| 110 |
try: |
| 111 |
import guardian # NOQA |
| 112 |
except ImportError: |
| 113 |
pass |
| 114 |
else: |
| 115 |
settings.ANONYMOUS_USER_ID = -1 |
| 116 |
settings.AUTHENTICATION_BACKENDS = ( |
| 117 |
'django.contrib.auth.backends.ModelBackend', |
| 118 |
'guardian.backends.ObjectPermissionBackend', |
| 119 |
) |
| 120 |
settings.INSTALLED_APPS += ( |
| 121 |
'guardian', |
| 122 |
) |
| 123 |
|
| 124 |
# Manifest storage will raise an exception if static files are not present (ie, a packaging failure). |
| 125 |
if config.getoption('--staticfiles'): |
| 126 |
import rest_framework |
| 127 |
settings.STATIC_ROOT = os.path.join(os.path.dirname(rest_framework.__file__), 'static-root') |
| 128 |
backend = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' |
| 129 |
settings.STORAGES['staticfiles']['BACKEND'] = backend |
| 130 |
|
| 131 |
django.setup() |
| 132 |
|
| 133 |
if config.getoption('--staticfiles'): |
| 134 |
management.call_command('collectstatic', verbosity=0, interactive=False) |
| 135 |
|
| 136 |
|
| 137 |
def pytest_collection_modifyitems(config, items): |
| 138 |
from django.conf import settings |
| 139 |
|
| 140 |
if settings.DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql': |
| 141 |
skip_postgres = pytest.mark.skip(reason='Requires PostgreSQL database backend') |
| 142 |
for item in items: |
| 143 |
if 'requires_postgres' in item.keywords: |
| 144 |
item.add_marker(skip_postgres) |
| 145 |
|
| 146 |
|
| 147 |
@contextlib.contextmanager |
| 148 |
def _postgres_extension(extension_name): |
| 149 |
"""Helper to enable a PostgreSQL extension in tests.""" |
| 150 |
with connection.schema_editor(atomic=False) as schema_editor: |
| 151 |
schema_editor.execute( |
| 152 |
'CREATE EXTENSION IF NOT EXISTS %s' % schema_editor.quote_name(extension_name) |
| 153 |
) |
| 154 |
yield |
| 155 |
with connection.schema_editor(atomic=False) as schema_editor: |
| 156 |
schema_editor.execute( |
| 157 |
'DROP EXTENSION IF EXISTS %s' % schema_editor.quote_name(extension_name) |
| 158 |
) |
| 159 |
|
| 160 |
|
| 161 |
@pytest.fixture |
| 162 |
def unaccent_extension(db): |
| 163 |
"""Enable the unaccent PostgreSQL extension in tests.""" |
| 164 |
with _postgres_extension('unaccent'): |
| 165 |
yield |