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

时间:2012-04-23 19:38:02

标签: python unit-testing

我有一个应用程序,我想使用unittest进行测试,但我遇到了一些问题。 我的目录结构如下:

root_dir
├── src
│   ├── cmds
│   │   ├── baz.py
│   │   ├── __init__.py
│   │   └── bar.py
│   └── foo.py
└── tests
    ├── cmds.py
    └── __init__.py

我想测试来自baz的{​​{1}}和bar模块,我正在尝试

cmds

但在root_dir> python2.7 -m unittest tests.cmds我无法导入tests.cmds目录中的cmds包。

我该如何做到这一点?

基本上我想从src分别使用root_dirsrc目录测试应用程序。

我尝试将tests附加到src,但是当我从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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

我认为你几乎是对的。但是当您从根目录运行测试时,我的路径('../src')是错误的。也许你可以这样做:

import os
import sys

ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sys.path.append(os.path.join(ROOT, 'src'))

from cmds.baz import about