zoukankan      html  css  js  c++  java
  • 5.pytest中fixture的使用(scope参数)

    fixture的目的是提供一个固定的基线测试可以可靠的重复执行;

    相当于我们上一篇文章写到的setup和teardown。但是使用起来它不在限于固定的名称,会更加的方便灵活;

    fixture从简单的单元扩展到复杂的功能测试,允许根据配置和组件选项进行参数化,或者跨函数、类、模块或整个测试范围重用。

    本篇文章主要写fixture函数中的scope参数scope参数的值有:function(默认)class session module

    1.如何创建一个fixture函数

    import pytest
    
    #通过装饰器的方式编写一个fixture函数,提供安装和拆卸功能
    @pytest.fixture(scope='function')
    def fix_test():
        print('----- 我是fixture函数 -----')
    
    # 通过参数的形式将fixture函数传入到测试函数中,用来实现fixture函数
    def test1(fix_test):
        print('我是第一个测试用例')
        print('我需要依赖fixture函数')
    
    def test2():
        print('我是第二个测试用例')
        print('我不需要依赖fixture函数')
    
    def test3(fix_test):
        print('我是第三个测试用例')
        print('我需要依赖fixture函数')

    执行结果可以清楚的看到三个测试用例执行其中第一个和第三个是执行了fixture函数。第二个测试用例没有执行fixture函数

     2.上面例子只看到了fixture实现了安装功能,并没有实现拆卸功能。如果想要fixture函数中实现拆卸功能或者测试用例中需要将fixture函数提供一个值,则需要用到yield关键字。

    import pytest
    
    #通过装饰器的方式编写一个fixture函数,提供安装和拆卸功能
    @pytest.fixture(scope='function')
    def fix_test():
        print('----- 创建浏览器驱动器对象 -----')
        # 在我们的自动化测试中都需要用到浏览器驱动器对象。
        # 在fixture函数中更多的使用的是yield关键字来返回
        driver = 'Chrome'
        yield driver
        # 在yield关键字后则是我们的拆卸功能
        print('销毁浏览器驱动器对象')
    
    # 通过参数的形式将fixture函数传入到测试函数中,用来实现fixture函数
    def test1(fix_test):
        print('打开百度')
    
    
    def test2():
        print('我是第二个测试用例')
        print('我不需要依赖fixture函数')
    
    def test3(fix_test):
        print('打开淘宝')

     3.conftest.py文件的编写

    在整个测试过程中如果想要实现fixture函数跨类或模块使用,则可以将fixture函数写到conftest.py文件中,在测试模块中不需要导入conftest.py文件,pytest会自动发现它;

    注意:1.conftest.py文件名不可修改;2.conftest.py文件必须和测试模块在同一个package内,且这个package有__init__.py文件;

    conftest.py文件
    
    # scope参数的值为class则是类级别的fixture函数,和setup_class teardown_class 执行相同
    # scope参数的值为session和module的区别
    # 为session时fixture函数作用域整个测试,为module时fixture作用于测试的每个模块 @pytest.fixture(scope
    ='session') def fix_test(): print('----- 创建浏览器驱动器对象 -----') driver = 'Chrome' yield driver print('销毁浏览器驱动器对象')
    第一个测试模块
    
    class Test_web():
    
        def test1(self,fix_test):
            print('%s-----打开京东'%fix_test)
    
        def test2(self,fix_test):
            print('%s-----打开唯品会' % fix_test)
    第二个测试模块
    
    def test1(fix_test):
        print('%s-----打开百度'%fix_test)
    
    
    def test2():
        print('我是第二个测试用例')
        print('我不需要依赖fixture函数')
    
    def test3(fix_test):
        print('%s-----打开淘宝'%fix_test)

  • 相关阅读:
    [luogu2059 JLOI2013] 卡牌游戏 (概率dp)
    [luogu1772 ZJOI2006] 物流运输 (最短路 线性dp)
    [luogu 2568] GCD (欧拉函数)
    [poj 2976] Dropping tests (分数规划 二分)
    cf掉分记——Avito Code Challenge 2018
    新博客的第一篇博文~
    [noip2011 luogu1312] Mayan游戏(模拟)
    bzoj2618 [Cqoi2006]凸多边形
    LLppdd never give up!
    我的scoi2018
  • 原文地址:https://www.cnblogs.com/XhyTechnologyShare/p/12259751.html
Copyright © 2011-2022 走看看