conftest.py 配置

319 阅读3分钟

一、概述

"conftest.py" 是 pytest 测试框架中的一个特殊的配置文件,它能够为整个测试环境提供一些共享的配置。

  • onftest.py 文件通常会存放在测试目录的根目录中,或者是测试目录的子目录中,以便于对应的配置可以在整个测试环境中起作用。
  • fixtures 是 conftest.py 文件最常见的用法,用于共享数据设置处理测试所需的资源
  • 每个 fixture 函数通常都有一个固定的名称,并且可以在测试用例中通过参数注入的方式使用它们。

二、场景说明

假设我们有三个业务模块,分别为商品模块、订单模块、用户模块。它们都有各自的测试用例,其中订单用户模块需要拿到登录成功返回的 token 才能进行测试。

  • 调用示意图

  • 示例目录说明

三、代码示例

3.1 最外层

  • conftest.py:
import pytest


@pytest.fixture(scope="session")
def login():
    print("### 登录系统! ###")
    name = "jan"
    token = "111"
    yield name, token
    print("### 退出系统! ###")


@pytest.fixture(autouse=True)
def get_token(login):
    name, token = login
    print(f"===(全局 conftest.py),每个测试函数执行前都自动调用 get_token fixture===")

  • demo_run.py:
import pytest

if __name__ == '__main__':
    pytest.main(["-s", "../test-demo/"])

3.2 商品模块测试

  • test_cases.py:
def test_case1():
    print(">>>无需登录的商品模块:执行商品查询测试>>>")

3.3 订单模块测试

  • conftest.py:
import pytest


@pytest.fixture(scope="module")
def open_order_management_system(login):
    name, token = login
    print(f"===(order 目录下的 conftest.py),得到token{token},用户{name}打开订单管理系统. ===")

  • test_cases.py:
def test_case1(open_order_management_system):
    print(">>>进入订单管理:执行创建订单测试>>>")


def test_case2(open_order_management_system):
    print(">>>进入订单管理:执行查询订单测试>>>")

3.4 用户模块测试

  • test_cases.py:
def test_case1(login):
    name, token = login
    print(f">>>(全局 conftest.py)得到token:{token},进入用户管理:执行创建用户测试>>>")

3.5 执行结果

import pytest

if __name__ == '__main__':
    pytest.main(["-s", "../test-demo/"])
# ### 登录系统! ###
#
# ===(全局 conftest.py),每个测试函数执行前都自动调用 get_token fixture===
# >>>无需登录的商品模块:执行商品查询测试>>>
#
# ===(order 目录下的 conftest.py),得到token111,用户jan打开订单管理系统. ===
# ===(全局 conftest.py),每个测试函数执行前都自动调用 get_token fixture===
# >>>进入订单管理:执行创建订单测试>>>
#
# ===(全局 conftest.py),每个测试函数执行前都自动调用 get_token fixture===
# >>>进入订单管理:执行查询订单测试>>>
#
# ===(全局 conftest.py),每个测试函数执行前都自动调用 get_token fixture===
# >>>(全局 conftest.py)得到token:111,进入用户管理:执行创建用户测试>>>
#
# ### 退出系统! ###

四、关于 conftest.py 配置 fixture

  • pytest 会默认读取 conftest.py 里面的所有 fixture 。
  • conftest.py 文件名称是固定的,不能改动。
  • conftest.py 只对同一个 package 下的所有测试用例生效。
  • 不同目录可以有自己的 conftest.py,一个项目中可以有多个 conftest.py 。
  • 测试用例文件中不需要手动 import conftest.py,pytest 会自动查找

五、结束语

“-------怕什么真理无穷,进一寸有一寸的欢喜。”

微信公众号搜索:饺子泡牛奶