如何从python中的tests模块导入src

Pau*_*aul 2 python unit-testing

我有一个应用程序,我想测试使用,unittest但我有一些问题.我的目录结构如下:

root_dir
??? src
?   ??? cmds
?   ?   ??? baz.py
?   ?   ??? __init__.py
?   ?   ??? bar.py
?   ??? foo.py
??? tests
    ??? cmds.py
    ??? __init__.py
Run Code Online (Sandbox Code Playgroud)

我想测试bazbar模块cmds,我正在尝试

root_dir> python2.7 -m unittest tests.cmds

但是tests.cmds我无法导入cmds我的src目录中的包.

我怎样才能做到这一点?

基本上我想root_dirsrctests目录分别测试应用程序.

我试图追加srcsys.path,但是当我导入cmds.baztests/cmds.py我还是得到一个AttributeError: 'module' object has no attribute 'cmds'从单元测试.

编辑:我的导入和sys.path声明是:

import sys
sys.path.append('../src')
from cmds.baz import about
Run Code Online (Sandbox Code Playgroud)

追溯:

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'
Run Code Online (Sandbox Code Playgroud)

Zau*_*bov 5

一个非常错误的事情是附加相对路径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
Run Code Online (Sandbox Code Playgroud)