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