需要导入模块pytest
初始化操作:
使用装饰器:pytest.fixture(scope=‘function‘,autouse=False)
fixture()函数参数解释说明
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>‘)``. """
清除操作:
yeild
teardown
例子:
参数中设置autouse=True ,则每个测试用例都执行初始化清除操作
@pytest.fixture(scope=‘function‘) def simple_request(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
执行结果:

原文:https://www.cnblogs.com/aiyumo/p/12401938.html