diff --git a/changelog/4745.bugfix.rst b/changelog/4745.bugfix.rst new file mode 100644 index 000000000..a7bfad2a7 --- /dev/null +++ b/changelog/4745.bugfix.rst @@ -0,0 +1 @@ +Fix/improve collection of args when passing in ``__init__.py`` and a test file. diff --git a/src/_pytest/main.py b/src/_pytest/main.py index e17385f10..81a597985 100644 --- a/src/_pytest/main.py +++ b/src/_pytest/main.py @@ -582,7 +582,7 @@ class Session(nodes.FSCollector): col = self._node_cache[argpath] else: collect_root = self._pkg_roots.get(argpath.dirname, self) - col = collect_root._collectfile(argpath) + col = collect_root._collectfile(argpath, handle_dupes=False) if col: self._node_cache[argpath] = col m = self.matchnodes(col, names) diff --git a/testing/test_collection.py b/testing/test_collection.py index 329182b0f..5fe313f98 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -1157,3 +1157,32 @@ def test_collectignore_via_conftest(testdir, monkeypatch): result = testdir.runpytest() assert result.ret == EXIT_NOTESTSCOLLECTED + + +def test_collect_pkg_init_and_file_in_args(testdir): + subdir = testdir.mkdir("sub") + init = subdir.ensure("__init__.py") + init.write("def test_init(): pass") + p = subdir.ensure("test_file.py") + p.write("def test_file(): pass") + + # NOTE: without "-o python_files=*.py" this collects test_file.py twice. + # This changed/broke with "Add package scoped fixtures #2283" (2b1410895) + # initially (causing a RecursionError). + result = testdir.runpytest("-v", str(init), str(p)) + result.stdout.fnmatch_lines( + [ + "sub/test_file.py::test_file PASSED*", + "sub/test_file.py::test_file PASSED*", + "*2 passed in*", + ] + ) + + result = testdir.runpytest("-v", "-o", "python_files=*.py", str(init), str(p)) + result.stdout.fnmatch_lines( + [ + "sub/__init__.py::test_init PASSED*", + "sub/test_file.py::test_file PASSED*", + "*2 passed in*", + ] + )