From 2bc4065a00b52bb185cdd4793cc01be39cacbb63 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Tue, 20 Sep 2011 17:53:07 -0400 Subject: [PATCH] rewrite file newlines when the python parser is picky --- CHANGELOG | 1 + _pytest/assertion/rewrite.py | 9 +++++++++ testing/test_assertrewrite.py | 6 ++++++ 3 files changed, 16 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index ddc3b0f18..998fe3be2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ Changes between 2.1.1 and [NEXT VERSION] ---------------------------------------- +- fix assertion rewriting on files with windows newlines on some Python versions - refine test discovery by package/module name (--pyargs), thanks Florian Mayer - fix issue69 / assertion rewriting fixed on some boolean operations - fix issue68 / packages now work with assertion rewriting diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 0a8e59e2b..3dfa66321 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -38,6 +38,8 @@ else: PYC_EXT = ".py" + "c" if __debug__ else "o" PYC_TAIL = "." + PYTEST_TAG + PYC_EXT +REWRITE_NEWLINES = sys.version_info[:2] != (2, 7) and sys.version_info < (3, 2) + class AssertionRewritingHook(object): """Import hook which rewrites asserts.""" @@ -181,12 +183,19 @@ def _write_pyc(co, source_path, pyc): fp.close() return True +RN = "\r\n".encode("utf-8") +N = "\n".encode("utf-8") + def _rewrite_test(state, fn): """Try to read and rewrite *fn* and return the code object.""" try: source = fn.read("rb") except EnvironmentError: return None + # On Python versions which are not 2.7 and less than or equal to 3.1, the + # parser expects *nix newlines. + if REWRITE_NEWLINES: + source = source.replace(RN, N) + N try: tree = ast.parse(source) except SyntaxError: diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 8d5045105..3a706a8ea 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -357,3 +357,9 @@ def test_optimized(): def test_rewritten(): assert "@py_builtins" in globals()""") assert testdir.runpytest().ret == 0 + + def test_translate_newlines(self, testdir): + content = "def test_rewritten():\r\n assert '@py_builtins' in globals()" + b = content.encode("utf-8") + testdir.tmpdir.join("test_newlines.py").write(b, "wb") + assert testdir.runpytest().ret == 0