diff --git a/changelog/1671.bugfix.rst b/changelog/1671.bugfix.rst new file mode 100644 index 00000000000..c46eac82866 --- /dev/null +++ b/changelog/1671.bugfix.rst @@ -0,0 +1,2 @@ +The name of the ``.pyc`` files cached by the assertion writer now includes the pytest version +to avoid stale caches. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index cce98000530..f50d8200e89 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -13,6 +13,7 @@ import atomicwrites from _pytest._io.saferepr import saferepr +from _pytest._version import version from _pytest.assertion import util from _pytest.assertion.util import ( # noqa: F401 format_explanation as _format_explanation, @@ -21,7 +22,7 @@ from _pytest.pathlib import PurePath # pytest caches rewritten pycs in __pycache__. -PYTEST_TAG = "{}-PYTEST".format(sys.implementation.cache_tag) +PYTEST_TAG = "{}-pytest-{}".format(sys.implementation.cache_tag, version) PYC_EXT = ".py" + (__debug__ and "c" or "o") PYC_TAIL = "." + PYTEST_TAG + PYC_EXT diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 33c889104bd..258b5d3b788 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -780,6 +780,24 @@ def test_it(): assert testdir.runpytest().ret == 0 + def test_cached_pyc_includes_pytest_version(self, testdir, monkeypatch): + """Avoid stale caches (#1671)""" + monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False) + testdir.makepyfile( + test_foo=""" + def test_foo(): + assert True + """ + ) + result = testdir.runpytest_subprocess() + assert result.ret == 0 + found_names = glob.glob( + "__pycache__/*-pytest-{}.pyc".format(pytest.__version__) + ) + assert found_names, "pyc with expected tag not found in names: {}".format( + glob.glob("__pycache__/*.pyc") + ) + @pytest.mark.skipif('"__pypy__" in sys.modules') def test_pyc_vs_pyo(self, testdir, monkeypatch): testdir.makepyfile(