pytest-fixture
目录
简介
conftest.py: 数据共享
Fixture+yield实现setup teardown
Fixtures工厂方法
Fixture参数化
简介
目的是为测试的重复执行提供一个可靠的固定基线
- 使⽤fixture执⾏配置及销毁;⾮常灵活使⽤。
- 数据共享:conftest.py配置⾥写⽅法可以实现数据共享,不需要import导⼊。可以跨⽂件共享
- scope的层次及神奇的yield组合相当于各种setup 和 teardown
Fixture参数含义:
- scope : 共享此夹具的范围,"function" (默认)或“class”“module”“package”“session”。此参数也可以是作为参数接收的可调用对象,并且必须返回具有上述值之一
- params – 一个可选的参数列表,它将导致对夹具函数和所有使用它的测试的多次调用。当前参数可用request.param。
- autouse – 如果为 True,则为所有可以看到它的测试激活夹具func。如果为 False(默认值),则需要显式引用来激活夹具。
- ids – 每个对应于参数的字符串 id 列表,因此它们是测试 id 的一部分。如果没有提供 id,它们将从参数中自动生成。
- name -夹具的名称。这默认为装饰函数的名称。如果固定装置在其被定义在相同的模块中使用的,功能名称夹具将被函数ARG请求固定装置被遮蔽; 解决此问题的一种方法是命名装饰函数fixture_,然后使用 @pytest.fixture(name=’’).
conftest.py: 数据共享
- 如果在测试中需要使用多个测试文件中的fixture函数,则可以将其移动到conftest.py文件中,所需的fixture对象会自动被Pytest发现,而不需要再每次导入。
- fixture函数的发现顺序:从测试类开始,然后是测试模块,然后是 conftest.py文件,最后是内置和第三方插件。
- 如果要使用数据文件中的测试数据,最好的方法是将这些数据加载到fixture函数中以供测试用例注入使用。这利用到了pytest的自动缓存机制。
- scope参数的可选值包括:function(函数),class(类),module(模块),package(包)及 session(会话)。
Conftest.py@pytest.fixture(scope="session")
def say_no():print("say no test fixture")
测试用例(不需要导入conftest.py,直接可以使用):
def test_s(say_no):print("abc")
运行结果:
注意:
- 在测试函数的fixture对象请求中,较高范围的fixture(例如session会话级)较低范围的fixture(例如 function函数级或class类级优先执行。相同范围的fixture对象的按引入的顺序及fixtures之间的依赖关系按顺序调用。
- 当存在多个目录中有conftest.py时,采用就近原则。
自己模块 > 当前目录下conftest.py > 父目录下conftest.py > … > / conftest.py , 层层往上,永远不会去寻找兄弟目录下的conftest.py
Fixture+yield实现setup teardown
Conftest.py@pytest.fixture(scope="session")
def say_no():print("setup")yieldprint("teardown")
测试用例
def test_s(say_no):print("abc")
Fixtures工厂方法
“工厂作为Fixture方法”模式可以在单个测试中多次需要Fixture方法结果的情况下提供帮助。不是直接返回数据,而是返回一个生成数据的函数。然后可以在测试中多次调用此函数。 Fixtures工厂方法可根据需要提供参数生成Fixture和方法:
@pytest.fixture
def make_customer_record():def _make_customer_record(name):return {"name": name,"orders": []}return _make_customer_recorddef test_customer_records(make_customer_record):customer_1 = make_customer_record("Lisa")customer_2 = make_customer_record("Mike")customer_3 = make_customer_record("Meredith")
Fixture参数化
fixture 通过固定参数 request 传递参数
例如:
@pytest.fixture(params=['tom', "jack", "tony"], ids=["name1", "name2", "name3"])
def demo(request):print("-------")yield request.paramprint("=======")def test_demo(demo):print("name", demo)