From 33b663e03d7673fc92d7dee27c845d0431890b44 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Sat, 5 Oct 2013 15:03:04 -0400 Subject: [PATCH] fix coding cookie detection logic --- CHANGELOG | 5 +++++ _pytest/assertion/rewrite.py | 6 +++--- testing/test_assertrewrite.py | 8 +++++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index dbf4d1341..69bf7e9ee 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +Changes between 2.4.2 and 2.4.3 +----------------------------------- + +- In assertion rewriting mode on Python 2, fix the detection of coding cookies. + Changes between 2.4.1 and 2.4.2 ----------------------------------- diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 96b1a33d3..8ef27ac15 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -196,7 +196,7 @@ def _write_pyc(state, co, source_path, pyc): RN = "\r\n".encode("utf-8") N = "\n".encode("utf-8") -cookie_re = re.compile("coding[:=]\s*[-\w.]+") +cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+") BOM_UTF8 = '\xef\xbb\xbf' def _rewrite_test(state, fn): @@ -220,8 +220,8 @@ def _rewrite_test(state, fn): end1 = source.find("\n") end2 = source.find("\n", end1 + 1) if (not source.startswith(BOM_UTF8) and - (not cookie_re.match(source[0:end1]) or - not cookie_re.match(source[end1:end2]))): + cookie_re.match(source[0:end1]) is None and + cookie_re.match(source[end1:end2]) is None): if hasattr(state, "_indecode"): return None # encodings imported us again, we don't rewrite state._indecode = True diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 82fe9a366..fa2d5380f 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -441,7 +441,6 @@ class TestAssertionRewriteHookDetails(object): '* 3 passed*', ]) - @pytest.mark.skipif("sys.version_info[0] >= 3") def test_assume_ascii(self, testdir): content = "u'\xe2\x99\xa5'" @@ -450,6 +449,13 @@ class TestAssertionRewriteHookDetails(object): assert res.ret != 0 assert "SyntaxError: Non-ASCII character" in res.stdout.str() + @pytest.mark.skipif("sys.version_info[0] >= 3") + def test_detect_coding_cookie(self, testdir): + testdir.tmpdir.join("test_utf8.py").write("""# -*- coding: utf-8 -*- +u"St\xc3\xa4d" +def test_rewritten(): + assert "@py_builtins" in globals()""", "wb") + assert testdir.runpytest().ret == 0 def test_write_pyc(self, testdir, tmpdir, monkeypatch): from _pytest.assertion.rewrite import _write_pyc