我有一个要测试使用的应用程序,unittest但是有一些问题。我的目录结构如下:
unittest
root_dir ├── src │ ├── cmds │ │ ├── baz.py │ │ ├── __init__.py │ │ └── bar.py │ └── foo.py └── tests ├── cmds.py └── __init__.py
我想测试中的baz和bar模块,cmds然后尝试做
baz
bar
cmds
root_dir> python2.7 -m unittest tests.cmds
但是在tests.cmds我不能导入cmds我的src目录包。
tests.cmds
src
我该如何工作?
基本上,我想从测试的应用程序root_dir与src和tests单独的目录。
root_dir
tests
我尝试将追加src到sys.path,但是当我cmds.baz从导入时,tests/cmds.py我仍然AttributeError: 'module' object has no attribute 'cmds'从unittest得到一个。
sys.path
cmds.baz
tests/cmds.py
AttributeError: 'module' object has no attribute 'cmds'
编辑:我的导入和sys.path声明是:
import sys sys.path.append('../src') from cmds.baz import about
和回溯:
Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module> main(module=None) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs self.createTests() File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests self.module) File "/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'cmds'
要做的一件非常错误的事情是在上附加一个相对路径sys.path。如果要确定路径,请进行以下操作:
# assuming that the code is in test's __init__.py import os import sys sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__), '../src/') )) # now you can be sure that the project_root_dir/src comes first in sys.path