首页 > 其他 > 详细

pytest-fixture

时间:2019-12-11 18:39:43      阅读:95      评论:0      收藏:0      [点我收藏+]

fixture的作用

1.同unittest的setup和teardown,作为测试前后的初始化设置。

fixture的使用

1.作为前置条件使用

2.fixture的的作用范围

 

1.作为前置条件使用

@pytest.fixture()
def a():
    return 3

def test_b(a):
    assert a==3

2.fixture的作用范围

首先实例化更高范围的fixture.默认为scope="function",每个测试函数都会执行一次。

  • session : 多个.py文件执行时,只调用一次
  • module: 每一个.py调用一次
  • class : 每个类调用一次
  • function: 每个函数调用一次

3.fixture 作为setup/teardown执行

yield 前的在测试之前执行,yield后的在测试完后执行

@pytest.fixture
def a():
    print("setup")
    yield
    print("teardown")

def test_b(a):
    print("测试")

4.fixture with

# @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")

5. fixture request可以请求测试的上下文

@pytest.fixture(params=[1,3])
def a(request):
    return request.param

def test_b(a):
    assert a in [1,3]

6.fixture 工厂模式

在单个测试中,如果想多次调用该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")

7.带参数的fixture

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文件中,使用时不需要导入

pytest-fixture

原文:https://www.cnblogs.com/jiablogs/p/12024255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!