zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    系统学Python-01
    pandas(二)
    matplotlib
    Python数据分析-初识numpy、pandas、scipy、matplotlib和Scikit-Learn等数据处理库
    Python进行读取或写入等文件操作时的路径问题
    pandas(一)
    00 Python及第三方库的安装问题
    sorted ()函数和列表中的sort()函数
    git 获取branch名和commit id
    查看Android log 和TEE Log
  • 原文地址:https://www.cnblogs.com/totoro-cat/p/13372865.html
Copyright © 2011-2022 走看看