@@ -476,9 +476,6 @@ def __init__(self, request, tmpdir_factory):
476476 name = request .function .__name__
477477 self .tmpdir = tmpdir_factory .mktemp (name , numbered = True )
478478 self .test_tmproot = tmpdir_factory .mktemp ("tmp-" + name , numbered = True )
479- os .environ ["PYTEST_DEBUG_TEMPROOT" ] = str (self .test_tmproot )
480- os .environ .pop ("TOX_ENV_DIR" , None ) # Ensure that it is not used for caching.
481- os .environ .pop ("PYTEST_ADDOPTS" , None ) # Do not use outer options.
482479 self .plugins = []
483480 self ._cwd_snapshot = CwdSnapshot ()
484481 self ._sys_path_snapshot = SysPathsSnapshot ()
@@ -491,6 +488,13 @@ def __init__(self, request, tmpdir_factory):
491488 elif method == "subprocess" :
492489 self ._runpytest_method = self .runpytest_subprocess
493490
491+ mp = self .monkeypatch = MonkeyPatch ()
492+ mp .setenv ("PYTEST_DEBUG_TEMPROOT" , str (self .test_tmproot ))
493+ # Ensure no unexpected caching via tox.
494+ mp .delenv ("TOX_ENV_DIR" , raising = False )
495+ # Discard outer pytest options.
496+ mp .delenv ("PYTEST_ADDOPTS" , raising = False )
497+
494498 def __repr__ (self ):
495499 return "<Testdir %r>" % (self .tmpdir ,)
496500
@@ -508,7 +512,7 @@ def finalize(self):
508512 self ._sys_modules_snapshot .restore ()
509513 self ._sys_path_snapshot .restore ()
510514 self ._cwd_snapshot .restore ()
511- os . environ . pop ( "PYTEST_DEBUG_TEMPROOT" , None )
515+ self . monkeypatch . undo ( )
512516
513517 def __take_sys_modules_snapshot (self ):
514518 # some zope modules used by twisted-related tests keep internal state
@@ -799,11 +803,11 @@ def inline_run(self, *args, **kwargs):
799803 """
800804 finalizers = []
801805 try :
802- # Do not load user config.
803- monkeypatch = MonkeyPatch ()
804- monkeypatch .setenv ("HOME" , str (self .tmpdir ))
805- monkeypatch .setenv ("USERPROFILE" , str (self .tmpdir ))
806- finalizers .append (monkeypatch .undo )
806+ # Do not load user config (during runs only) .
807+ mp_run = MonkeyPatch ()
808+ mp_run .setenv ("HOME" , str (self .tmpdir ))
809+ mp_run .setenv ("USERPROFILE" , str (self .tmpdir ))
810+ finalizers .append (mp_run .undo )
807811
808812 # When running pytest inline any plugins active in the main test
809813 # process are already imported. So this disables the warning which
0 commit comments