4

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

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

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

root_dir> python2.7 -m unittest tests.cmds

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

我怎样才能使这项工作?

基本上我想分别从和root_dir目录测试应用程序。srctests

我尝试附加src到,但是当我从中sys.path导入时,我仍然从单元测试中得到一个。cmds.baztests/cmds.pyAttributeError: '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'
4

2 回答 2

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
于 2012-04-24T12:15:10.047 回答
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
于 2012-04-24T12:15:03.820 回答