diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index 6fbf8144a8f..daf9194062e 100644 --- a/src/_pytest/config/__init__.py +++ b/src/_pytest/config/__init__.py @@ -603,6 +603,7 @@ def __init__(self, pluginmanager): self._warn = self.pluginmanager._warn self.pluginmanager.register(self, "pytestconfig") self._configured = False + self.cwd = os.getcwd() def do_setns(dic): import pytest @@ -847,11 +848,10 @@ def parse(self, args, addopts=True): args, self.option, namespace=self.option ) if not args: - cwd = os.getcwd() - if cwd == self.rootdir: + if self.cwd == self.rootdir: args = self.getini("testpaths") if not args: - args = [cwd] + args = [self.cwd] self.args = args except PrintHelp: pass diff --git a/testing/test_collection.py b/testing/test_collection.py index 3860cf9f906..ad55ac98c5f 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -1017,5 +1017,29 @@ def test_1(): """ ) result = testdir.runpytest() + result.stdout.fnmatch_lines(["*1 passed in*"]) assert result.ret == 0 + + +def test_collect_with_chdir_during_import(testdir): + subdir = testdir.tmpdir.mkdir("sub") + testdir.tmpdir.join("conftest.py").write( + textwrap.dedent( + """ + import os + os.chdir(%r) + """ + % (str(subdir),) + ) + ) + testdir.makepyfile( + """ + def test_1(): + import os + assert os.getcwd() == %r + """ + % (str(subdir),) + ) + result = testdir.runpytest() result.stdout.fnmatch_lines(["*1 passed in*"]) + assert result.ret == 0