Pytest 测试用例生命周期管理-自动生效(autouse)

autouse 简介

在自动化测试中,fixture 可以用于自动生效(autouse),它们会自动在每个测试用例运行前自动调用,而无需在测试用例中显式引用 Fixture。这对于执行通用的测试前和测试后操作非常有用。


autouse 参数与 yield 关键字的区别

  • yield 解决的是「怎么清理」

  • autouse=True 解决的是「清理会不会被执行」

pytest 不会主动执行 fixture,fixture 只有在 被使用时才会执行,而 autouse=True 的本质作用即pytest 会在每个测试生命周期节点自动插入这个 fixture。


autouse 的作用本质

  • 创建一个 fixture 函数

    python 复制代码
    @pytest.fixture(autouse=True)
    def clean_env():
  • autouse 的作用本质是调用如上代码时不需要显试调用,默认直接测试函数调用了 fixture 函数

    python 复制代码
    def test_search():

autouse 参数的使用场景

  • 不想原测试⽅法有任何改动,或全部都⾃动实现⾃动应⽤,没有特例,也都不需要 yield 给返回值时可以选择⾃动应⽤。

代码示例

  • 代码示例

    python 复制代码
    import pytest
    
    @pytest.fixture(scope="class", autouse=True)
    def login():
        # setup 操作
        print("输入密码")
        username = "user"
        password = 'Aa123456'
        yield #username, password  # 相当于return
        # teardown 操作
        print("退出操作")
    
    def test_search():
        # username, password = login
        # print(f"password: {password} , username : {username}")
        print("搜索")
    • 运行结果:由结果可见,没有调用 fixture 函数,但 fixture 函数内的条件均执行了
相关推荐
我的xiaodoujiao14 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
测试老哥1 天前
接口自动化测试分层设计与实践总结
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
AC赳赳老秦3 天前
招投标公开数据自动化采集实战:基于 OpenClaw 的定时抓取与业务关键词精准推送
运维·服务器·数据库·自动化·测试用例·deepseek·openclaw
一孤程4 天前
Pytest+Selenium搭建自动化框架-保姆级实战教程
selenium·自动化·pytest
天才测试猿5 天前
Selenium自动化测试网页加载太慢怎么解决?
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
BullSmall6 天前
大模型基础测试用例库完整编写方案 + 核心注意事项
测试用例
名字还没想好☜8 天前
用 pytest fixture 组织可维护的测试:告别一堆重复的 setUp
数据库·python·oracle·pytest·测试
一孤程8 天前
AI辅助测试用例生成实战——用大模型把测试设计效率提升300%
人工智能·测试工具·ai·aigc·测试用例·测试·测试覆盖率