• pytest--fixture的使用(前置、后置)



    一、fixture定义

    fixture是处理前后置处理的,也叫测试固件,只需要使用@pytest.fixture() 即可定义

    @pytest.fixture()  # fixture装饰器
    def first(): # 定义一个函数
        print("setup...") # 函数内容
    
    
    • 1
    • 2
    • 3
    • 4

    二、fixture前置处理

    定义好fixture函数后,如何应用呢?通常我们只需要在测试函数中,传入Fixture的这个函数名即可

    import pytest  # 导入pytest
    
    @pytest.fixture()
    def first():
        print("setup...")
    
    def test_pytest(first):  # 定义测试函数,在此处引用fixture函数名即可
        print("first test")
    
    
    if __name__ == '__main__':  # 定义主函数
        pytest.main()  # 调用pytest
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    说明:在执行test_pytest函数之前,会先执行first函数,因为first是前置函数,会在测试函数之前执行。如果需要每个测试函数都自动执行,则可以设置autouse的参数为True,即autouse=True

    @pytest.fixture(autouse=True) # 传入autouse参数
    def first():
        print("setup...")
    
    
    • 1
    • 2
    • 3
    • 4

    三、Fixture的作用域

    @pytest.fixture()中scope参数是控制Fixture的作用域的,可根据实际需要,调整运行方式,scope支持以下四种作用域,从大到小依次是:

    session (会话)

    module (模块)

    class (类)

    function (函数)

    fixture默认的scope=function,所以我们不传的时候,默认对测试函数生效
    将scope指定为class,可以实现每个测试类前执行一次
    module指的是,在某个py文件执行前,执行一次,一个py文件就是一个模块
    session是指pytest的会话,即所有的测试执行开始到结束,只会执行一次的操作

    四、Fixture的全局作用域

    如果想在多个py文件中都可以引用这个前置操作,那么可以使用公共文件进行处理,即conftest.py,这个是固定文件名称,不可修改。
    这个文件在pytest中被大量使用,用于定义一些Hook相关函数以及注册全局的Fixture函数。定义在conftest.py中的Fixture,都是全局的Fixture,可以在多个py文件中去使用
    conftest.py

    @pytest.fixture(autouse=True) # 传入autouse参数
    def first():
        print("setup...")
    
    • 1
    • 2
    • 3

    test_first.py

    def test_pytest(first):  # 定义测试函数,在此处引用fixture函数名即可
        print("first test")
    
    • 1
    • 2

    五、Fixture的后置处理

    fixture的后置处理直接使用yield即可,可以帮助我们来做分割,在yield之前的属于setup,而之后的就是teardown。

    @pytest.fixture()
    def first():
        print("setup...")
        yield
        print("teardown...")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    说明:yield后的内容是执行完测试用例才会执行的,放在最后

  • 相关阅读:
    将 RDBMS 恐龙迁移到云端
    IO的演进
    pc端字体为什么到12像素以后不生效
    以目录创建的conda环境添加到jupyter的kernel中
    NLP之Bi-LSTM(在长句中预测下一个单词)
    java并发编程学习五——volatile
    J2EE从入门到入土03.Set集合
    拓扑排序板子练习
    java:application.properties的详细使用以及区分环境
    会议审批 查询&会议签字
  • 原文地址:https://blog.csdn.net/weixin_44688529/article/details/126700424