pytest module import ImportError: No module named

pytest module import ImportError: No module named

这个问题已经被问过 DOZENS 次了,但我遇到的每个问题都没有适合我的解决方案。

我正在使用 Python 2.7 和 pytest 进行 运行 测试。

结构如下(来自我的 project/git repo 的根目录):

myapp/
    myapp/
        __init__.py           # def main():
                              #    ... stuff
                              # if __name__ == "__main__":
                              #    main()

        __main__.py           # import __init__ as myapp
                              # myapp.main()

        config.yaml           # (app config file)

        myapplib/
                __init__.py   # (Empty file)

                config.py     # Loads {projectroot}/config.yaml
                              # def cfg(): 
                              #    ... stuff
    tests/
        test_stuff.py         # from myapplib.config import cfg

然后我尝试 运行 tests/test_stuff.py 文件:

cd {projectroot}
pytest

它抱怨:

myapp/tests/test_stuff.py:38: in <module>
    from myapplib.config import cfg
E   ImportError: No module named myapp.config

我尝试过的一些事情:

  1. 使用-m导入myapplibmyapp.myapplib
  2. 从不同的目录开始 pytest(例如,内部测试/)
  3. 在所有其他答案中使用所有路径黑客
  4. 将其更改为 from . import XXX.. 或任何相关导入选项(但这些都失败并显示 ValueError: Attempted relative import in non-package.

毫无价值,应用程序本身在项目目录中运行良好:

cd {projectroot}
python myapp

...所有配置和路径都可以正常工作。只是测试找不到路径。


这是我目前所拥有内容的完整复制:

https://pyfiddle.io/fiddle/4fa60f5a-02df-43bb-8aa3-03e59ff72650/?m=Saved%20fiddle

你是 运行

myapp/tests/test_stuff.py

您需要编辑 test_stuff.py 中的路径以指向 myapp(其中包含 __init__.py

我在我的系统上测试过这个(文件 test_stuff.py):

import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__),os.pardir,"myapp"))
import myapplib

(获取 python 模块的完整路径,然后使用父目录将 python 路径添加到 myapp 的第二层)

在我的 dirtree 上工作,像你的一样配置:

S:\python\myapp\myapp
S:\python\myapp\tests
S:\python\myapp\myapp\myapplib
S:\python\myapp\myapp\myapplib\__init__.py
S:\python\myapp\tests\test_stuff.py

建议:当摆弄sys.path.append()时:

  • 始终使用绝对路径,使用 __file__ 确保当前目录不会妨碍。 从不 取决于当前目录,或者此技巧仅在给定目录中才有效。
  • 调试:打印您要添加的路径以检查它是否正确。因为它是绝对的,所以你很容易看出它是否正确。