我有一连串在 Travis CI 上运行的单元测试,并且只在 PY3.2 上运行。我怎样才能在不使用 Six.u() 的情况下解决这个问题?
def test_parse_utf8(self):
s = String("foo", 12, encoding="utf8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u"hello joh\u0503n")
======================================================================
ERROR: Failure: SyntaxError (invalid syntax (test_strings.py, line 37))
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/travis/build/construct/construct/tests/test_strings.py", line 37
self.assertEqual(s.build(u"hello joh\u0503n"), b"hello joh\xd4\x83n")
^
SyntaxError: invalid syntax
试图让它工作:
PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else s.decode("utf-8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u("hello joh\u0503n"))
引用自https://pythonhosted.org/six/
在 Python 2 上, u() 不知道文字的编码是什么。每个字节直接转换为相同值的 unicode 代码点。因此,只有将 u() 与 ASCII 数据字符串一起使用才是安全的。
但使用 unicode 的全部意义在于不限于 ASCII。