我有一个应用程序,我想使用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_dir
和src
目录测试应用程序。
我尝试将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
答案 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