• 接口测试返回参数的自动化对比!


    引言

    在现代软件开发过程中,接口测试是验证系统功能正确性和稳定性的核心环节。接口返回参数的对比不仅是确保接口功能实现的手段,也是测试过程中常见且重要的任务。为了提高对比的效率和准确性,我们可以通过自动化手段实现这一过程。本文将介绍接口测试返回参数自动化对比的原理,展示如何使用 Python 和 MySQL 实现对比功能,并提供最佳实践的建议,帮助读者在实际项目中应用这些技术。

    自动化对比的原理

    接口测试返回参数的自动化对比涉及以下几个步骤:

    1. 提取和存储预期结果:在测试用例设计阶段,定义接口调用的预期返回结果,并将其存储在文件或数据库中。

    2. 执行接口调用:通过自动化测试脚本执行接口调用,获取实际的返回结果。

    3. 结果比对:将实际返回的结果与预期结果进行比对,以确认接口是否满足需求。

    自动化对比的工作流程

    1. 准备测试数据:包括请求参数和预期返回结果。

    2. 执行测试用例:发送请求并接收响应。

    3. 对比实际返回的结果和预期结果:通过编写自动化脚本对比返回的参数。

    4. 记录对比结果:将对比结果存储到数据库中,并生成测试报告。

    5. 数据清理:在测试完成后对数据进行清理以维护数据库的健康状态。

    数据库设计与实现

    为了实现自动化对比,我们选择 MySQL 数据库来存储测试执行信息和对比结果。以下是数据库设计方案及其实现细节。

    数据库表设计

    1. 测试执行表

    存储每次测试执行的信息。

    1. CREATE TABLE test_execution (
    2.     execution_id VARCHAR(36PRIMARY KEY,
    3.     test_case_id INT NOT NULL,
    4.     execution_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    5.     status VARCHAR(10NOT NULL
    6. );
    2. 接口调用表

    存储每次接口调用的信息。

    1. CREATE TABLE api_call (
    2.     call_id VARCHAR(36) PRIMARY KEY,
    3.     execution_id VARCHAR(36),
    4.     api_endpoint VARCHAR(255NOT NULL,
    5.     request_params JSON,
    6.     response_data JSON,
    7.     compare_result VARCHAR(10),
    8.     FOREIGN KEY (execution_id) REFERENCES test_execution(execution_id)
    9. );
    3. 对比结果表

    存储每次对比的详细信息。

    1. CREATE TABLE compare_result (
    2.     compare_id VARCHAR(36) PRIMARY KEY,
    3.     call_id VARCHAR(36),
    4.     field_name VARCHAR(255),
    5.     expected_value TEXT,
    6.     actual_value TEXT,
    7.     match_result VARCHAR(10),
    8.     FOREIGN KEY (call_id) REFERENCES api_call(call_id)
    9. );

    数据库操作示例

    以下是插入测试执行记录、接口调用记录和对比结果记录的代码示例:

    1. import mysql.connector
    2. from uuid import uuid4
    3. # 数据库上下文管理器
    4. class Database:
    5.     def __enter__(self):
    6.         self.connection = mysql.connector.connect(
    7.             host="localhost",
    8.             user="root",
    9.             password="password",
    10.             database="test_db"
    11.         )
    12.         self.cursor = self.connection.cursor()
    13.         return self
    14.     def __exit__(self, exc_type, exc_value, traceback):
    15.         self.connection.commit()
    16.         self.cursor.close()
    17.         self.connection.close()
    18. # 插入测试执行记录
    19. def insert_test_execution(test_case_id):
    20.     execution_id = str(uuid4())
    21.     with Database() as db:
    22.         db.cursor.execute(
    23.             "INSERT INTO test_execution (execution_id, test_case_id, status) VALUES (%s, %s, %s)",
    24.             (execution_id, test_case_id, 'running')
    25.         )
    26.     return execution_id
    27. # 插入接口调用记录
    28. def insert_api_call(execution_id, api_endpoint, request_params, response_data, compare_result):
    29.     call_id = str(uuid4())
    30.     with Database() as db:
    31.         db.cursor.execute(
    32.             "INSERT INTO api_call (call_id, execution_id, api_endpoint, request_params, response_data, compare_result) VALUES (%s, %s, %s, %s, %s, %s)",
    33.             (call_id, execution_id, api_endpoint, json.dumps(request_params), json.dumps(response_data), compare_result)
    34.         )
    35.     return call_id
    36. # 插入对比结果记录
    37. def insert_compare_result(call_id, field_name, expected_value, actual_value, match_result):
    38.     compare_id = str(uuid4())
    39.     with Database() as db:
    40.         db.cursor.execute(
    41.             "INSERT INTO compare_result (compare_id, call_id, field_name, expected_value, actual_value, match_result) VALUES (%s, %s, %s, %s, %s, %s)",
    42.             (compare_id, call_id, field_name, expected_value, actual_value, match_result)
    43.         )

    动态参数的过滤

    在接口测试中,动态参数(如时间戳、随机数等)可能会导致对比结果的不一致。为了提高对比的准确性,需要在对比过程中对这些动态参数进行过滤。

    动态参数过滤的实现

    以下是动态参数过滤的示例代码,过滤掉返回结果中的动态字段:

    1. import requests
    2. import json
    3. # 动态参数过滤函数
    4. def filter_dynamic_params(response_data: dict, exclude_keys: list) -> dict:
    5.     """
    6.     过滤动态参数,排除不需要对比的字段。
    7.     """
    8.     return {k: v for k, v in response_data.items() if k not in exclude_keys}
    9. # 动态参数列表
    10. dynamic_params = ['timestamp''token''session_id']
    11. # 执行接口调用并对比结果
    12. def call_and_compare(execution_id, url, params, expected_response):
    13.     response = requests.post(url, json=params)
    14.     actual_response = response.json()
    15.     filtered_response = filter_dynamic_params(actual_response, dynamic_params)
    16.     filtered_expected_response = filter_dynamic_params(expected_response, dynamic_params)
    17.     compare_result = 'match' if filtered_expected_response == filtered_response else 'mismatch'
    18.     call_id = insert_api_call(execution_id, url, params, filtered_response, compare_result)
    19.     for key in filtered_expected_response:
    20.         if key in filtered_response:
    21.             match_result = 'match' if filtered_expected_response[key== filtered_response[keyelse 'mismatch'
    22.             insert_compare_result(call_id, key, filtered_expected_response[key], filtered_response[key], match_result)
    23. # 测试用例
    24. def test_interface():
    25.     execution_id = insert_test_execution(1)
    26.     url = "http://api.example.com/login"
    27.     params = {"username""test""password""test"}
    28.     expected_response = {"status""success""timestamp""ignore"}
    29.     call_and_compare(execution_id, url, params, expected_response)
    30.     # 更新测试执行状态
    31.     with Database() as db:
    32.         db.cursor.execute("UPDATE test_execution SET status = %s WHERE execution_id = %s", ('completed', execution_id))
    33. if __name__ == "__main__":
    34.     test_interface()

    集成对比结果的报告内容

    在测试执行完成后,我们可以生成一个对比结果报告,以展示测试的执行情况和结果。

    生成报告的代码示例
    1. from jinja2 import Template
    2. # 生成对比结果报告
    3. def generate_report(execution_id):
    4.     with Database() as db:
    5.         db.cursor.execute("""
    6.             SELECT a.api_endpoint, a.request_params, a.response_data, a.compare_result, c.field_name, c.expected_value, c.actual_value, c.match_result
    7.             FROM api_call a
    8.             JOIN compare_result c ON a.call_id = c.call_id
    9.             WHERE a.execution_id = %s
    10.         """, (execution_id,))
    11.         results = db.cursor.fetchall()
    12.     # Jinja2 模板
    13.     template_str = """
    14.     html>
    15.     <html>
    16.     <head><title>测试对比结果报告title>head>
    17.     <body>
    18.         <h1>测试对比结果报告h1>
    19.         <p><strong>测试执行ID:strong>{{ execution_id }}p>
    20.         <table border="1">
    21.             <tr>
    22.                 <th>接口地址th>
    23.                 <th>请求参数th>
    24.                 <th>返回数据th>
    25.                 <th>对比结果th>
    26.                 <th>字段名称th>
    27.                 <th>预期值th>
    28.                 <th>实际值th>
    29.                 <th>匹配结果th>
    30.             tr>
    31.             {% for row in results %}
    32.             <tr>
    33.                 <td>{{ row.api_endpoint }}td>
    34.                 <td>{{ row.request_params }}td>
    35.                 <td>{{ row.response_data }}td>
    36.                 <td>{{ row.compare_result }}td>
    37.                 <td>{{ row
    38. .field_name }}td>
    39.                 <td>{{ row.expected_value }}td>
    40.                 <td>{{ row.actual_value }}td>
    41.                 <td>{{ row.match_result }}td>
    42.             tr>
    43.             {% endfor %}
    44.         table>
    45.     body>
    46.     html>
    47.     """
    48.     template = Template(template_str)
    49.     html_report = template.render(execution_id=execution_id, results=results)
    50.     # 保存报告到文件
    51.     with open(f'report_{execution_id}.html', 'w') as f:
    52.         f.write(html_report)

    对比数据的清理

    测试完成后,需要对比数据进行清理,以保持数据库的健康状态。以下是手动和自动数据清理的示例代码。

    手动清理数据
    1. def manual_cleanup(execution_id):
    2.     with Database() as db:
    3.         db.cursor.execute("DELETE FROM compare_result WHERE call_id IN (SELECT call_id FROM api_call WHERE execution_id = %s)", (execution_id,))
    4.         db.cursor.execute("DELETE FROM api_call WHERE execution_id = %s", (execution_id,))
    5.         db.cursor.execute("DELETE FROM test_execution WHERE execution_id = %s", (execution_id,))
    自动清理数据
    1. import schedule
    2. import time
    3. # 自动清理任务
    4. def auto_cleanup():
    5.     with Database() as db:
    6.         db.cursor.execute("""
    7.             DELETE FROM compare_result WHERE compare_id IN (
    8.                 SELECT compare_id FROM compare_result
    9.                 WHERE compare_id NOT IN (
    10.                     SELECT compare_id FROM api_call WHERE execution_id IN (
    11.                         SELECT execution_id FROM test_execution WHERE status = 'completed'
    12.                     )
    13.                 )
    14.             )
    15.         """)
    16.         db.cursor.execute("""
    17.             DELETE FROM api_call WHERE call_id IN (
    18.                 SELECT call_id FROM api_call
    19.                 WHERE call_id NOT IN (
    20.                     SELECT call_id FROM compare_result
    21.                 )
    22.             )
    23.         """)
    24.         db.cursor.execute("""
    25.             DELETE FROM test_execution WHERE status = 'completed' AND execution_id NOT IN (
    26.                 SELECT execution_id FROM api_call
    27.             )
    28.         """)
    29. # 设置定时任务
    30. schedule.every().day.at("00:00").do(auto_cleanup)
    31. while True:
    32.     schedule.run_pending()
    33.     time.sleep(1)

    结论

    在本文中,我们详细探讨了接口测试返回参数的自动化对比方法,包括动态参数的过滤、对比结果的报告生成以及对比数据的清理。通过合理的工具和技术手段,可以显著提高接口测试的效率和效果。希望本文提供的实践经验和代码示例能帮助从事接口测试的技术人员在实际项目中更好地应用自动化对比技术,提高测试的质量和效率。

    最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 

    软件测试面试文档

    我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

    在这里插入图片描述

  • 相关阅读:
    多态(polymorphic)
    【Linux】:Kafka组件介绍
    爬虫实现自己的翻译服务器
    学习开发一个RISC-V上的操作系统(汪辰老师) — unrecognized opcode `csrr t0,mhartid‘报错问题
    GO语言-栈的应用-表达式求值
    博云入选国家级专精特新「小巨人」名单!
    含免费次数的常用API接口
    ​怎么测试websocket接口
    设计模式-外观模式
    swiper的使用,一次显示多个,竖着排列,多行多列
  • 原文地址:https://blog.csdn.net/jiangjunsss/article/details/140400360