需要导入模块pytest
使用装饰器:pytest.fixture(scope=‘function‘,autouse=False)
fixture()函数参数解释说明
fixture里面有个scope参数可以控制fixture的作用范围:session>module>class>function
-function:每一个函数或方法都会调用
-class:每一个类调用一次,一个类中可以有多个方法
-module:每一个.py文件调用一次,该文件内又有多个function和class
-session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
def fixture( callable_or_scope=None, *args, scope="function", params=None, autouse=False, ids=None, name=None ) 参数说明 :arg scope: the scope for which this fixture is shared, one of ``"function"`` (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"`` (``"package"`` is considered **experimental** at this time). This parameter may also be a callable which receives ``(fixture_name, config)`` as parameters, and must return a ``str`` with one of the values mentioned above. See :ref:`dynamic scope` in the docs for more information. :arg params: an optional list of parameters which will cause multiple invocations of the fixture function and all of the tests using it. The current parameter is available in ``request.param``. :arg autouse: if True, the fixture func is activated for all tests that can see it. If False (the default) then an explicit reference is needed to activate the fixture. :arg ids: list of string ids each corresponding to the params so that they are part of the test id. If no ids are provided they will be generated automatically from the params. :arg name: the name of the fixture. This defaults to the name of the decorated function. If a fixture is used in the same module in which it is defined, the function name of the fixture will be shadowed by the function arg that requests the fixture; one way to resolve this is to name the decorated function ``fixture_<fixturename>`` and then use ``@pytest.fixture(name=‘<fixturename>‘)``. """
fixture()函数参数说明
初始化清除操作:
方式一:
def simple_setup():
清除操作
yield
清除操作or清除操作函数
方式二:
def simple_setup(request):
清除操作
request.addfinalizer(清除操作函数)
例子:
参数中设置autouse=True ,则每个测试用例都执行初始化清除操作
@pytest.fixture(scope=‘function‘) def simple_request(): print(‘开始初始化‘) yield after_test() def after_test(): print(‘开始清除‘) # autoust=False,添加初始化操作函数名作为参数,就会执行初始化操作,不加则不执行 def test_request(simple_request): print(‘测试用例1,开始执行测试‘) assert 1 == 1 def test_request2(): print(‘测试用例2,开始执行测试‘) assert 1 == 1
@pytest.fixture(scope=‘function‘) def simple_request(request): print(‘开始初始化‘) request.addfinalizer(after_test) def after_test(): print(‘开始清除‘) # autoust=False,添加初始化操作函数名作为参数,就会执行初始化操作,不加则不执行 def test_request(simple_request): print(‘测试用例1,开始执行测试‘) assert 1 == 1 def test_request2(): print(‘测试用例2,开始执行测试‘) assert 1 == 1
执行结果:
原文地址:https://www.cnblogs.com/aiyumo/p/12401938.html
时间: 2024-11-09 03:18:42