Travis无法以Python 3变体导入我的测试模块

时间:2016-03-02 19:26:57

标签: python python-2.7 unit-testing python-3.x travis-ci

我正在尝试针对Travis CI上的多个Python变体测试我的应用程序。在Python 2.7中,测试按预期传递。但是,在Python 3.4中我得到了这个追溯

ERROR: tests.test_mymodule (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/opt/python/3.4.2/lib/python3.4/unittest/case.py", line 58, in testPartExecutor
    yield
  File "/opt/python/3.4.2/lib/python3.4/unittest/case.py", line 577, in run
    testMethod()
  File "/opt/python/3.4.2/lib/python3.4/unittest/loader.py", line 32, in testFailure
    raise exception
ImportError: Failed to import test module: tests.test_mymodule
Traceback (most recent call last):
  File "/opt/python/3.4.2/lib/python3.4/unittest/loader.py", line 312, in _find_tests
    module = self._get_module_from_name(name)
  File "/opt/python/3.4.2/lib/python3.4/unittest/loader.py", line 290, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/MyGitHubName/mymodule/tests/test_mymodule.py", line 8, in <module>
    from mymodule import mymodule
  File "/home/travis/build/MyGitHubName/mymodule/mymodule/__init__.py", line 1, in <module>
    from mymodule import MyModule
ImportError: cannot import name 'MyModule'

在Python 3.5中,我得到了这个(类似,但与3.4完全不同)

ERROR: mymodule (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: mymodule
Traceback (most recent call last):
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 462, in _find_test_path
    package = self._get_module_from_name(name)
  File "/opt/python/3.5.0/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/MyGitHubName/mymodule/mymodule/__init__.py", line 1, in <module>
    from mymodule import MyModule
ImportError: cannot import name 'MyModule'

我的测试脚本具有以下导入:

import unittest
from mock import patch
from mymodule import MyModule

在特拉维斯,我试图通过两个

运行测试
python setup.py test

python -m unittest discover

__init__.py的{​​{1}}看起来像这样:

mymodule

from mymodule import MyModule 包含mymodule.py类。

同样,由于导入错误,这些工作在Python 2.7上,但不在3.4或3.5上。我需要调整我的导入以允许我的测试在Python 2.7和Python 3.4 / 3.5中运行?

1 个答案:

答案 0 :(得分:0)

假设你有这样的项目结构:

enter image description here

您确实会收到该错误,因为您应该更明确地了解python3中的导入: Changes in import statement python3

因此,只需将mymodule/__init__.py中的import语句编辑为显式:

from .mymodule import MyModule