标签:调用 customer 生成 条件 data 共享 close tom hello
1.同unittest的setup和teardown,作为测试前后的初始化设置。
1.作为前置条件使用
2.fixture的的作用范围
@pytest.fixture()
def a():
return 3
def test_b(a):
assert a==3
首先实例化更高范围的fixture.默认为scope="function",每个测试函数都会执行一次。
yield 前的在测试之前执行,yield后的在测试完后执行
@pytest.fixture def a(): print("setup") yield print("teardown") def test_b(a): print("测试")
# @pytest.fixture() # def write_file(): # f = open("myfile.txt","w") # f.write("hello") # yield # f.close() @pytest.fixture() def write_file(): with open("myfile.txt","w") as f: f.write("hello1") def test_write_file(write_file): print("ceshi")
@pytest.fixture(params=[1,3]) def a(request): return request.param def test_b(a): assert a in [1,3]
在单个测试中,如果想多次调用该fixture,就可以用工厂模式。fixture的结果返回的不是数据,而是返回生成数据的函数。
@pytest.fixture def make_customer_record(): def _make_customer_record(name): return {"name": name, "orders": []} return _make_customer_record def test_customer_records(make_customer_record): customer_1 = make_customer_record("Lisa") customer_2 = make_customer_record("Mike") customer_3 = make_customer_record("Meredith")
params列表有几个值,测试就会执行几次。例params=[1,2],测试用例会执行2次
@pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)]) def data_set(request): return request.param def test_data(data_set): pass
1.conftest.py 共享fixture。如果定义fixture过多且需要多个地方调用,可将fixture放入conftest.py文件中,使用时不需要导入
标签:调用 customer 生成 条件 data 共享 close tom hello
原文地址:https://www.cnblogs.com/jiablogs/p/12024255.html