在 Pytest 上找不到 Python 包

标签 python python-3.x pytest

我有以下项目结构:

foo
│
├── foo
│   ├── cli
│   │    ├── tests
│   │    └── __init__.py
│   ├── core
│   │    ├── tests
│   │    └── __init__.py
│   ├── tests
│   │    ├── __init__.py
│   │    └── test_foo.py
│   ├── __init__.py
│   └── foo.py
├── kube
├── requirements
├── ...any-other-non-source-related
└── README.md

foo/foo.py 文件中,我有以下占位符代码:

import cli
import core


def say_hi():
    print('hi')


if __name__ == '__main__':
    say_hi()

在文件 foo/tests/test_foo.py 上,我有以下内容:

from foo import foo


def test_foo():
    foo.say_hi()

    assert False

然后,在 shell 中,我得到以下信息:

$ python foo/foo.py 
hi
$ pipenv run pytest
===================== test session starts =====================
platform linux -- Python 3.7.4, pytest-5.3.1, py-1.8.0, pluggy-0.13.1
rootdir: /xxx/xxx/xxx/xxx/python-project-folder-structures
collected 0 items / 1 error                                                                                                                                                                                         

===================== ERRORS =====================
_____ ERROR collecting foo/tests/test_foo.py _____
ImportError while importing test module '/xxx/xxx/xxx/xxx/python-project-folder-structures/foo/tests/test_foo.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
foo/tests/test_foo.py:1: in <module>
    from foo import foo
foo/foo.py:1: in <module>
    import cli
E   ModuleNotFoundError: No module named 'cli'
!!!!!!! Interrupted: 1 error during collection !!!!!!!
===================== 1 error in 0.05s =====================

有人可以帮忙吗?为什么 Pytest 没有建立我的导入?我尝试了多种方法,即使在 foo 文件夹(根级别)之外使用 tests 文件夹,但错误仍然存​​在。

我发现解决这个问题的唯一方法是将 conftest.py 文件放在代码级别,这样它就会被 pytest 发现。我真的不想这样做,因为我想将测试与源代码分离。

最佳答案

如果有人为此苦苦挣扎,我能够找到解决方案。我从 foo 目录中删除了 __init__.py 文件,给出了以下结构:

foo
│
├── foo
│   ├── cli
│   │    ├── tests
│   │    └── __init__.py
│   ├── core
│   │    ├── tests
│   │    └── __init__.py
│   ├── tests
│   │    ├── __init__.py
│   │    └── test_foo.py
│   └── foo.py
├── kube
├── requirements
├── ...any-other-non-source-related
└── README.md

他们,在 mt 测试中,我现在得到以下结果:

import foo


def test_foo():
    foo.say_hi()

    assert False

我注意到 Pytest 的行为是从测试一直到根目录,识别包。由于 foo 是一个包(带有 __init__.py 文件),因此它会将其作为一个包添加到我的 PATH :)

重要 请注意,import foo 语句涉及 foo.py 文件,而不是 foo 目录。因此,如果您的文件在 foo 目录中名为 boo.py,则导入应为:import boo

关于在 Pytest 上找不到 Python 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120154/

相关文章:

python - 使用 CVXOPT 或 CVXPY 进行凸规划

python-3.x - 如何在 Python 3.7 中验证输入属性

python - 如何解决“PytestDeprecationWarning : pytest. config global is deprecated

python-3.x - 使用 pytest 禁用在控制台上打印日志输出

python - 为什么 Pytest 对 fixture 参数执行嵌套循环

python - 在 Python 中第一次出现模式时搜索 1GB+ 数据字符串的最快方法

python - 如何将 dbus 和 policykit 连接到我在 python 中的函数?

python - 元组列表的频率

python - 为什么 py.test 向后运行模块 doctests?

Python - 组合类的继承