当 pytest 测试位于新项目的 /tests 目录中时出现 ModuleNotFoundError

ModuleNotFoundError when pytest tests are in /tests directory in new project

我正在尝试尽早将测试引入 Python 3.9 项目,但是我在使用 pytest 时遇到了问题。

test_legacy.py:

from crmpicco.subtasks.legacy import Legacy

def test_is_complete(self):
    legacy = Legacy()
    assert legacy.is_complete(self) == True

我要测试的 class 在 legacy.py:

from crmpicco.subtasks.subtask import Subtask


class Legacy(Subtask):
    def execute(self):
        print("legacy")

    def is_complete(self):
        return True

当我 运行 我得到:

ImportError while importing test module '/private/var/www/crmpicco/crmpicco/tests/test_legacy.py'. Hint: make sure your test modules/packages have valid Python names.

E ModuleNotFoundError: No module named 'crmpicco'

我尝试将 __init__.py 文件添加到我的 /tests 目录,然后再次将其删除,但没有效果

我错过了什么?

pytest tries to find rootdir 可能是 /private/var/www/crmpicco/crmpicco 最简单的方法是 运行 使用 python -m pytest 进行测试,其中 运行 pytest 但添加 .至 PYTHONPATH

为我解决此问题的方法是将 PYTHONPATH 导出添加到我的 shell。

export PYTHONPATH=/var/www/crmpicco/crmpicco