Merge pull request #3872 from nicoddemus/tests-in-init-files

Collect tests from __init__.py files if they match 'python_files'
This commit is contained in:
Bruno Oliveira 2018-08-26 08:50:17 -03:00 committed by GitHub
commit dd5f5ca4cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 37 additions and 5 deletions

View File

@ -0,0 +1 @@
Fix collection of tests from ``__init__.py`` files if they match the ``python_files`` configuration option.

View File

@ -672,7 +672,9 @@ class Testdir(object):
example_path.copy(result)
return result
else:
raise LookupError("example is not found as a file or directory")
raise LookupError(
'example "{}" is not found as a file or directory'.format(example_path)
)
Session = Session

View File

@ -201,15 +201,19 @@ def pytest_collect_file(path, parent):
ext = path.ext
if ext == ".py":
if not parent.session.isinitpath(path):
for pat in parent.config.getini("python_files") + ["__init__.py"]:
if path.fnmatch(pat):
break
else:
if not path_matches_patterns(
path, parent.config.getini("python_files") + ["__init__.py"]
):
return
ihook = parent.session.gethookproxy(path)
return ihook.pytest_pycollect_makemodule(path=path, parent=parent)
def path_matches_patterns(path, patterns):
"""Returns True if the given py.path.local matches one of the patterns in the list of globs given"""
return any(path.fnmatch(pattern) for pattern in patterns)
def pytest_pycollect_makemodule(path, parent):
if path.basename == "__init__.py":
return Package(path, parent)
@ -590,6 +594,11 @@ class Package(Module):
self.session.config.pluginmanager._duplicatepaths.remove(path)
this_path = self.fspath.dirpath()
init_module = this_path.join("__init__.py")
if init_module.check(file=1) and path_matches_patterns(
init_module, self.config.getini("python_files")
):
yield Module(init_module, self)
pkg_prefixes = set()
for path in this_path.visit(rec=self._recurse, bf=True, sort=True):
# we will visit our own __init__.py file, in which case we skip it

View File

@ -0,0 +1,2 @@
[pytest]
python_files = *.py

View File

@ -0,0 +1,2 @@
def test_init():
pass

View File

@ -0,0 +1,2 @@
def test_foo():
pass

View File

@ -938,3 +938,17 @@ def test_fixture_scope_sibling_conftests(testdir):
"*1 passed, 1 error*",
]
)
def test_collect_init_tests(testdir):
"""Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)"""
p = testdir.copy_example("collect/collect_init_tests")
result = testdir.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines(
[
"*<Module '__init__.py'>",
"*<Function 'test_init'>",
"*<Module 'test_foo.py'>",
"*<Function 'test_foo'>",
]
)