diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2018-11-24 15:12:56 -0500 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2018-11-25 15:11:54 -0500 |
commit | 20998572517413d52e4ca63a79d5a790578d19cb (patch) | |
tree | d5d6d7f9ed7e0c9dfb19fceb27374d0823b6f970 | |
parent | 3c57eda03b6a1a40f480db30a19978e95dfbed31 (diff) | |
download | python-coveragepy-git-20998572517413d52e4ca63a79d5a790578d19cb.tar.gz |
Control the sys.path that tests see
-rw-r--r-- | tests/conftest.py | 35 | ||||
-rw-r--r-- | tests/test_testing.py | 6 |
2 files changed, 41 insertions, 0 deletions
diff --git a/tests/conftest.py b/tests/conftest.py index e9802517..2c30a2d7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,6 +7,8 @@ Pytest auto configuration. This module is run automatically by pytest, to define and enable fixtures. """ +import os +import sys import warnings import pytest @@ -33,3 +35,36 @@ def set_warnings(): # pypy3 warns about unclosed files a lot. # pylint: disable=undefined-variable warnings.filterwarnings("ignore", r".*unclosed file", category=ResourceWarning) + + +@pytest.fixture(autouse=True) +def reset_sys_path(): + """Clean up sys.path changes around every test.""" + sys_path = list(sys.path) + yield + sys.path[:] = sys_path + + +@pytest.fixture(autouse=True) +def fix_xdist_sys_path(): + """Prevent xdist from polluting the Python path. + + We run tests that care a lot about the contents of sys.path. Pytest-xdist + changes sys.path, so running with xdist, vs without xdist, sets sys.path + differently. With xdist, sys.path[1] is an empty string, without xdist, + it's the virtualenv bin directory. We don't want the empty string, so + clobber that entry. + + See: https://github.com/pytest-dev/pytest-xdist/issues/376 + + """ + if os.environ.get('PYTEST_XDIST_WORKER', ''): + # We are running in an xdist worker. + if sys.path[1] == '': + # xdist has set sys.path[1] to ''. Clobber it. + del sys.path[1] + # Also, don't let it sneak stuff in via PYTHONPATH. + try: + del os.environ['PYTHONPATH'] + except KeyError: + pass diff --git a/tests/test_testing.py b/tests/test_testing.py index 2b01584e..79d8dcae 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -19,6 +19,12 @@ from tests.coveragetest import CoverageTest, convert_skip_exceptions from tests.helpers import CheckUniqueFilenames, re_lines, re_line +def test_xdist_sys_path_nuttiness_is_fixed(): + # See conftest.py:fix_xdist_sys_path + assert sys.path[1] != '' + assert os.environ.get('PYTHONPATH') is None + + class TestingTest(TestCase): """Tests of helper methods on `backunittest.TestCase`.""" |