1111import sys
1212import types
1313
14- import py
14+ import pathlib
1515import pytest
1616
1717from .django_compat import is_django_unittest # noqa
@@ -87,13 +87,6 @@ def pytest_addoption(parser):
8787 type = 'bool' , default = False )
8888
8989
90- def _exists (path , ignore = EnvironmentError ):
91- try :
92- return path .check ()
93- except ignore :
94- return False
95-
96-
9790PROJECT_FOUND = ('pytest-django found a Django project in %s '
9891 '(it contains manage.py) and added it to the Python path.\n '
9992 'If this is wrong, add "django_find_project = false" to '
@@ -120,21 +113,28 @@ def _handle_import_error(extra_message):
120113
121114
122115def _add_django_project_to_path (args ):
123- args = [x for x in args if not str (x ).startswith ("-" )]
124-
125- if not args :
126- args = [py .path .local ()]
127-
128- for arg in args :
129- arg = py .path .local (arg )
130-
131- for base in arg .parts (reverse = True ):
132- manage_py_try = base .join ('manage.py' )
133-
134- if _exists (manage_py_try ):
135- sys .path .insert (0 , str (base ))
136- return PROJECT_FOUND % base
116+ def is_django_project (path ):
117+ return path .is_dir () and (path / 'manage.py' ).exists ()
118+
119+ def find_django_path (args ):
120+ args = [pathlib .Path (x ) for x in args if not str (x ).startswith ("-" )]
121+ args = [p for p in args if p .is_dir ()]
122+
123+ if not args :
124+ args = [pathlib .Path .cwd ()]
125+
126+ for arg in args :
127+ if is_django_project (arg ):
128+ return arg
129+ for parent in arg .parents :
130+ if is_django_project (parent ):
131+ return parent
132+ return None
137133
134+ project_dir = find_django_path (args )
135+ if project_dir :
136+ sys .path .insert (0 , str (project_dir ))
137+ return PROJECT_FOUND % project_dir
138138 return PROJECT_NOT_FOUND
139139
140140
0 commit comments