Skip to content

Commit a5b5090

Browse files
Merge pull request #2070 from nedbat/bug2038
Don't fail if imp can't find the source for a .pyc file. #2038
2 parents a3319ff + 06bb61b commit a5b5090

File tree

4 files changed

+41
-2
lines changed

4 files changed

+41
-2
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ Michael Birtwell
101101
Michael Droettboom
102102
Michael Seifert
103103
Mike Lundy
104+
Ned Batchelder
104105
Nicolas Delaby
105106
Oleg Pidsadnyi
106107
Oliver Bestwalter

CHANGELOG.rst

+6-1
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,17 @@
55

66
*
77

8-
*
8+
* Cope gracefully with a .pyc file with no matching .py file (`#2038`_). Thanks
9+
`@nedbat`_.
910

1011
*
1112

1213
*
1314

15+
.. _@nedbat: https://github.com/nedbat
16+
17+
.. _#2038: https://github.com/pytest-dev/pytest/issues/2038
18+
1419

1520
3.0.4
1621
=====

_pytest/assertion/rewrite.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,12 @@ def find_module(self, name, path=None):
8080
tp = desc[2]
8181
if tp == imp.PY_COMPILED:
8282
if hasattr(imp, "source_from_cache"):
83-
fn = imp.source_from_cache(fn)
83+
try:
84+
fn = imp.source_from_cache(fn)
85+
except ValueError:
86+
# Python 3 doesn't like orphaned but still-importable
87+
# .pyc files.
88+
fn = fn[:-1]
8489
else:
8590
fn = fn[:-1]
8691
elif tp != imp.PY_SOURCE:

testing/test_assertrewrite.py

+28
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import glob
12
import os
3+
import py_compile
24
import stat
35
import sys
46
import zipfile
7+
58
import py
69
import pytest
710

@@ -573,6 +576,31 @@ def test_no_bytecode():
573576
monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
574577
assert testdir.runpytest_subprocess().ret == 0
575578

579+
def test_orphaned_pyc_file(self, testdir):
580+
if sys.version_info < (3, 0) and hasattr(sys, 'pypy_version_info'):
581+
pytest.skip("pypy2 doesn't run orphaned pyc files")
582+
583+
testdir.makepyfile("""
584+
import orphan
585+
def test_it():
586+
assert orphan.value == 17
587+
""")
588+
testdir.makepyfile(orphan="""
589+
value = 17
590+
""")
591+
py_compile.compile("orphan.py")
592+
os.remove("orphan.py")
593+
594+
# Python 3 puts the .pyc files in a __pycache__ directory, and will
595+
# not import from there without source. It will import a .pyc from
596+
# the source location though.
597+
if not os.path.exists("orphan.pyc"):
598+
pycs = glob.glob("__pycache__/orphan.*.pyc")
599+
assert len(pycs) == 1
600+
os.rename(pycs[0], "orphan.pyc")
601+
602+
assert testdir.runpytest().ret == 0
603+
576604
@pytest.mark.skipif('"__pypy__" in sys.modules')
577605
def test_pyc_vs_pyo(self, testdir, monkeypatch):
578606
testdir.makepyfile("""

0 commit comments

Comments
 (0)