fixture的作用:作用类似unittest中setup/teardown,它的优势是可以跨文件共享
fixture的格式:在普通函数上加上装饰器@pytest.fixture(),且函数名不能以test_开头,目的是与测试用例做区分
fixture如何使用?fixture可以有返回值,如果没有return默认但会None;用例调用fixture的返回值,就是直接把fixture的函数名称作为参数传入。
特别说明:用例断言失败是failed,fixture断言失败是error
fixture的作用范围
demo1:fixture可以返回一个元组、列表或字典
# test_01.py import pytest @pytest.fixture() def user(): print("用户名") name = ‘wangmm‘ password = ‘123456‘ return name,password def test_a(user): u = user[0] p = user[1] assert u == ‘wangmm‘ 执行结果: D:\myproject\pytest_demo\testcases>pytest -vs test_01.py =================================================================================== test session starts ==================================================================================== platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe cachedir: .pytest_cache rootdir: D:\myproject\pytest_demo\testcases collected 1 item test_01.py::test_a 用户名 PASSED ================================================================================= 1 passed in 0.03 seconds =================================================================================
demo2:test_用例传多个fixture参数
# test_02.py import pytest @pytest.fixture() def username(): name = ‘wangmm‘ return name @pytest.fixture() def pw(): password = ‘123456‘ return password def test_user(username, pw): assert username == ‘wangmm‘ assert pw == ‘123456‘ 执行结果: D:\myproject\pytest_demo\testcases>pytest -vs test_02.py =================================================================================== test session starts ==================================================================================== platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe cachedir: .pytest_cache rootdir: D:\myproject\pytest_demo\testcases collected 1 item test_02.py::test_user PASSED ================================================================================= 1 passed in 0.03 seconds =================================================================================
demo3:fixture与fixture间相互调用
# test_03.py import pytest @pytest.fixture() def first(): a = "wangmm" return a @pytest.fixture() def sencond(first): ‘‘‘psw调用user fixture‘‘‘ a = first b = "123456" return (a, b) def test_1(sencond): ‘‘‘用例传fixture‘‘‘ assert sencond[0] == "wangmm" assert sencond[1] == "123456" 输出结果: D:\myproject\pytest_demo\testcases>pytest -vs test_03.py =================================================================================== test session starts ==================================================================================== platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe cachedir: .pytest_cache rootdir: D:\myproject\pytest_demo\testcases collected 1 item test_03.py::test_1 PASSED
原文:https://www.cnblogs.com/wang-mengmeng/p/11460287.html