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 函数内的条件均执行了
相关推荐
程序员小远18 天前
自动化测试基础知识总结
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
程序员三藏18 天前
Web自动化测试详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
糖果店的幽灵19 天前
软件测试接口测试从入门到精通:Python接口自动化 - pytest测试框架
软件测试·python·功能测试·自动化·pytest·接口测试
oscar99919 天前
AI 测试用例生成:在 Katalon True Platform 中从需求直达执行
人工智能·测试用例·katalon
2601_9618752419 天前
花生十三资料1200题|题库|刷题
conda·pytest·pillow·pip·web3.py·ipython·gunicorn
某人辛木19 天前
Web自动化测试
前端·python·pycharm·pytest
淡漠的蓝精灵21 天前
pytest-xdist:把 pytest 测试分发到多核 CPU 执行
其他·pytest
weixin_3077791322 天前
从脚本执行到智能体协作:AI辅助测试能力的范式重构
运维·开发语言·人工智能·算法·测试用例
jjjava2.023 天前
软件测试与开发全流程解析
java·功能测试·测试用例