fix coding cookie detection logic

This commit is contained in:
Benjamin Peterson 2013-10-05 15:03:04 -04:00
parent 4bfbe7ec22
commit 33b663e03d
3 changed files with 15 additions and 4 deletions

View File

@ -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
-----------------------------------

View File

@ -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

View File

@ -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