接口主动化测试设计思绪--设计实战

[复制链接]
发表于 2025-9-8 06:20:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
课程:B站大学
记录python学习,直到学会基本的爬虫,使用python搭建接口主动化测试就算学会了,在进阶webui主动化,app主动化



怎样进行接口主动化测试设计思绪?

目前网络到的设计方案思绪如下:
基类 + 工具类:解决通用逻辑的复用问题。
参数化测试:得当简单场景的大量数据驱动。
会合管理测试数据:提升测试数据维护效率。
数据驱动框架:复杂场景和大规模用例时使用。
数据库动态天生:需要强耦合数据库或验证复杂业务逻辑时使用。
基于基类和工具类的测试框架设计思绪
1. 背景

在接口主动化测试中,为了提高代码的复用性、可维护性和扩展性,通常需要设计一个高效的测试框架。本文提出了一种基于基类 + 工具类的设计方案,旨在解决以下问题:


  • 测试用例中重复逻辑过多,代码冗余。
  • 测试数据难以管理,维护成本高。
  • 接口测试的校验逻辑分散,不易复用。
2. 设计目标


  • 复用性:


  • 通用功能会合封装,避免重复代码。
  • 测试数据与测试逻辑分离,提高数据复用率。

  • 可维护性:


  • 测试代码结构清晰,便于维护和扩展。
  • 测试日记与错误信息明确,易于定位问题。

  • 扩展性:


  • 能快速适配新增的测试场景。
  • 支持复杂业务逻辑的验证需求。

3. 框架设计

3.1 基类设计

核心功能:


  • 提供测试前后的通用操作(如情况初始化)。
  • 提供常用的辅助方法(如加载测试数据、通用校验等)。
  • 测试用例类通过继承基类复用其功能。
    示例代码
  1. import pytest
  2. import json
  3. class BaseTest:
  4.     @pytest.fixture(scope="class", autouse=True)
  5.     def setup(self):
  6.         """测试初始化,执行每个测试类前的准备工作"""
  7.         self.api = APIClient()  # 初始化 API 客户端实例
  8.     def load_test_data(self, file_path):
  9.         """从指定文件加载 JSON 测试数据"""
  10.         try:
  11.             with open(file_path, 'r', encoding='utf-8') as file:
  12.                 return json.load(file)
  13.         except FileNotFoundError:
  14.             raise FileNotFoundError(f"Test data file not found: {file_path}")
  15.         except json.JSONDecodeError:
  16.             raise ValueError(f"Invalid JSON format in file: {file_path}")
  17.     def validate_response(self, response, expected_data):
  18.         """验证接口响应字段是否匹配"""
  19.         for key, value in expected_data.items():
  20.             assert response.data[key] == value, f"Mismatch for {key}: expected {value}, got {response.data[key]}"
复制代码
3.2 工具类设计

核心功能:


  • 封装通用工具方法(如数据校验、日记记录)。
  • 提供独立于测试逻辑的功能支持,供多个模块调用。
    示例代码
  1. class TestUtils:
  2.     @staticmethod
  3.     def compare_dicts(expected, actual):
  4.         """比较两个字典的值"""
  5.         for key, value in expected.items():
  6.             assert actual[key] == value, f"Key '{key}' mismatch: expected {value}, got {actual}"
  7.     @staticmethod
  8.     def log_request_response(request, response):
  9.         """记录请求和响应日志日志"""
  10.         print(f"Request: {request}")
  11.         print(f"Response: {response}")
  12.     @staticmethod
  13.     def generate_unique_id():
  14.         """生成唯一标识符(示例方法)"""
  15.         import uuid
  16.         return str(uuid.uuid4())
复制代码

4. 测试用例实现

核心思绪:


  • 测试用例类继承 BaseTest,复用初始化和通用方法。
  • 根据详细场景调用工具类中的方法,简化测试逻辑。
    示例代码
  1. import pytest
  2. from test_utils import TestUtils
  3. class TestCategory(BaseTest):
  4.     @pytest.fixture(scope="class", autouse=True)
  5.     def setup(self):
  6.         """继承基类 setup 并扩展初始化逻辑"""
  7.         super().setup()
  8.         self.create_data_file = "create_data.json"
  9.         self.update_data_file = "update_data.json"
  10.     def test_create_category(self):
  11.         """测试新增商品分类"""
  12.         data = self.load_test_data(self.create_data_file)  # 加载测试数据
  13.         response = self.api.createCategory(data)          # 调用接口
  14.         assert response.code == 0                         # 验证接口响应
  15.         assert response.data is not None                  # 验证是否返回数据
  16.     def test_update_category(self):
  17.         """测试修改商品分类"""
  18.         data = self.load_test_data(self.update_data_file)  # 加载测试数据
  19.         response = self.api.updateCategory(data)          # 调用接口
  20.         assert response.code == 0                         # 验证接口响应
  21.         assert response.data is True                      # 验证是否返回正确结果
  22.     def test_validate_category(self):
  23.         """验证修改后的分类是否正确"""
  24.         expected_data = self.load_test_data(self.update_data_file)
  25.         category_id = expected_data["categoryId"]
  26.         response = self.api.getCategory(category_id)
  27.         assert response.code == 0
  28.         self.validate_response(response, expected_data)   # 使用基类方法验证字段
复制代码

5. 测试数据管理



  • 会合化管理:

    • 将测试数据保存在 JSON 文件中,按模块或场景划分。
    • 文件命名发起:create_data.json、update_data.json。

  • 动态加载:

    • 使用基类中的方法动态加载测试数据,减少硬编码。
      示例测试数据

  1. create_data.json
  2. {
  3.   "categoryId": 1,
  4.   "shopId": 1,
  5.   "categoryName": "创建商品分类",
  6.   "memberDiscountInfo": [],
  7.   "isShopDisplay": 1,
  8.   "isDeleted": 0,
  9.   "sort": 1,
  10.   "createBy": "tester",
  11.   "createTime": "2023-10-01T00:00:00",
  12.   "updateBy": "tester",
  13.   "updateTime": "2023-10-01T00:00:00"
  14. }
复制代码

6. 优势分析


  • 代码复用性:


  • 通用功能封装到基类和工具类中,减少重复代码。

  • 可维护性:


  • 测试数据会合存储,便于管理和更新。
  • 测试逻辑清晰,便于团队协作。

  • 扩展性:


  • 基类和工具类支持新增功能的快速扩展。
  • 新增测试场景时,仅需编写少量代码。

小技巧:这里我们可以对每个测试用例的逻辑进行封装,解决在实际业务场景中需要不绝的调用不同的接口完成测试,也可以对每个函数打标志@pytest.mark.update_category(目前没感觉到用处)
比如:存在一个写了对于模块全部调用接口的测试用例文件test_case_helpers.py,新建一个test_category.py文件用来模仿实际的业务场景。但是也有个问题,假如一个场景就是一个py文件,岂不是需要新建很多的py文件??(貌似可以一个py文件中界说不同的类,不同的类对应不同的业务场景,py文件看上去少)
示例:
  1. # test_product.py
  2. import pytest
  3. from test_case_helpers import test_create_product, test_update_product, test_get_product
  4. class TestCreateProduct:
  5.     def test_create_product(self, api_client):
  6.         """新增商品的测试"""
  7.         test_create_product(api_client, "create_product_data.json")
  8.     def test_validate_create(self, api_client):
  9.         """新增商品后验证商品信息"""
  10.         test_get_product(api_client, "create_product_data.json")
  11. class TestUpdateProduct:
  12.     def test_update_product(self, api_client):
  13.         """修改商品的测试"""
  14.         test_update_product(api_client, "update_product_data.json")
  15.     def test_validate_update(self, api_client):
  16.         """修改商品后验证商品信息"""
  17.         test_get_product(api_client, "update_product_data.json")
  18. class TestCreateAndValidateProduct:
  19.     def test_create_and_validate(self, api_client):
  20.         """新增商品并查看新增是否正确"""
  21.         test_create_product(api_client, "create_product_data.json")
  22.         test_get_product(api_client, "create_product_data.json")
  23. class TestUpdateAndValidateProduct:
  24.     def test_update_and_validate(self, api_client):
  25.         """修改商品并查看修改是否正确"""
  26.         test_update_product(api_client, "update_product_data.json")
  27.         test_get_product(api_client, "update_product_data.json")
复制代码
7. 总结

1、通过基类与工具类的设计,可以有效提升接口主动化测试的开发效率与代码质量。
2、就目前而言,我发现可以用下面的方式写:
1.1:通过单独的casehelp.py文件封装该模块下能调用的全部接口方法为不同的def函数(每个函数里面进行详细的断言以及覆盖率等),
1.2:在外部新建一个actl_case.py文件进行直接调用def函数进行测试,使用@pytest.mark.run(order=xxx)实验函数的运行次序(这里在想可以写个py脚本把casehelp.py文件中的def函数名都读取出来写入到actl_case.py文件中并在每个def函数头一行前加入@pytest.mark.run(order=xxx)装饰器),然后只需要更改order就可以完成不同业务场景的测试了。
1.3:actl.case文件一个业务场景新建一个类,一个类就对应一个业务场景,然后给这个类打上标志@pytest.mark.xxx,运行的时候过滤筛选标志实验。
目前写调用测试用例的流程:

1、新建test_xxx_xxx测试用例文件
2、检察api指定的请求数据模子,天生对应的json测试数据
3、区分不同的请求接口:
POST:有json的创建json测试数据、有dict的传字典、params的用例参数化
GET:参数少的用例参数化,参数多的用json
得当快速实现接口间依赖的场景方式如下:
独立封装接口函数,手动传递依赖数据:

  • 每个接口独立封装为函数
  • 通过函数调用传递数据

实践是检验真理的唯一标准

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表