From 024df06ec15d7304fbb5f9a2b1aa44f2af9daf4c Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Mon, 2 Oct 2023 13:58:54 -0400 Subject: [PATCH] tests: Set HOME to a temporary directory when running tests. When running the tests in my environment, tests that derived from `test_wrapper.GitCheckoutTestCase` would fail on commit or tag due to incomplete or incorrect gpg config. Ideally, the tests should not be dependent on the user's git config. This change ensures $HOME (or Windows equivalent) is replaced for the session. Bug: 302797407 Change-Id: Ib42b712dd7b6602fee6e18329a8c6d52fb9458b9 Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/388235 Tested-by: Jason R. Coombs Reviewed-by: Mike Frysinger Commit-Queue: Jason R. Coombs --- tests/conftest.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index e1a2292a..3c312015 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,8 +14,11 @@ """Common fixtures for pytests.""" +import pathlib + import pytest +import platform_utils import repo_trace @@ -23,3 +26,49 @@ import repo_trace def disable_repo_trace(tmp_path): """Set an environment marker to relax certain strict checks for test code.""" # noqa: E501 repo_trace._TRACE_FILE = str(tmp_path / "TRACE_FILE_from_test") + + +# adapted from pytest-home 0.5.1 +def _set_home(monkeypatch, path: pathlib.Path): + """ + Set the home dir using a pytest monkeypatch context. + """ + win = platform_utils.isWindows() + vars = ["HOME"] + win * ["USERPROFILE"] + for var in vars: + monkeypatch.setenv(var, str(path)) + return path + + +# copied from +# https://github.com/pytest-dev/pytest/issues/363#issuecomment-1335631998 +@pytest.fixture(scope="session") +def monkeysession(): + with pytest.MonkeyPatch.context() as mp: + yield mp + + +@pytest.fixture(autouse=True, scope="session") +def session_tmp_home_dir(tmp_path_factory, monkeysession): + """Set HOME to a temporary directory, avoiding user's .gitconfig. + + b/302797407 + + Set home at session scope to take effect prior to + ``test_wrapper.GitCheckoutTestCase.setUpClass``. + """ + return _set_home(monkeysession, tmp_path_factory.mktemp("home")) + + +# adapted from pytest-home 0.5.1 +@pytest.fixture(autouse=True) +def tmp_home_dir(monkeypatch, tmp_path_factory): + """Set HOME to a temporary directory. + + Ensures that state doesn't accumulate in $HOME across tests. + + Note that in conjunction with session_tmp_homedir, the HOME + dir is patched twice, once at session scope, and then again at + the function scope. + """ + return _set_home(monkeypatch, tmp_path_factory.mktemp("home"))