python - 为什么pytest-django找不到manage.py?

标签 python django pytest pytest-django

我有一个这样的项目结构:

setup.cfg
integration_tests/
  |----tests.py
src/
  |----manage.py
  |----my_django_app/

还有一个 setup.cfg:

[tool:pytest]
addopts=--tb=short --strict -ra
DJANGO_SETTINGS_MODULE = my_django_app.settings
env = 
    APP_ENV=testing
    USE_SQLITE_DB=True

但是当我导航到该目录结构的顶部并运行 pytest 时,我得到以下信息:

“pytest-django 找不到 Django 项目(找不到 manage.py 文件)。您必须明确地将 Django 项目添加到 Python 路径才能将其拾取。”

如果我改为导航到 /src/ 并运行 pytest,则测试运行没有问题,但很明显,因为我处于下一个级别,所以没有集成测试运行。

根据文档,它似乎应该从您运行 pytest 的位置向下钻取以尝试找到 manage.py:https://pytest-django.readthedocs.io/en/latest/managing_python_path.html#automatic-looking-for-of-django-projects

如果不是这种情况,那么是否有某种方法可以在 setup.cfg 中配置设置以将 src/ 添加到 PYTHONPATH?文档中关于使用 pip 在可编辑模式下安装 src/ 的建议在我们的环境中并不成立。

最佳答案

您可以使用 pytest-pythonpaths pytests 插件。

例子:

[pytest] 
python_paths = your/path/apps your/path/libs

在您的具体情况下:

[tool:pytest]
addopts=--tb=short --strict -ra
DJANGO_SETTINGS_MODULE = my_django_app.settings
env = 
    APP_ENV=testing
    USE_SQLITE_DB=True
python_paths = src

为什么找不到manage.py?

先看看pytest是如何测试发现的。

Conventions for Python test discovery

pytest implements the following standard test discovery:

  • If no arguments are specified then collection starts from testpaths (if configured) or the current directory. Alternatively, command line arguments can be used in any combination of directories, file names or node ids.

  • Recurse into directories, unless they match norecursedirs. In those directories, search for test_*.py or *_test.py files, imported by their test package name.

  • From those files, collect test items: test prefixed test functions or methods outside of class test prefixed test functions or methods inside Test prefixed test classes (without an init method)

因此,manage.py 不符合测试文件的条件,因此不会被自动发现,您需要在 python 路径中运行测试。

关于python - 为什么pytest-django找不到manage.py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601828/

相关文章:

Django 身份验证 Mongodb

python - 检查在测试期间是否调用了 pytest fixture 一次

python - 使用 pytest 测试日志输出

python - 函数自行运行,但不在类中运行

python - 如何制作可以下载带有各自URL的图像的图像爬虫

python - Tensorflow:BeamSearchDecoder 的问题 - dynamic_decode

django - 在后台运行 django 时创建的两个进程

python - Django 自定义用户管理员 change_password

python-3.x - 如何将python dict转换为DictRow对象

python - PowerShell 将环境变量设置为子表达式会丢弃换行符