Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pytester: only change HOME when not changed in fixtures #485

Merged
merged 2 commits into from
Dec 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 45 additions & 35 deletions src/_pytest/pytester/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ def pytest_configure(config):
if checker.matching_platform():
config.pluginmanager.register(checker)

config.pluginmanager.register(PytesterManageEnv())

config.addinivalue_line(
"markers",
"pytester_example_path(*path_segments): join the given path "
Expand Down Expand Up @@ -539,42 +541,50 @@ def _display_running(header: str, *args: str) -> None:
print("{}: {}\n{}in: {}".format(header, args_str, indent, cwd))


@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_call(item: Function) -> Generator[None, None, None]:
"""Setup/activate testdir's monkeypatching only during test calls.

When it would be done via the instance/fixture directly it would also be
active during teardown (e.g. with the terminal plugin's reporting), where
it might mess with the column width etc.
"""
try:
funcargs = item.funcargs
except AttributeError:
testdir = None
else:
testdir = funcargs.get("testdir")
if not isinstance(testdir, Testdir):
yield
return

mp = testdir.monkeypatch
mp.setenv("PYTEST_DEBUG_TEMPROOT", str(testdir.test_tmproot))
# Ensure no unexpected caching via tox.
mp.delenv("TOX_ENV_DIR", raising=False)
# Discard outer pytest options.
mp.delenv("PYTEST_ADDOPTS", raising=False)
# Ensure no user config is used.
tmphome = str(testdir.tmpdir)
mp.setenv("HOME", tmphome)
mp.setenv("USERPROFILE", tmphome)
# Do not use colors for inner runs by default.
mp.setenv("PY_COLORS", "0")

mp.setattr("_pytest.terminal.get_terminal_width", lambda: 80)
try:
class PytesterManageEnv:
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_setup(self):
initial_home = os.getenv("HOME")
yield
finally:
mp.undo()
self._initial_home_changed = os.getenv("HOME") != initial_home

@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_call(self, item: Function) -> Generator[None, None, None]:
"""Setup/activate testdir's monkeypatching only during test calls.

When it would be done via the instance/fixture directly it would also be
active during teardown (e.g. with the terminal plugin's reporting), where
it might mess with the column width etc.
"""
try:
funcargs = item.funcargs
except AttributeError:
testdir = None
else:
testdir = funcargs.get("testdir")
if not isinstance(testdir, Testdir):
yield
return

mp = testdir.monkeypatch
mp.setenv("PYTEST_DEBUG_TEMPROOT", str(testdir.test_tmproot))
# Ensure no unexpected caching via tox.
mp.delenv("TOX_ENV_DIR", raising=False)
# Discard outer pytest options.
mp.delenv("PYTEST_ADDOPTS", raising=False)
# Ensure no user config is used.
if not self._initial_home_changed:
tmphome = str(testdir.tmpdir)
mp.setenv("HOME", tmphome)
mp.setenv("USERPROFILE", tmphome)
# Do not use colors for inner runs by default.
mp.setenv("PY_COLORS", "0")

mp.setattr("_pytest.terminal.get_terminal_width", lambda: 80)
try:
yield
finally:
mp.undo()


class Testdir(Generic[AnyStr]):
Expand Down
18 changes: 18 additions & 0 deletions testing/test_pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -1433,3 +1433,21 @@ def test_makefiles_sequence_duplicate(self, testdir: "Testdir") -> None:
)
assert tuple(x.name for x in files) == ("1", "2", "1")
assert tuple(x.read_text() for x in files) == ("foo2", "bar", "foo2")


def test_home_used_from_fixture(testdir: "Testdir") -> None:
p1 = testdir.makepyfile(
"""
import os
import pytest

@pytest.fixture
def fix():
os.environ["HOME"] = "/new/home"

def test(testdir, fix):
assert os.environ["HOME"] == "/new/home"
"""
)
result = testdir.runpytest(p1, "-ppytester")
assert result.ret == 0