-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathtest_django_settings_module.py
607 lines (500 loc) · 16.9 KB
/
test_django_settings_module.py
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE
If these tests fail you probably forgot to run "python setup.py develop".
"""
import pytest
BARE_SETTINGS = """
# At least one database must be configured
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
}
SECRET_KEY = 'foobar'
"""
def test_ds_ini(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
DJANGO_SETTINGS_MODULE = tpkg.settings_ini
"""
)
pkg = testdir.mkpydir("tpkg")
pkg.join("settings_ini.py").write(BARE_SETTINGS)
testdir.makepyfile(
"""
import os
def test_ds():
assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_ini'
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines([
"django: settings: tpkg.settings_ini (from ini)",
"*= 1 passed*",
])
assert result.ret == 0
def test_ds_env(testdir, monkeypatch) -> None:
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "tpkg.settings_env")
pkg = testdir.mkpydir("tpkg")
settings = pkg.join("settings_env.py")
settings.write(BARE_SETTINGS)
testdir.makepyfile(
"""
import os
def test_settings():
assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env'
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines([
"django: settings: tpkg.settings_env (from env)",
"*= 1 passed*",
])
def test_ds_option(testdir, monkeypatch) -> None:
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "DO_NOT_USE_env")
testdir.makeini(
"""
[pytest]
DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini
"""
)
pkg = testdir.mkpydir("tpkg")
settings = pkg.join("settings_opt.py")
settings.write(BARE_SETTINGS)
testdir.makepyfile(
"""
import os
def test_ds():
assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_opt'
"""
)
result = testdir.runpytest_subprocess("--ds=tpkg.settings_opt")
result.stdout.fnmatch_lines([
"django: settings: tpkg.settings_opt (from option)",
"*= 1 passed*",
])
def test_ds_env_override_ini(testdir, monkeypatch) -> None:
"DSM env should override ini."
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "tpkg.settings_env")
testdir.makeini(
"""\
[pytest]
DJANGO_SETTINGS_MODULE = DO_NOT_USE_ini
"""
)
pkg = testdir.mkpydir("tpkg")
settings = pkg.join("settings_env.py")
settings.write(BARE_SETTINGS)
testdir.makepyfile(
"""
import os
def test_ds():
assert os.environ['DJANGO_SETTINGS_MODULE'] == 'tpkg.settings_env'
"""
)
result = testdir.runpytest_subprocess()
assert result.parseoutcomes()["passed"] == 1
assert result.ret == 0
def test_ds_non_existent(testdir, monkeypatch) -> None:
"""
Make sure we do not fail with INTERNALERROR if an incorrect
DJANGO_SETTINGS_MODULE is given.
"""
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "DOES_NOT_EXIST")
testdir.makepyfile("def test_ds(): pass")
result = testdir.runpytest_subprocess()
result.stderr.fnmatch_lines(["*ImportError:*DOES_NOT_EXIST*"])
assert result.ret != 0
def test_ds_after_user_conftest(testdir, monkeypatch) -> None:
"""
Test that the settings module can be imported, after pytest has adjusted
the sys.path.
"""
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "settings_after_conftest")
testdir.makepyfile("def test_ds(): pass")
testdir.makepyfile(settings_after_conftest="SECRET_KEY='secret'")
# testdir.makeconftest("import sys; print(sys.path)")
result = testdir.runpytest_subprocess("-v")
result.stdout.fnmatch_lines(["* 1 passed*"])
assert result.ret == 0
def test_ds_in_pytest_configure(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
pkg = testdir.mkpydir("tpkg")
settings = pkg.join("settings_ds.py")
settings.write(BARE_SETTINGS)
testdir.makeconftest(
"""
import os
from django.conf import settings
def pytest_configure():
if not settings.configured:
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'tpkg.settings_ds')
"""
)
testdir.makepyfile(
"""
def test_anything():
pass
"""
)
r = testdir.runpytest_subprocess()
assert r.parseoutcomes()["passed"] == 1
assert r.ret == 0
def test_django_settings_configure(testdir, monkeypatch) -> None:
"""
Make sure Django can be configured without setting
DJANGO_SETTINGS_MODULE altogether, relying on calling
django.conf.settings.configure() and then invoking pytest.
"""
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
p = testdir.makepyfile(
run="""
from django.conf import settings
settings.configure(SECRET_KEY='set from settings.configure()',
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}},
INSTALLED_APPS=['django.contrib.auth',
'django.contrib.contenttypes',])
import pytest
pytest.main()
"""
)
testdir.makepyfile(
"""
import pytest
from django.conf import settings
from django.test.client import RequestFactory
from django.test import TestCase
from django.contrib.auth.models import User
def test_access_to_setting():
assert settings.SECRET_KEY == 'set from settings.configure()'
# This test requires Django to be properly configured to be run
def test_rf(rf):
assert isinstance(rf, RequestFactory)
# This tests that pytest-django actually configures the database
# according to the settings above
class ATestCase(TestCase):
def test_user_count(self):
assert User.objects.count() == 0
@pytest.mark.django_db
def test_user_count():
assert User.objects.count() == 0
"""
)
result = testdir.runpython(p)
result.stdout.fnmatch_lines(["* 4 passed*"])
def test_settings_in_hook(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeconftest(
"""
from django.conf import settings
def pytest_configure():
settings.configure(SECRET_KEY='set from pytest_configure',
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
INSTALLED_APPS=['django.contrib.auth',
'django.contrib.contenttypes',])
"""
)
testdir.makepyfile(
"""
import pytest
from django.conf import settings
from django.contrib.auth.models import User
def test_access_to_setting():
assert settings.SECRET_KEY == 'set from pytest_configure'
@pytest.mark.django_db
def test_user_count():
assert User.objects.count() == 0
"""
)
r = testdir.runpytest_subprocess()
assert r.ret == 0
def test_django_not_loaded_without_settings(testdir, monkeypatch) -> None:
"""
Make sure Django is not imported at all if no Django settings is specified.
"""
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makepyfile(
"""
import sys
def test_settings():
assert 'django' not in sys.modules
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines(["* 1 passed*"])
assert result.ret == 0
def test_debug_false_by_default(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeconftest(
"""
from django.conf import settings
def pytest_configure():
settings.configure(SECRET_KEY='set from pytest_configure',
DEBUG=True,
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
INSTALLED_APPS=['django.contrib.auth',
'django.contrib.contenttypes',])
"""
)
testdir.makepyfile(
"""
from django.conf import settings
def test_debug_is_false():
assert settings.DEBUG is False
"""
)
r = testdir.runpytest_subprocess()
assert r.ret == 0
@pytest.mark.parametrize('django_debug_mode', (False, True))
def test_django_debug_mode_true_false(testdir, monkeypatch, django_debug_mode: bool) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
django_debug_mode = {}
""".format(django_debug_mode)
)
testdir.makeconftest(
"""
from django.conf import settings
def pytest_configure():
settings.configure(SECRET_KEY='set from pytest_configure',
DEBUG=%s,
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
INSTALLED_APPS=['django.contrib.auth',
'django.contrib.contenttypes',])
""" % (not django_debug_mode)
)
testdir.makepyfile(
"""
from django.conf import settings
def test_debug_is_false():
assert settings.DEBUG is {}
""".format(django_debug_mode)
)
r = testdir.runpytest_subprocess()
assert r.ret == 0
@pytest.mark.parametrize('settings_debug', (False, True))
def test_django_debug_mode_keep(testdir, monkeypatch, settings_debug: bool) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
django_debug_mode = keep
"""
)
testdir.makeconftest(
"""
from django.conf import settings
def pytest_configure():
settings.configure(SECRET_KEY='set from pytest_configure',
DEBUG=%s,
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
INSTALLED_APPS=['django.contrib.auth',
'django.contrib.contenttypes',])
""" % settings_debug
)
testdir.makepyfile(
"""
from django.conf import settings
def test_debug_is_false():
assert settings.DEBUG is {}
""".format(settings_debug)
)
r = testdir.runpytest_subprocess()
assert r.ret == 0
@pytest.mark.django_project(
extra_settings="""
INSTALLED_APPS = [
'tpkg.app.apps.TestApp',
]
"""
)
def test_django_setup_sequence(django_testdir) -> None:
django_testdir.create_app_file(
"""
from django.apps import apps, AppConfig
class TestApp(AppConfig):
name = 'tpkg.app'
def ready(self):
populating = apps.loading
print('READY(): populating=%r' % populating)
""",
"apps.py",
)
django_testdir.create_app_file(
"""
from django.apps import apps
populating = apps.loading
print('IMPORT: populating=%r,ready=%r' % (populating, apps.ready))
SOME_THING = 1234
""",
"models.py",
)
django_testdir.create_app_file("", "__init__.py")
django_testdir.makepyfile(
"""
from django.apps import apps
from tpkg.app.models import SOME_THING
def test_anything():
populating = apps.loading
print('TEST: populating=%r,ready=%r' % (populating, apps.ready))
"""
)
result = django_testdir.runpytest_subprocess("-s", "--tb=line")
result.stdout.fnmatch_lines(["*IMPORT: populating=True,ready=False*"])
result.stdout.fnmatch_lines(["*READY(): populating=True*"])
result.stdout.fnmatch_lines(["*TEST: populating=True,ready=True*"])
assert result.ret == 0
def test_no_ds_but_django_imported(testdir, monkeypatch) -> None:
"""pytest-django should not bail out, if "django" has been imported
somewhere, e.g. via pytest-splinter."""
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makepyfile(
"""
import os
import django
from pytest_django.lazy_django import django_settings_is_configured
def test_django_settings_is_configured():
assert django_settings_is_configured() is False
def test_env():
assert 'DJANGO_SETTINGS_MODULE' not in os.environ
def test_cfg(pytestconfig):
assert pytestconfig.option.ds is None
"""
)
r = testdir.runpytest_subprocess("-s")
assert r.ret == 0
def test_no_ds_but_django_conf_imported(testdir, monkeypatch) -> None:
"""pytest-django should not bail out, if "django.conf" has been imported
somewhere, e.g. via hypothesis (#599)."""
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makepyfile(
"""
import os
import sys
# line copied from hypothesis/extras/django.py
from django.conf import settings as django_settings
# Don't let pytest poke into this object, generating a
# django.core.exceptions.ImproperlyConfigured
del django_settings
from pytest_django.lazy_django import django_settings_is_configured
def test_django_settings_is_configured():
assert django_settings_is_configured() is False
def test_django_conf_is_imported():
assert 'django.conf' in sys.modules
def test_env():
assert 'DJANGO_SETTINGS_MODULE' not in os.environ
def test_cfg(pytestconfig):
assert pytestconfig.option.ds is None
"""
)
r = testdir.runpytest_subprocess("-s")
assert r.ret == 0
def test_no_django_settings_but_django_imported(testdir, monkeypatch) -> None:
"""Make sure we do not crash when Django happens to be imported, but
settings is not properly configured"""
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeconftest("import django")
r = testdir.runpytest_subprocess("--help")
assert r.ret == 0
def test_dch_ini(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
DJANGO_CONFIGURATION_HOOK = tpkg.test.setup
"""
)
pkg = testdir.mkpydir("tpkg")
pkg.join("test.py").write("""
# Test
from django.conf import settings
def setup():
settings.configure()
""")
testdir.makepyfile(
"""
import os
def test_ds():
pass
"""
)
result = testdir.runpytest_subprocess()
assert result.ret == 0
def test_dch_ini_invalid_path(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
DJANGO_CONFIGURATION_HOOK = invalid_path
"""
)
testdir.makepyfile(
"""
import os
def test_ds():
pass
"""
)
result = testdir.runpytest_subprocess()
result.stderr.fnmatch_lines(["ImportError: Invalid path for configuration hook: invalid_path"])
assert result.ret == 1
def test_dch_ini_no_module(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
DJANGO_CONFIGURATION_HOOK = tpkg.not_existing.setup
"""
)
testdir.makepyfile(
"""
import os
def test_ds():
pass
"""
)
result = testdir.runpytest_subprocess()
result.stderr.fnmatch_lines(["ImportError: Unable to import module tpkg.not_existing"])
assert result.ret == 1
def test_dch_ini_module_but_no_func(testdir, monkeypatch) -> None:
monkeypatch.delenv("DJANGO_SETTINGS_MODULE")
testdir.makeini(
"""
[pytest]
DJANGO_CONFIGURATION_HOOK = tpkg.test.not_existing_function
"""
)
pkg = testdir.mkpydir("tpkg")
pkg.join("test.py").write("""
# Test
from django.conf import settings
def setup():
settings.configure()
""")
testdir.makepyfile(
"""
import os
def test_ds():
pass
"""
)
result = testdir.runpytest_subprocess()
result.stderr.fnmatch_lines(["ImportError: No function found with name "
"not_existing_function in module tpkg.test!"])
assert result.ret == 1