pytest中文文档重点记录

Fixture(https://docs.pytest.org/en/latest/fixture.htm):

fixture有自己的名字,按照影响范围如session, module, class, function等进行声明

fixture可以调用其它fixture

fixture可接收参数

在pytest 3.7版本引入 package scope, 实验功能,可能在将来被移除。

更高scope级别的fixture会被先调用,停止时低级别fixture先被调用(停止)。类似先进后出。

pytest支持在fixture scope out时执行停止代码,在fixture里用yield当做返回,yield之后的代码会被当做停止代码在停止时执行。还可以使用yield + with的方式执行停止代码,with天然地会在执行结束前关闭连接等资源。

yield之前实际就是pytest的setup代码,当此部分出现异常时,pytest不会执行yield之后的代码,即teardown代码;但如果是测试case中有异常,yield后的代码仍会被执行。

还有另一种执行停止代码的方法,使用request-context object的addfinalizer (https://docs.pytest.org/en/latest/fixture.html#request-context)

yield和addfinalizer调用代码的方式差不多,有两点不同:

    addfinalizer 可以定义多个结束方法

    无论setup code是否正常执行,addfinalizer 都会被调用  ?

Fixture的自省:待加

Factories as fixtures:

在一个简单测试中当fixture会被多次调用时,factory as fixture模式可以返回一个方法,因此测试用例中可以任意调用多次。

@pytest.fixture
def make_customer_record():

    created_records = []

    def _make_customer_record(name):
        record = models.Customer(name=name, orders=[])
        created_records.append(record)
        return record

    yield _make_customer_record

    for record in created_records:
        record.destroy()


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

  

Parametrizing fixtures,带参数的fixture:

 request.params接收一个列表,列表中每个参数会触发一次执行。

 

 

原文地址:https://www.cnblogs.com/tlmn2008/p/9529914.html