-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Expand file tree
/
Copy pathconftest.py
More file actions
148 lines (129 loc) · 5.09 KB
/
conftest.py
File metadata and controls
148 lines (129 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import os
import dj_database_url
import django
import pytest
from django.apps import apps
from django.core import management
from django.core.management.color import no_style
from django.db import connection
from django.test import TestCase, TransactionTestCase
@pytest.fixture(autouse=True)
def _reset_sequences(request):
"""Reset all database sequences so PKs start from 1 in each test.
PostgreSQL sequences are non-transactional and persist across
TestCase's transaction rollbacks. This fixture ensures every test
gets predictable PKs starting from 1 regardless of execution order.
No-op on SQLite and skipped for tests that don't use the database.
"""
if connection.vendor != 'postgresql':
return
# Only run for tests that actually have database access.
if not (request.cls and issubclass(request.cls, (TestCase, TransactionTestCase))):
if 'db' not in request.fixturenames and 'transactional_db' not in request.fixturenames:
return
table_names = set(connection.introspection.table_names())
models = [m for m in apps.get_models() if m._meta.db_table in table_names]
sql_list = connection.ops.sequence_reset_sql(no_style(), models)
if sql_list:
with connection.cursor() as cursor:
for sql in sql_list:
cursor.execute(sql)
def pytest_addoption(parser):
parser.addoption('--staticfiles', action='store_true', default=False,
help='Run tests with static files collection, using manifest '
'staticfiles storage. Used for testing the distribution.')
def pytest_configure(config):
from django.conf import settings
if os.getenv('DATABASE_URL'):
databases = {
'default': dj_database_url.config(),
'secondary': dj_database_url.config(),
}
else:
databases = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
'secondary': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
}
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DEFAULT_AUTO_FIELD="django.db.models.AutoField",
DATABASES=databases,
SITE_ID=1,
SECRET_KEY='not very secret in tests',
USE_I18N=True,
STATIC_URL='/static/',
ROOT_URLCONF='tests.urls',
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
"debug": True, # We want template errors to raise
}
},
],
MIDDLEWARE=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
INSTALLED_APPS=(
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'tests.authentication',
'tests.generic_relations',
'tests.importable',
'tests',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.MD5PasswordHasher',
),
)
# Add django.contrib.postgres when using a PostgreSQL database
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
settings.INSTALLED_APPS += (
'django.contrib.postgres',
)
# guardian is optional
try:
import guardian # NOQA
except ImportError:
pass
else:
settings.ANONYMOUS_USER_ID = -1
settings.AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
settings.INSTALLED_APPS += (
'guardian',
)
# Manifest storage will raise an exception if static files are not present (ie, a packaging failure).
if config.getoption('--staticfiles'):
import rest_framework
settings.STATIC_ROOT = os.path.join(os.path.dirname(rest_framework.__file__), 'static-root')
backend = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
settings.STORAGES['staticfiles']['BACKEND'] = backend
django.setup()
if config.getoption('--staticfiles'):
management.call_command('collectstatic', verbosity=0, interactive=False)
def pytest_collection_modifyitems(config, items):
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql':
skip_postgres = pytest.mark.skip(reason='Requires PostgreSQL database backend')
for item in items:
if 'requires_postgres' in item.keywords:
item.add_marker(skip_postgres)