Requests + Pytest + Allure 实现 API 自动化测试

项目地址:https://github.com/tomoyachen/api-test-scaffold

基于 Pytest + Requests + Allure 实现快速搭建 API 自动化测试项目的脚手架。

文章目录

  • TODO
  • 已实现
  • 目录结构
  • 用例示例
  • Allure 报告
  • 日志
  • GitLab CI

TODO

  1. 基于 GitLab CI 的 飞书、钉钉的通知
  2. 基于 pre-commit 规范提交代码风格
  3. 进一步完善 GitLab CI 过程(触发器、美化报告)

已实现

(Changes)

  1. 基本的测试用例示例
  2. 简单、易维护的分层
  3. 多套环境的配置、静态数据
  4. 接口会话信息输出
  5. 支持 Allure 报告
  6. 登录态用例示例(包含免登录策略)
  7. 经典场景用例示例(动态传参、遍历测试、tags)
  8. 支持操作 Mysql、Redis
  9. 基于 GitLab CI 的执行用例、生成 allure 报告、部署 pages
  10. 基于 GitLab CI 支持 allure 单次报告、增量报告
  11. 基于 GitLac CI 支持根据提交所影响的范围来动态执行用例

目录结构

api-test-scaffold
├─common
│      config.py # 读取配置(dev.yaml)、静态数据(dev/project_1.yaml)
│      request.py # 请求基类
│
├─config
│      dev.yaml # 环境配置(URL、数据库连接信息)
│      dev-01.yaml
│
├─fixtures
│  └─dev
│          project_1.yaml # 静态数据(用户信息、各种常量)
│
├─outputs
│  ├─report # allure 原始文件
│  └─report-html # allure 生成的 html 目录(用于部署在线报告)
│
├─request
│  └─project_1 # 项目文件夹
│      └─module_1 # 模块文件夹
│              post_method_request.py # 被测接口(维护接口基本信息、工具方法)
│              get_method_request.py 
│
├─testcase
│  └─project_1
│      └─module_1
│              post_method_test.py # 测试用例
│              get_method_test.py
│
│  .gitignore
│  conftest.py # Pytest 最先执行的文件(大量内置钩子、定义全局fixture)
│  poetry.lock
│  pyproject.toml
│  pytest.ini # Pytest 配置文件
│  .gitlab-ci.yml # GitLab CI 配置
└─ README.md

用例示例

testcase\project_1\module_1\post_method_test.py

import pytest
import allure
from request.project_1.module_1.post_method_request import PostMethodRequest

@allure.epic("Project 1")
@allure.feature("Module 1")
@allure.story("Post 请求接口")
class PostMethodTest():

    @pytest.fixture(scope='function')
    def api(self):
        request = PostMethodRequest()
        yield request

    @allure.title("成功请求")
    def test_post_method(self, api):

        api.request()
        api.assertion(expect_code=200)

    @allure.title("id 不存在")
    def test_post_method_with_id_not_exists(self, api):

        api.data['id'] = -1
        api.request()
        api.assertion(expect_code=1001, expect_message='id 不存在')

Allure 报告

Requests + Pytest + Allure 实现 API 自动化测试_第1张图片
Requests + Pytest + Allure 实现 API 自动化测试_第2张图片

日志

2021-11-26 21:16:40    INFO    conftest.py:38    用户 zhangsan 免登录
2021-11-26 21:16:41    INFO    request.py:77    Caller: 
POST  https://httpbin.org/post
Request Headers: {'content-type': 'application/json; charset=utf-8'}
Request Body: {'id': 1, 'status': 1, 'code': 200, 'message': None}
HTTP Code: 200
Response Body: {  "json": {    "code": 200,     "id": 1,     "message": null,     "status": 1  }}

GitLab CI

Requests + Pytest + Allure 实现 API 自动化测试_第3张图片

你可能感兴趣的:(Pytest,Python,接口测试,Playwright,自动化测试,Pytest)