• Pytest_fixture装饰器、调用fixture的三种方法、usefixtures与传fixture区别、fixture自动使用autouse=True


    1、调用fixture方法1:函数或类的方法直接传fixture的函数参数名称

    import pytest
    
    @pytest.fixture(scope="function")  # 此装饰器相当于 setup_function 的内容
    def some_data():
        print("开始")
        # yield   # 表示此代码之后的语句视为teardown_function的内容
        print("结束")
    
    def test_some_data(some_data):
        print("test")
    
    if __name__ == '__main__':
        pytest.main(['001_Pytest_fixture装饰器_fixtrue_参数化演示_usefixtures与传fixture的区别.py', '-s'])
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2、调用fixture方法2:使用装饰器@pytest.mark.usefixtures()修饰需要运行的用例。

    import pytest
    
    @pytest.fixture()
    def test1():
        print('\n开始执行用例1')
    
    @pytest.mark.usefixtures('test1')
    def test_2():
        print('\n开始执行用例2')
    
    if __name__ == '__main__':
        pytest.main(['test.py', '-s'])
    # 输出:
    # 开始执行用例1
    # 开始执行用例2.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3、调用fixture方法3:叠加usefixtures。

    # 如果一个方法或class用例想要同时调用多个fixture,可以使用@pytest.mark.usefixture()进行叠加。
    # 注意:叠加顺序,先执行的放底层,后执行的放上层。
    import pytest
    
    @pytest.fixture()
    def test1():
        print('开始执行用例1')
    
    @pytest.fixture()
    def test2():
        print('开始执行用例2')
    
    @pytest.mark.usefixtures('test1')
    @pytest.mark.usefixtures('test2')
    def test_3():
        print('开始执行用例3')
    
    if __name__ == '__main__':
        pytest.main(['test.py', '-s'])
    # 输出:
    # 开始执行用例2
    # 开始执行用例1
    # 开始执行用例3.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    4、usefixtures与传fixture区别

    1、如果fixture有返回值,那么usefixture就无法获取到返回值,这个是装饰器usefixture与用例直接传fixture参数的区别。
    2、当fixture需要用到return出来的参数时,只能把参数名称直接当参数传入。
    3、当不需要用到return出来的参数时,两种方式都可以。
    
    • 1
    • 2
    • 3

    5、fixture自动使用autouse=True

    1、当用例很多的时候,每次都传这个参数,会很麻烦。
    2、fixture里面有个参数autouse,默认是False没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了。
    
    
    • 1
    • 2
    • 3
  • 相关阅读:
    2023 年收入最高的 10 种编程语言 Java 排第 10 位
    信息增益,经验熵和经验条件熵——决策树
    【JavaScript】JQuery基础使用
    仅需三行代码! C# 快速实现PDF转PPT
    qt designer加载自定义组件
    GNU LD脚本命令语言(一)
    install Oracle JDK in Linux:安装oracle JDK in linux
    区分Cookie,Session,Token
    canvas基础简单易懂教程(完结,多图)
    探索一些常见的存储过程奥秘
  • 原文地址:https://blog.csdn.net/weixin_44801980/article/details/125505685