pytest夹具Fixture笔记

8 阅读1分钟
# 一,夹具能够用来做什么
# 1.替代setup/teardown,更灵活的前置/后置
# 2.消除重复代码,一次定义到处用
# 3.控制作用域:想让它活多久就活多久
# 4.数据传递 & 依赖管理

# 二,夹具核心作用域
# @pytest.fixture(scope="xxx")
# function → 每个测试函数前后执行(默认)
# class → 每个测试类前后执行
# module → 每个.py文件前后执行一次
# session → 整个测试运行只执行一次(最常用:登录拿token)

# 三,运用
# 1,全局token(整个项目之登录一次),基础返回数据
@pytest.fixture(scope="session", autouse=True)
def demo_token():
    # 模拟登陆
    url = "https://httpbin.org/post"
    data = {"username": "admin", "pwd": "123456"}
    response = requests.post(url, json=data)
    token = "this-is-real-token"
    return token
# 后续使用直接填demo_token进行调用

# 2,yield 前后置(前置操作 + 后置清理)
# 定义夹具 前置+后置
@pytest.fixture(scope="function")  #加autouse = True,自动执行,不用写夹具名称
def my_fixture():
    # 前置
    print("用例前执行")
    token = "this-is-real-token"

    # 交出token,执行用例
    yield token

    # 后置执行
    print("用例后执行")

def test_case1(my_fixture):    #加autouse = True,my_fixture可不写
    token = my_fixture  # 拿到yield返回的值
    print(f"用例执行,使用token:{token}")
    assert 1 == 1
    
# 3,夹具自动执行,见2  autouse = True

# 4,夹具别名:
@pytest.fixture(name="header")
def get_headers():
    return {"token": "123"}

# 5,夹具参数化:
@pytest.fixture(params=[1, 2, 3])
def data(request):
    return request.param

# 数据驱动:
def readexcel():
    df = pd.read_excel("c.xlsx")
    return df.to_dict(orient="records")
# pytest数据驱动,自动执行
@pytest.mark.parametrize("case", readcsv())
def test_cases(case):
    url = case["url"]
    method = case["method"].upper()
    params = case["params"]

    if method == "GET":
        resp = requests.get(url, params=params)
    elif method == "POST":
        resp = requests.post(url, json=params)

    assert resp.status_code == int(case["except"])

# 6:夹具调用夹具(嵌套依赖)
@pytest.fixture
def token():
    return "t123"
@pytest.fixture
def headers(token):
    return {"token": token}


# 7,企业必用conftest.py不需要import,全项目可用根目录下
# 你的项目 /
# ├── conftest.py  # 夹具全部写这里
# └── test_api.p