Skip to content

Commit

Permalink
Merge pull request #2070 from nedbat/bug2038
Browse files Browse the repository at this point in the history
Don't fail if imp can't find the source for a .pyc file. #2038
  • Loading branch information
RonnyPfannschmidt committed Nov 22, 2016
2 parents a3319ff + 06bb61b commit a5b5090
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ Michael Birtwell
Michael Droettboom
Michael Seifert
Mike Lundy
Ned Batchelder
Nicolas Delaby
Oleg Pidsadnyi
Oliver Bestwalter
Expand Down
7 changes: 6 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@

*

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

*

*

.. _@nedbat: https://github.com/nedbat

.. _#2038: https://github.com/pytest-dev/pytest/issues/2038


3.0.4
=====
Expand Down
7 changes: 6 additions & 1 deletion _pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ def find_module(self, name, path=None):
tp = desc[2]
if tp == imp.PY_COMPILED:
if hasattr(imp, "source_from_cache"):
fn = imp.source_from_cache(fn)
try:
fn = imp.source_from_cache(fn)
except ValueError:
# Python 3 doesn't like orphaned but still-importable
# .pyc files.
fn = fn[:-1]
else:
fn = fn[:-1]
elif tp != imp.PY_SOURCE:
Expand Down
28 changes: 28 additions & 0 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import glob
import os
import py_compile
import stat
import sys
import zipfile

import py
import pytest

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

def test_orphaned_pyc_file(self, testdir):
if sys.version_info < (3, 0) and hasattr(sys, 'pypy_version_info'):
pytest.skip("pypy2 doesn't run orphaned pyc files")

testdir.makepyfile("""
import orphan
def test_it():
assert orphan.value == 17
""")
testdir.makepyfile(orphan="""
value = 17
""")
py_compile.compile("orphan.py")
os.remove("orphan.py")

# Python 3 puts the .pyc files in a __pycache__ directory, and will
# not import from there without source. It will import a .pyc from
# the source location though.
if not os.path.exists("orphan.pyc"):
pycs = glob.glob("__pycache__/orphan.*.pyc")
assert len(pycs) == 1
os.rename(pycs[0], "orphan.pyc")

assert testdir.runpytest().ret == 0

@pytest.mark.skipif('"__pypy__" in sys.modules')
def test_pyc_vs_pyo(self, testdir, monkeypatch):
testdir.makepyfile("""
Expand Down

0 comments on commit a5b5090

Please sign in to comment.