pytest文档66-工厂化的 fixtures

前言

在一个测试用例中需要多次调用同一个fixture的时候,工厂化的 fixture 的模式对于一个 fixture 在单一的测试中需要被多次调用非常有用。
之前写fixture是直接return一个数据,在测试用例中可以直接使用,现在我们需要返回一个生成数据的函数,这样就能在用例中多次调用了。

Factories as fixtures

“Factories as fixtures”模式可以帮助在一次测试中多次需要一个fixture的结果的情况下。
fixture不是直接返回数据,而是返回一个生成数据的函数。然后可以在测试中多次调用此函数。

使用示例

import pytest


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

如果工厂创建的数据需要管理,那么fixture可以处理:

import pytest


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

场景案例

有个场景案例:当用户第一次注册的时候,可以注册成功,第二次注册的时候,提示用户已被注册了

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


@pytest.fixture()
def register():

    def _register(user):
        # 调用注册接口,返回结果
        print("注册用户:%s" % user)
        result = {"code": 0,
                  "message": "success"}
        return result

    return _register



def test_case_1(register):
    '''测试重复注册接口案例'''
    # 第一次调用注册
    result1 = register("yoyo")
    assert result1["message"] == "success"

    # 第二次调用
    result2 = register("yoyo")
    # 真实场景可以断言 已被注册了

这种场景把注册写到fixture的话,在测试用例里面就需要调用两次

网易云完整视频课程《pytest+yaml 框架使用与开发》https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338

posted @ 2020-12-02 12:33  上海-悠悠  阅读(2049)  评论(0编辑  收藏  举报