在接口测试中,我们常常会遇到批量参数化执行的需求,比如查询接口需要传入不同筛选条件进行验证。本文通过实际项目案例,讲解如何使用 Pytest + Allure + YAML 实现接口自动化测试,完整展示从封装请求、读取参数、到生成测试报告的全过程。

一、接口背景说明

我们以一个“视图数据列表查询接口”为例,接口地址如下:

POST /api-engine-mid/v2/page/record/list

每个查询请求都需要传入 viewCode、pageCode、筛选条件等参数。我们通过封装 RecordList 类来组织这类查询逻辑。

📦 接口封装类 RecordList

python

class RecordList(Common):
    COOKIE = "_bl_uid=qdlFeiX0y1FdXe1wkg6I5sd6n8da"
    CONTENT_TYPE = "application/json;charset=UTF-8"

    def __init__(self, token):
        self.token = token
        super().__init__(token)

    def get_viewCode(self, view_code="bushuyu", page_code="2023060819591966712110", page=1, num=10, **kwargs):
        url = f"{host}/api-engine-mid/v2/page/record/list"
        data = {
            "viewCode": view_code,
            "pageCode": page_code,
            "page": page,
            "num": num,
        }
        data.update(kwargs)

        headers = {
            "Content-Type": self.CONTENT_TYPE,
            "Cookie": self.COOKIE,
            "X-User-Token": self.token
        }

        try:
            resp = requests.post(url, data=json.dumps(data), headers=headers)
            resp.raise_for_status()
            return resp.json() if resp.json()['code'] == 0 else resp.headers.get("Oryx-Trace-Id")
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {e}")
            return None

二、测试数据设计(YAML)

我们把不同 viewCode、condition 和 value 组合存放在 conf/viewCode.yaml 中:

yaml

list_text:
  viewCode: ["dengyu", "budengyu", "wenbenbaohan", "wenbenbubaohan", "quanbu1", "bushuyu", "weikong", "wenbenfeikong"]
  condition: ["等于", "不等于", "包含", "不包含", "属于", "不属于", "空", "非空"]
  value: ["1", "1", "1", "1", ["1","2","3"], ["1","2","3"], "无", "无"]
  expected: [1, 20, 3, 18, 2, 19, 14, 7]

三、读取 YAML 并格式化为 Pytest 参数化格式

python

def read_yaml(file_path: str) -> dict:
    try:
        with open(file_path, encoding="utf-8") as fp:
            return yaml.safe_load(fp)
    except Exception as e:
        print(f"读取 YAML 出错: {e}")
        return {}

def read_viewCode(file_type, file="conf/viewCode.yaml") -> List[Tuple[str, str, str, str]]:
    data = read_yaml(file)
    if file_type in data:
        view_code = data[file_type].get('viewCode', [])
        condition = data[file_type].get('condition', [])
        value = data[file_type].get('value', [])
        expected = data[file_type].get('expected', [])
        return list(zip(view_code, condition, value, expected))
    return []

四、编写测试用例并添加 Allure 标注

python

@allure.feature("视图筛选器功能")
class Test_ViewCode:
    @allure.story("文本字段筛选")
    @allure.title("左边:文本,条件:{condition},右边:{value}")
    @pytest.mark.parametrize("viewCode, condition, value, expected", read_viewCode("list_text"))
    def test_list_text(self, before_recordList, viewCode, condition, value, expected):
        recordList = before_recordList

        with allure.step("获取视图列表结果"):
            result = recordList.get_viewCode(viewCode=viewCode)
            allure.attach("查询参数", f"viewCode: {viewCode}, condition: {condition}, value: {value}", allure.attachment_type.TEXT)
            allure.attach("查询结果", f"{result}", allure.attachment_type.JSON)

        with allure.step("验证结果"):
            actual_total = result['page']['total']
            allure.attach("预期结果", str(expected), allure.attachment_type.TEXT)
            allure.attach("实际结果", str(actual_total), allure.attachment_type.TEXT)
            assert actual_total == expected, f"期望值为 {expected},实际返回为 {actual_total}"

五、运行测试并生成 Allure 报告

python

if __name__ == '__main__':
    pytest.main(['tc/test_viewCode.py', '-s', '--alluredir=tmp/report', '--clean-alluredir'])
    os.system("allure generate ./tmp/report -o ./report/html --clean")
    os.system("allure serve -p 60000 ./tmp/report")

六、测试结构说明

project/
│
├── conf/
│   └── viewCode.yaml           # 存放测试数据(参数化用)
│
├── tc/
│   └── test_viewCode.py        # 测试用例文件
│
├── utils/
│   └── record_list.py          # 接口封装类
│
├── tmp/
│   └── report/                 # pytest执行后生成的中间结果(用于Allure)
│
├── report/
│   └── html/                   # 最终生成的 Allure HTML 报告
│
├── run_tests.py                # ⬅️ 测试执行脚本
│
└── requirements.txt            # 依赖列表(建议添加)

七、总结

本文从接口封装、数据驱动、测试编写到报告生成,完整演示了一个“列表类接口”的自动化思路。使用 Pytest + YAML 管理测试数据,可以高效地实现用例批量执行。而通过 Allure 报告,则能清晰呈现测试过程与结果,便于分析问题。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐