• 【PYTEST】第四章Fixture


    知识点:

    • 利用fixture共享数据
    • conftest.py共享fixture
    • 使用多个fixture
    • fixture作用范围
    • usefixture
    • 重命名

    1. 利用fixture共享数据

    test_data中包含了一个fixture名为data,pytest会优先搜索fixture,返回data值

    pytest/ch3/test_one.py

    import pytest
    
    """
    fixture :
        @pytest.fixture
        声明了一个fixture,如果测试函数中用到fixture名,那么pytest会检测到,并且再执行测试用例前,先执行fixture
    """
    
    @pytest.fixture()
    def data():
        return 3
    
    def test_data(data):
        assert data == 4
    

    2. conftest.py

      针对fixture,可以单独放在一个文件里,如果你希望测试文件共享fixture, 那么在你当前的目录下创建conftest.py文件,将所有的fixture放进去,注意如果你只想作用于某一个文件夹,那么在那个文件夹创建contest.py

    pytest/ch3/conftest.py

    import pytest
    import requests
    
    """
    如果想多个测试用例共享fixture,可以单独建立一个conftest.py 文件,可以看成提供测试用例使用的一个fixture仓库
    """
    
    
    @pytest.fixture()
    def login():
        url = 'http://api.shoumilive.com:83/api/p/login/login/pwd'
        data = {"phone": "18860910", "pwd": "123456"}
        res = requests.post(url, data)
        return res.text
    

    pytest/ch3/test_conftest.py

    import json
    
    import pytest
    
    """
    通过conftest 建立公共仓库,testcase获取公共仓库
    """
    @pytest.mark.login
    def test_conftest(login):
        data = json.loads(login)
        print(data['code'])
        assert data['code'] == '200'

    if __name__ == '__main__':
    pytest.main(["--setup-show", "-m", "login", "-s", "-v"])

    3. 使用多个fixture

    pytest/ch3/conftest.py

    @pytest.fixture()
    def one():
        return 1
    
    @pytest.fixture()
    def two():
        return 2
    

    pytest/ch3/test_muti.py

    def test_muti(one, two):
        assert one == two
    

    4. fixture 作用范围

      用scope来指定作用范围, 作用范围有固定的待选值,fucntion, class, module, session(默认为function)

    5. usefixture

      指定fixture ,使用@pytest.mark.usefixtures('')标记测试函数,或者测试类

    6. 重命名

      如果一个测试命名过长的话,我们可以使用name参数,给她重名了,我们使用fixture的时候,只需要传入name值即可

    @pytest.fixture(name='maoyan')
    def test_maoyan_page_001():
        return 2
    

      

    github: https://github.com/wangxiao9/pytest.git

  • 相关阅读:
    php之面向对象(2)
    PHP ON 阿里云的环境配置攻略
    InitPHP框架搭建高可用WEB应用
    PHP移动互联网开发笔记(6)——MySQL数据库基础回顾[1]
    5 个不用 Bootstrap 的理由
    http中get与post的区别
    django的CSRF保护机制
    博客园项目开发中的难点
    centos7.5静态网页基于nginx建站(python3.6 mysql5.7 nginx安装以及配置)
    python3面向对象常用特性知识点
  • 原文地址:https://www.cnblogs.com/totoro-cat/p/13372865.html
Copyright © 2020-2023  润新知