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 函数内的条件均执行了
相关推荐
Da Da 泓4 天前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
会开车的鸟哥5 天前
自动创建测试用例与组件测试向导
测试用例·simuinktest
螺丝钉tina5 天前
[Playwright][08] Upload 模块自动化:如何设计真实业务测试用例?
运维·自动化·测试用例
TomEval6 天前
【测AI】第22篇:Agent 系统测试方法 — AI 学会“动手“了
人工智能·python·prompt·aigc·测试用例
车软学堂6 天前
CANoe自动化:跑起第一个测试用例
运维·车载系统·自动化·汽车·测试用例
2601_967987377 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
jiangbqing8 天前
测试功能点,测试用例、测试报告全流程技能直接用
功能测试·测试用例·测试用例 测试报告
自动化测试行业观察8 天前
AI智能测试用例生成技术解析:多源融合+LLM混合生成方案与实践
自动化测试·人工智能·科技·测试用例·智能化测试·ai测试平台·ai智能遍历
TomEval8 天前
【测AI】第20篇:大模型安全测试 —— 越狱攻击与防护
人工智能·python·功能测试·ai·aigc·测试用例·安全性测试
Madison-No712 天前
pytest框架
pytest