zoukankan      html  css  js  c++  java
  • pytest 框架之中的 fixture 的使用

    pytest.fixture 使用说明:
    1,函数之间的通信是通过 pytest.fixture来实现的
    2,pytest.fixture 可以实现在函数、类、模块或整个测试会话范围内重复使用fixture
    3,request 使用fixture标记函数后,函数将默认接入一个request参数,它将包含使用该fixture函数的函数信息
    在一个文件之中 pytest 运行流程!(以下步骤是根据以下实例来讲解,如果遇到其他,请参考!)
    1,首先 寻找 test_ 函数,pytest找到了测试函数 test_say
    2,测试函数需要一个名为 what 的函数参数,可以放在本文件之中 也可以放在 conftest.py 之中
    3,what 就是 被@pytest.fixture 装饰的函数!
    4,调用 what 来创建一个实例。
    在 conftest.py 之中定义 fixture 实例
    复制代码
    import pytest
    import smtplib
    
    # scope="module" 表明每个测试模块只能调用一次修饰的smtp fixture函数
    # scope='module'  一般用于网络请求之中
    @pytest.fixture(scope="module")
    def what():
        return 'hello'
    
    # 当所有的测试完成之后会调用 yield(不在使用 return)
    @pytest.fixture(scope="module")
    def file1():
        # 使用 with 完成 连接的关闭!
        with open("1.txt", 'wb') as file:
            file.write('hello file1')
            yield file
            print('测试完成')
    
    #也可以使用 request.addfinalizer 来完成 测试完最后的工作!
    # request.scope= module 将 fixture参数都封装为 request 属性!
    # 可以增加 params 属性实现多次 请求!
    @pytest.fixture(scope="module",params=["smtp.qq.com", "mail.python.org"])
    def smtp(request):
        smtp = smtplib.SMTP(request.param, 587, timeout=5)
        def fin():
            print("执行结束!")
            smtp.close()
        def fin1():
            print('this ok!')
        request.addfinalizer(fin)
        request.addfinalizer(fin1) #可以注册多个 功能比 yield 强大!
        return smtp
    复制代码
    新建文件 test_fix.py
    复制代码
    import pytest
    
    # pytest会从conftest.py文件之中搜索 如果你放在 conftest 之中
    # 函数传参 只能传 被 fixture 装饰的函数!这是一个很坑的地方
    def test_say(what):
        print(what)
        assert 1 # for demo purposes
    
    # 在此时就能体现 scope="module" 的作用 重用了当前模块上一个的实例 速度会加快
    #两个测试函数的运行速度与单个测试函数一样快
    # 一般用在网络请求之中
    def test_say1(what):
        print(what)
        assert 1 # for demo purposes
    
    def test_ehlo(file1):
        print('it come from test_fixture_t')
    
    def test_noop(smtp):
        assert 0  # for demo purposes
    复制代码
  • 相关阅读:
    java jni 调用c语言函数
    BeautifulSoup入门
    Python单引号、双引号、三个双引号的区别
    Request库的安装与使用
    awk命令入门
    sed命令入门
    编译生成protobuf的jar包
    编辑crontab添加Linux计划任务
    tar命令详解及使用实例
    MySQL用户管理
  • 原文地址:https://www.cnblogs.com/gaidy/p/13175600.html
Copyright © 2011-2022 走看看