首页 > 编程问答 >从 PyCharm IDE 运行测试时未找到 Pytest 夹具

从 PyCharm IDE 运行测试时未找到 Pytest 夹具

时间:2024-07-22 14:51:17浏览次数:9  
标签:python pycharm pytest python-decorators pytest-fixtures

我的项目中的 pytest 装置遇到问题。我有一个根 conftest.py 文件,其中包含一些通用固定装置和用于特定测试的隔离 conftest.py 文件。文件夹结构如下:

product-testing/
├── conftest.py  # Root conftest.py
├── tests/
│   └── grpc_tests/
│       └── collections/
│           └── test_collections.py
└── fixtures/
    └── collections/
        └── conftest.py  # Used by test_collections.py specifically

当我尝试使用测试函数附近的“运行按钮”从 IDE (PyCharm) 运行测试时,pytest 无法从根目录初始化装置 conftest.py 测试代码是这样的:

import datetime
import allure
from faker import Faker
from fixtures.collections.conftest import collection

fake = Faker()

@allure.title("Get list of collections")
def test_get_collections_list(collection, postgres):
    with allure.step("Send request to get the collection"):
        response = collection.collection_list(
            limit=1,
            offset=0,
            # ...And the rest of the code
        )

这是来自 fixtures/collection/

import datetime
import pytest

from faker import Faker
from path.to.file import pim_collections_pb2

fake = Faker()


@pytest.fixture(scope="session")
def collection(grpc_pages):
    def create_collection(collection_id=None, store_name=None, items_ids=None, **kwargs):
        default_params = {
            "id": collection_id,
            "store_name": store_name,
            "item_ids": items_ids,
            "is_active": True,
            "description_eng": fake.text(),
            # rest of the code

的竞赛,这是根 conftest.py 文件

import pytest
from faker import Faker

from pages.manager import DBManager, GrpcPages, RestPages

fake = Faker()


@pytest.fixture(scope="session")
def grpc_pages():
    return GrpcPages()


@pytest.fixture(scope="session")
def rest_pages():
    return RestPages()


@pytest.fixture(scope="session")
def postgres():
    return DBManager()

#some other code

我得到的错误消息是:

test setup failed
file .../tests/grpc_tests/collections/test_collections.py, line 9
    @allure.title("Create a multi-collection")
    def test_create_multicollection(collection, postgres):

file .../fixtures/collections/conftest.py, line 10
    @pytest.fixture(scope="session")
    def collection(grpc_pages):
E       fixture 'grpc_pages' not found
>       available fixtures: *session*faker, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, collection, doctest_namespace, factoryboy_request, faker, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

但是,当我通过终端用 pytest . ,没有错误。似乎 pytest 在一种情况下可以看到根 conftest.py ,但在另一种情况下却看不到。

我尝试直接从根 conftest.py 显式导入缺失的装置来解决该问题。这适用于单个测试运行,但在使用像 pytest . 这样的 CLI 命令运行所有测试时会导致错误,并出现以下错误:

```
ImportError while importing test module '/path/to/test_collections.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
.../importlib/init.py:127: in import_module
    return bootstrap.gcd_import(name[level:], package, level)
tests/.../test_collections.py:6: in <module>
    from conftest import grpc_pages
E   ImportError: cannot import name 'grpc_pages' from 'conftest' (/path/to/fixtures/users/conftest.py)
```

感觉 pytest 正在尝试在隔离的 grpc_pages 而不是根目录中查找 conftest.py 文件。

此外,当导入不明确时,可以通过像

  • pytest -k "test_create_multicollection" ./tests/grpc_tests/collections/
  • pytest path/to/test_collections.py::test_create_multicollection

这样的命令运行隔离测试。但是,我需要让 IDE 中的 run 按钮为经验不足的非技术团队成员工作。

所以我的问题是:

  1. 是否有人遇到过 PyCharm 无法从root conftest.py 运行单个测试时,但 pytest 可以从命令行运行?
  2. 如何修复此问题,以便 PyCharm 的运行按钮和命令行 pytest 一致工作?

其他上下文

  • Pytest 版本:pytest 7.4.4
  • PyCharm 版本:2023.2.1
  • Python 版本:3.9.6

提前感谢您的帮助!


问题出在 PyCharm 如何创建测试运行配置,而不是 pytest 本身。当你使用 PyCharm 中测试函数旁边的“运行”按钮时,它会创建一个使用测试文件所在的目录作为测试根目录的运行配置。这意味着 pytest 只会搜索该目录及其子目录中的 conftest.py 文件,而不会搜索你的项目根目录。

你可以通过两种方法解决这个问题:

方法 1:修改运行配置

  1. 像往常一样点击测试函数旁边的“运行”按钮。
  2. 在出现的运行配置窗口中,找到“测试”部分。
  3. 将“目标”字段从文件名改为项目根目录。你可以使用“...”按钮进行浏览。
  4. 勾选“使用 pytest 选项运行配置”选项。
  5. 点击“应用”保存更改。

现在,当你使用这个运行配置时,pytest 将会从你的项目根目录开始搜索,从而找到根 conftest.py 文件中的 fixtures。

方法 2:修改 PyCharm 默认测试运行配置

  1. 打开 PyCharm 的设置(File > Settings 或 Ctrl+Alt+S)。
  2. 导航到“工具”>“Python 集成工具”>“测试”。
  3. 选择“pytest”。
  4. 勾选“默认使用 pytest 选项运行配置”。
  5. 在“默认测试运行器选项”字段中添加 --rootdir= 并将你的项目根目录路径粘贴在后面。
  6. 点击“应用”保存更改。

这样一来,所有新创建的 pytest 运行配置都会默认使用项目根目录作为测试根目录,并且你不再需要为每个测试单独修改配置。

额外建议:

为了更清晰地组织你的测试代码,你可以考虑删除子目录中的 conftest.py 文件,并将所有 fixtures 集中到项目根目录下的 conftest.py 文件中。这可以避免 pytest 搜索路径的混乱,并使你的代码更易于维护。

如果你确实需要在子目录中定义 fixtures,请确保它们不会与根 conftest.py 文件中的 fixtures 发生名称冲突,并考虑使用更明确的命名来区分它们,例如使用模块名作为前缀。

标签:python,pycharm,pytest,python-decorators,pytest-fixtures
From: 78752644

相关文章

  • python pip 需要构建工具,而它已经安装
    我看到这个问题已经被发布了很多次,人们设法解决了这个问题,但我没有!!操作系统版本:Windows1021H1Build19043.1288Python版本:Python3.9.7(tags/v3.9.7:1016ef3,Aug302021,20:19:38)[MSCv.192964bit(AMD64)]onwin32Pip、wheel和setuptool都可以日期:......
  • 无法在浏览器中访问Python 127.0.0.1:8000上的本地主机
    fromdjango.contribimportadminfromdjango.urlsimportpath,includeurlpatterns=[path('admin/',admin.site.urls),path('products/'),include('products.urls')#thisline]嗨,任何人。很抱歉问这样的问题,但这是我第一次尝试python。......
  • 在 VSCode 中通过 Python 使用 YouTube API 时如何启用 Intellisense
    我想在使用GoogleYouTubeAPI和Python时在VSCode中获得IntelliSense。但我不知道详细步骤。fromgoogleapiclient.discoveryimportbuildapi_key="****"youtube=build("youtube","v3",developerKey=api_key)request=youtube.channels().list(part......
  • 当 python 脚本通过 jenkins + Github 在 Windows 本地计算机上运行时,chrome 浏览器不
    我的Python代码是(windowsMachine)fromseleniumimportwebdriverprint("newLine")print("2Line")print("3Line")holdChrome=webdriver.ChromeOptions()holdChrome.add_experimental_option("detach",True)#Restricta......
  • python_基础_数据类型
    基础数据类型不需要声明,只有被赋值后才会创建变量。变量本身没有类型,“类型”指的是所存值的类型。类型判断type(x)和isinstance(x,int)前者不会认为子类是一种他的父类类型后者会认为子类是父类类型>>>classA:...pass...>>>classB(A):...pass......
  • IPython 使用技巧
    IPython是一个强大的交互式Pythonshell,提供了许多方便的功能,使Python编程更加高效和愉快。本文将介绍一些IPython的实用技巧,帮助开发者充分利用其功能,提高编程效率。1.基本操作和快捷键1.1启动IPython可以通过在终端输入以下命令来启动IPython:ipython启动后,你......
  • 【python】类方法和静态方法的区别
    类方法和静态方法在Python中都可以用来定义与类相关的功能,但它们有不同的使用场景和优缺点。虽然类方法也可以用来实现验证逻辑,但静态方法在某些情况下更合适。让我们详细看看这两种方法的区别以及为什么在某些情况下静态方法可能更适合验证功能。类方法和静态方法的区别类......
  • Python自动化:一键提取千万个Excel指定数据
    一、传统方法的局限性打开每个Excel文件,逐个查找需要的数据。筛选出老板需要的数据列。复制并粘贴到新的工作表中。保存并关闭每个文件。这个过程不仅耗时,而且容易出错。每一次的筛选都可能遗漏数据,每一次的复制粘贴都可能引入错误。二、Python自动化的解决方案i......
  • Python:提交和跟踪许多子流程会导致“卡住”子流程
    我有一个第3方cli可执行文件,需要从python代码中调用。这些都是繁重的计算(CPU),我需要调用它大约50-100次。可执行文件本身在某种程度上是多线程的,但不是所有步骤,而且我有很多可用的核心。这意味着我希望同时运行多个子进程,但不是全部。因此,我需要提交其中一些,然后跟踪......
  • PyCharm远程部署带屏幕影响串口
    我有一个Flaskapp.py,我正在本地计算机上开发。Flask应用程序使用连接到远程计算机的串行接口(pyserial)。我设置PyCharm以在远程计算机上进行远程部署机器。当我远程(从本地机器)部署和运行应用程序时,我想在独立的screen中启动它,以便我可以在需......