在 Travis 上运行测试时语法无效



每次提交时,我都遇到了特拉维斯的问题。我的测试适用于本地,但在特拉维斯上我收到此错误:

Traceback (most recent call last):
  File "/opt/python/3.2.5/lib/python3.2/unittest/case.py", line 370, in _executeTestPart
    function()
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 32, in testFailure
    raise exception
ImportError: Failed to import test module: test.test_parser
Traceback (most recent call last):
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 261, in _find_tests
    module = self._get_module_from_name(name)
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 239, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/davidmogar/genderator/test/test_parser.py", line 5, in <module>
    import genderator
  File "/home/travis/build/davidmogar/genderator/genderator/__init__.py", line 3, in <module>
    from genderator.parser import Parser
  File "/home/travis/build/davidmogar/genderator/genderator/parser.py", line 5, in <module>
    from .utils import Normalizer
  File "/home/travis/build/davidmogar/genderator/genderator/utils.py", line 63
    u'N{COMBINING TILDE}'
                        ^
SyntaxError: invalid syntax

下面是该行所在的代码:

def remove_accent_marks(text):
        good_accents = {
            u'N{COMBINING TILDE}',
            u'N{COMBINING CEDILLA}'
        }
        return ''.join(c for c in unicodedata.normalize('NFKD', text)
                       if unicodedata.category(c) != 'Mn' or c in good_accents)

我不知道问题是什么,因为正如我所说,所有测试都在本地工作。这是我的.travis.yml文件:

language: python
python:
  - "3.2"
  - "3.3"
  - "3.4"
script: python -m unittest discover

知道吗?

Python 3

中的u'...'语法仅在 Python 3.3 及更高版本中受支持。

u前缀仅用于支持多语言 Python 代码(同时支持 2 和 3),如果您不需要支持 Python 2,则可以安全地删除。

如果你需要同时支持 Python 2 3.2,则必须使用不同的方法。您可以使用from __future__导入使 Python 2 中的所有字符串文本生成unicode字符串对象;这适用于每个模块:

from __future__ import unicode_literals
def remove_accent_marks(text):
    good_accents = {
        'N{COMBINING TILDE}',
        'N{COMBINING CEDILLA}'
    }

这些字符串在 Python 2 和 3 中都将被视为 Unicode。

或者你可以创建自己的多语言函数:

import sys
if sys.version_info[0] < 3:
    u = lambda s: unicode(s.replace(r'\', r'\\'), "unicode_escape")
else:
    u = lambda s: s

并在所有 Unicode 字符串上使用它:

def remove_accent_marks(text):
    good_accents = {
        u('N{COMBINING TILDE}'),
        u('N{COMBINING CEDILLA}')
    }

或者,您可以使用six库为您生成该桥:

import six
def remove_accent_marks(text):
    good_accents = {
        six.u('N{COMBINING TILDE}'),
        six.u('N{COMBINING CEDILLA}')
    }

你可能想阅读 Python 移植 HOWTO。

最新更新