python-conftest、fixture、matefunc介绍

pytest的规则使用

"""
使用pytest编写用例,必须遵守以下规则:
    (1)测试文件名必须以“test_”开头或者"_test"结尾(如:test_ab.py)
    (2)测试类命名以"Test"开头。
    (3)测试方法必须以“test_”开头。

conftest.py与运行的用例要在同一个pakage下,并且有__init__.py文件
conftest.py中的函数不调用也不会执行,调用方式:无需导入,直接同名参数在用例中使用
"""

"""
@pytest.mark.标签名
   标记范围:测试用例、测试类、模块文件

@pytest.fixture(scope='function',params=None,autouse=False,ids=None,name=None)
    fixture scope参数
        scope参数可以控制fixture的作用范围(session>module>class>function)
            function:每一个函数或方法都会调用,默认值@pytest.fixture(scope='function')或 @pytest.fixture()
            class:   每一个class调用一次,一个类中可以有多个方法
            module:  每一个.py调用一次,一个文件中有多个function和class
            session: 多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
    fixture其他参数
        params:一个可选的参数列表,它将导致多个参数调用fixture功能和所有测试使用它。
        autouse:如果True,则为所有测试激活fixture func可以看到它(如果为True不需要调用就执行)。如果为False则显示需要参考来激活fixture,如果为True不需要调用就执行
        ids:每个字符串id的列表,每个字符串对应于params这样他们就是测试ID的一部分。如果没有提供ID它们将从params自动生成
        name:fixture的名称。这默认为装饰函数的名称。如果fixture在定义它的统一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽,解决这个问题的一种方法时将装饰函数命令"fixture_<fixturename>"然后使用"@pytest.fixture(name='<fixturename>')"。

1、每个接口需共用到的token
2、每个接口需共用到的测试用例数据
3、每个接口需共用到的配置信息
"""

"""
matefunc是pytest的一个类型
    param metafunc:共有五个属性值
        metafunc.fixturenames:参数化收集时的参数名称
        metafunc.module:使用参数名称进行参数化的测试用例所在的模块d对象
        metafunc.config:测试用例会话
        metafunc.function:测试用例对象,即函数或方法对象metafunc.function.__name__
        metafunc.cls: 测试用例所属的类的类对象
        metafunc.parametrize:将key列表和value列表对应起来

print(metafunc.definition.own_markers) #[Mark(name='datafile', args=('D:\\codeBook\\pyhton\\shuzf_demo\\file/yaml/demo.yaml',), kwargs={})]
print(metafunc.definition.own_markers[0].args[0])  #D:\codeBook\pyhton\shuzf_demo\file/yaml/demo.yaml
print(metafunc.config.rootdir)         #D:\codeBook\pyhton\shuzf_demo

print(metafunc.fixturenames)           #['_session_faker', 'pytestconfig', 'faker_seed', 'parameters', 'request']
print(metafunc.config)                 #<_pytest.config.Config object at 0x000001FF8AA806D0>
print(metafunc.module)                 #<<module 'test_coll' from 'D:\\codeBook\\pyhton\\shuzf_demopy\\testCase\\test3\\test_coll.py'>
print(metafunc.cls)                    #class 'test_coll.TestCollection'>
print(metafunc.function)               #<function TestCollection.test_data_collection at 0x000001FFA2876E50>
"""

 

import pytest
@pytest.fixture(scope='session',autouse=True)  #scope设置执行范围,autous如果为True不需要调用就执行
def get_token():
    token = 'qeehfjejwjwjej11sss@22'
    return token


test_case=['a','b','c']
def pytest_generate_tests(metafunc):
    ids=[]
    if 'parameters' in metafunc.fixturenames:
        for case in test_case:
            ids.append(case)
    metafunc.parametrize('parameters',test_case, ids=ids, scope='function')

 

posted @ 2023-02-05 15:55  南方的墙  阅读(111)  评论(0编辑  收藏  举报