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

7 篇文章 1 订阅
3 篇文章 0 订阅

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

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

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 报告

在这里插入图片描述
在这里插入图片描述

日志

2021-11-26 21:16:40    INFO    conftest.py:38    用户 zhangsan 免登录
2021-11-26 21:16:41    INFO    request.py:77    Caller: <FrameSummary file D:\chen\PycharmProjects\api-test-scaffold\testcase\project_1\module_1\classic_scene_test.py, line 44 in test_classic_scene_with_parametrize>
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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值