Skip to content

Commit 211495b

Browse files
committed
Be more careful to not load Django when settings is not properly
configured. When another plugin(or conftest) imports Django, there might be errors arising. Importing Django before pytest-django has the chance to configure settings and call django.setup() may be an error, but it may also be correct depending on what gets imported. This commit closes pytest-dev#289.
1 parent 4ebff28 commit 211495b

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

docs/changelog.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
Changelog
22
=========
3+
4+
NEXT
5+
----
6+
* Fix error when Django happens to be imported before pytest-django runs.
7+
Thanks to Will Harris for `the bug report
8+
<https://github.com/pytest-dev/pytest-django/issues/289>`_.
9+
310
2.9.1
411
-----
512

pytest_django/plugin.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,11 @@ def _setup_django():
128128
if 'django' not in sys.modules:
129129
return
130130

131-
import django
131+
import django.conf
132+
133+
# Avoid trying to force-load Django when settings is not properly configured
134+
if not django.conf.settings.configured:
135+
return
132136

133137
if hasattr(django, 'setup'):
134138
django.setup()

tests/test_django_settings_module.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,3 +340,12 @@ def test_cfg(pytestconfig):
340340
""")
341341
r = testdir.runpytest_subprocess('-s')
342342
assert r.ret == 0
343+
344+
345+
def test_no_django_settings_but_django_imported(testdir, monkeypatch):
346+
"""Make sure we do not crash when Django happens to be imported, but
347+
settings is not properly configured"""
348+
monkeypatch.delenv('DJANGO_SETTINGS_MODULE')
349+
testdir.makeconftest('import django')
350+
r = testdir.runpytest_subprocess('--help')
351+
assert r.ret == 0

0 commit comments

Comments
 (0)