python-unittest-ImportError:起始目录不可导入

fra*_*ueh 8 python python-unittest

我正在按照python unittest进行一些测试,并使用发现功能将测试打包到套件中。但是,当我尝试使用unittest运行测试时,出现此错误:

Traceback (most recent call last):
   File "D:/Project/run_tests.py", line 12, in <module>
     suite2 = unittest.defaultTestLoader.discover(dir2, pattern='test*.py')
   File "C:\Python\Python36-32\lib\unittest\loader.py", line 338, in discover
     raise ImportError('Start directory is not importable: %r' % start_dir)
ImportError: Start directory is not importable: 'D:\\Project\\dir2'
Run Code Online (Sandbox Code Playgroud)

这是run_tests.py的样子:

import unittest

if __name__ == "__main__":

    dir1 = "./test1"
    suite1 = unittest.defaultTestLoader.discover(dir1, pattern='test*.py')
    runner1 = unittest.TextTestRunner()
    runner1.run(suite1)


    dir2 = "./tes2"
    suite2 = unittest.defaultTestLoader.discover(dir2, pattern='test*.py')
    runner2 = unittest.TextTestRunner()
    runner2.run(suite2)
Run Code Online (Sandbox Code Playgroud)

Dou*_*Liu 8

发生了非常类似的错误,但没有任何符号链接。

这是我的目录布局。

- project root
  - foo
  - bar
  - test
Run Code Online (Sandbox Code Playgroud)

foo和bar被认为是顶级程序包,其中所有测试用例都在其中进行测试。

在intellij中运行unittest时,我使用了以下参数:

  • 目标:脚本路径设置为test文件夹
  • 工作目录是项目的根源。

此设置给了我Start directory is not importable错误。

我在unittest.loader.py中跟踪了源,并意识到它检查了测试文件夹中的__init__.py。因此解决方案是__init__.py在我的test文件夹中添加一个。希望这对某人有帮助。

-编辑-

我在python 3.6,mac osx上

  • 添加 `_init__.py` 文件解决了我的问题,谢谢 (3认同)

Jam*_*ury 3

这里有一个类似的问题,有一个有用的答案

但是,如果您在 Linux 中使用像 PyCharm 这样的 IDE 并在软链接目录中打开文件,则可能会发生这种情况。运行测试的编辑器似乎对同一模块的两条路径感到困惑,并说其中一条不存在。将所有内容放在一个位置而不使用任何软链接为我解决了这个问题。