Skip to content

Commit 8c47ce9

Browse files
committed
pytester: use monkeypatch fixture
Fixes #6213.
1 parent a2d4833 commit 8c47ce9

File tree

3 files changed

+9
-9
lines changed

3 files changed

+9
-9
lines changed

changelog/6213.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytester: the ``testdir`` fixture uses the ``monkeypatch`` fixture for changing the environment.

src/_pytest/pytester.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,7 @@ def __init__(self, request, tmpdir_factory):
538538
self.request.addfinalizer(self.finalize)
539539
self._method = self.request.config.getoption("--runpytest")
540540

541-
mp = self.monkeypatch = MonkeyPatch()
541+
mp = self.monkeypatch = self.request.getfixturevalue("monkeypatch")
542542
mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self.test_tmproot))
543543
# Ensure no unexpected caching via tox.
544544
mp.delenv("TOX_ENV_DIR", raising=False)
@@ -566,7 +566,6 @@ def finalize(self):
566566
self._sys_modules_snapshot.restore()
567567
self._sys_path_snapshot.restore()
568568
self._cwd_snapshot.restore()
569-
self.monkeypatch.undo()
570569

571570
def __take_sys_modules_snapshot(self):
572571
# some zope modules used by twisted-related tests keep internal state

testing/test_pytester.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -542,17 +542,17 @@ def test_no_matching(function):
542542
func(bad_pattern) # bad pattern does not match any line: passes
543543

544544

545-
def test_pytester_addopts(request, monkeypatch):
545+
def test_pytester_addopts_before_testdir(request, monkeypatch):
546+
orig = os.environ.get("PYTEST_ADDOPTS", None)
546547
monkeypatch.setenv("PYTEST_ADDOPTS", "--orig-unused")
547-
548548
testdir = request.getfixturevalue("testdir")
549+
assert "PYTEST_ADDOPTS" not in os.environ
550+
testdir.finalize()
551+
assert os.environ.get("PYTEST_ADDOPTS") == orig
549552

550-
try:
551-
assert "PYTEST_ADDOPTS" not in os.environ
552-
finally:
553-
testdir.finalize()
554553

555-
assert os.environ["PYTEST_ADDOPTS"] == "--orig-unused"
554+
def test_testdir_respects_monkeypatch(testdir, monkeypatch):
555+
assert monkeypatch is testdir.monkeypatch
556556

557557

558558
def test_run_stdin(testdir):

0 commit comments

Comments
 (0)