【pytest官方文档学习】覆盖全局变量的示例代码在8.2.x版本运行报错

我们经常会在conftest.py中定义一些fixture提供给测试方法使用,但是在有些测试中,我们用不上或者需要对其结果进行处理后再用,这时候,就需要我们对fixture进行覆盖或重写。

在学习pytest-8.2.x官方文档看到了它给出的覆盖全局fixture的示例如下:

python 复制代码
tests/
    conftest.py
        # content of tests/conftest.py
        import pytest

        @pytest.fixture
        def username():
            return 'username'

    test_something.py
        # content of tests/test_something.py
        def test_username(username):
            assert username == 'username'

    subfolder/
        conftest.py
            # content of tests/subfolder/conftest.py
            import pytest

            @pytest.fixture
            def username(username):
                return 'overridden-' + username

        test_something_else.py
            # content of tests/subfolder/test_something_else.py
            def test_username(username):
                assert username == 'overridden-username'

我们可以看到,在subfolder/conftest.py文件中重写的"username " fixture访问了tests/conftest.py 文件中的"username "。

这种用法官方文档中也给出了解释:"Note that the base or super fixture can be accessed from the overriding fixture easily - used in the example above."说明官方是也是支持这么用的。

但是当我在pycharm中运行的时候,却报错了:

百思不得其解的时候,在网上看到了这位博主的文章【pytest-fixture】十一、覆盖各个级别的fixture_fixture级别-CSDN博客,发现他的运行是成功的,仔细看了他的运行环境,发现pytest版本是6.2.5。莫非是pytest版本问题?

于是,我将环境也换成了他的版本,运行结果真的时PASSED。

这... 嗯...问题记录下来吧~~

相关推荐
小江的记录本4 分钟前
【JVM虚拟机】垃圾回收GC:垃圾收集器:CMS:核心原理、回收流程、优缺点、废弃原因(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·面试·maven
田里的水稻1 小时前
OE_ubuntu26.04与宿主机之间复制粘贴内容
人工智能·python·机器人
jiayong232 小时前
02 创建虚拟环境
python
旺仔来了2 小时前
不联网的Linux下部署python环境
linux·开发语言·python
小江的记录本2 小时前
【JVM虚拟机】垃圾回收GC:垃圾回收算法:标记-清除、标记-复制、标记-整理、分代收集(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·算法·安全·面试
IP搭子来一个2 小时前
爬虫采集大量返回 403、429,到底卡在哪一环?
网络·爬虫·python
deepin_sir2 小时前
06 综合对比与实战选型——到底该用哪个?
python
小江的记录本3 小时前
【JVM虚拟机】垃圾回收GC:垃圾收集器:G1:Region分区、Mixed GC、回收流程、适用场景(高频)(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·spring cloud·面试
智研数智工坊3 小时前
FastAPI+uv+Jinja2+Nuitka 通用Web桌面框架搭建教程|从零搭建可打包迭代的Python开发底座
python·fastapi·uv·nuitka·jinja2·桌面应用开发
Ulyanov3 小时前
用声明式语法重新定义Python桌面UI:QML+PySide6现代开发入门(一)
开发语言·python·算法·ui·系统仿真·雷达电子对抗仿真