Python 为到Nose的导入路径提供基本目录

Python 为到Nose的导入路径提供基本目录,python,visual-studio-code,nose,Python,Visual Studio Code,Nose,在我的项目中,有一个子目录,其中包含我想进行单元测试的python应用程序。 结构如下: my-project/ python-app/ sometool/ __init__.py foo/ __init__.py aaa.py bar/ __init__.py bbb.py test/ sometool-tests/ foo-tests/

在我的项目中,有一个子目录,其中包含我想进行单元测试的python应用程序。 结构如下:

my-project/
  python-app/
    sometool/
      __init__.py
      foo/
        __init__.py
        aaa.py
      bar/
        __init__.py
        bbb.py
    test/
      sometool-tests/
        foo-tests/
          aaa_test.py
现在,
aaa.py
包含导入,如
import sometool.bar.bbb
,它假设应用程序的基本目录是
python app
,这在我的构建设置中确实是这样

aaa_test.py
显然导入
aaa
进行测试。 但是,当从主项目目录运行
nosetests./python app/sometool/test
时,导入失败,因为
myproject
现在是导入的基本目录,即从那里找不到
sometool.bar.bbb

如果我先将
cd
放入
python应用程序
,然后从那里运行
nosetests./sometool/test
,一切都会正常工作。 但是我想将VisualStudio代码配置为使用快捷方式运行这些测试,并且这些命令似乎总是从项目根目录执行


有没有办法将“基本目录”作为参数传递给Nose?

您可以在nosetests环境中使用上下文提供模块:

my-project/
  python-app/
     ...
  test/
    context.py
context.py:

import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import python-app
然后,您可以在测试中导入
python应用程序
,从上下文模块导入,例如在
aaa_test.py
中:

from tests.context import python-app
from python-app.sometool import foo, bar

这将使nosetests始终能够找到python应用程序,无论它在哪里执行。

谢谢,这很有效!为了不必在所有测试文件中导入
上下文
,我最终将路径操作代码放入
\uuuu init\uuuuuuuuuuuuuupy
(而不是
context.py
)。此外,以这种方式导入
python应用程序似乎不是必要的。