【工程实战】第十篇:性能监控集成 —— 自动化脚本的“副产品”:不仅仅是功能测试

专栏进度:10 / 10 (自动化实战专题 · 完结)

核心逻辑:利用 Pytest 的钩子函数(Hooks),在执行每一个功能测试用例时,同步记录接口响应耗时与服务器资源消耗。

一、 为什么要监控自动化脚本的"副产品"?

预警"性能退化":代码改动可能没产生 Bug,但产生了性能瓶颈。

定位"偶发超时":有些接口在特定数据组合下会变慢,功能测试能顺便捕捉到这些异常。

零成本性能基准:无需专门跑脚本,日常的回归测试就能沉淀出一套系统的性能趋势图。

二、 实战 1:接口响应时间监控(全自动埋点)

我们不需要修改任何测试用例,只需在 conftest.py 中利用 requests 的封装,将耗时数据写入 Allure 报告。

Python

python 复制代码
# common/request_util.py (增强版)
import time
import allure

class RequestUtil:
    def send_request(self, method, url, **kwargs):
        start_time = time.time()
        res = requests.request(method, url, **kwargs)
        end_time = time.time()
        
        # 计算耗时并计算毫秒
        duration = (end_time - start_time) * 1000
        
        # 自动将耗时数据塞进 Allure 报告的属性中
        allure.dynamic.parameter("Response Time (ms)", f"{duration:.2f}")
        
        # 如果响应超过阈值,标记一个警告
        if duration > 1000:
            print(f"⚠️ 预警:接口 {url} 响应过慢: {duration:.2f}ms")
            
        return res

三、 实战 2:服务器资源异步监控(侧信道采集)

在测试执行期间,我们可以启动一个异步线程,通过 psutil 库或调用 Prometheus 接口记录服务器状态。

Python

python 复制代码
# common/monitor_util.py
import psutil
import threading
import time

class ServerMonitor(threading.Thread):
    def __init__(self, interval=1):
        super().__init__()
        self.interval = interval
        self.stopped = False
        self.stats = []

    def run(self):
        while not self.stopped:
            cpu = psutil.cpu_percent()
            mem = psutil.virtual_memory().percent
            self.stats.append({"time": time.time(), "cpu": cpu, "mem": mem})
            time.sleep(self.interval)

    def stop(self):
        self.stopped = True
        return self.stats

# 在 conftest.py 中作为全局 Fixture 调用
@pytest.fixture(scope="session", autouse=True)
def monitor_server():
    monitor = ServerMonitor()
    monitor.start()
    yield
    stats = monitor.stop()
    # 结束后可以将统计图表附在 Allure 报告的总览页

四、 进阶:构建性能回归曲线

将每次 CI 运行后的平均响应时间存入数据库,你可以画出这样一张图:

X轴:构建版本号(Build #1, #2, #3...)

Y轴:核心链路平均响应时间

价值:如果看到曲线异常上扬,说明最近的 Commit 引入了性能缺陷。

五、 本专题总结:自动化框架的"完全体"

历经 10 篇实战,我们亲手搭建了一套具备以下能力的工厂级框架:

底层:Pytest 环境隔离与配置。

弹药:YAML 数据驱动与逻辑分离。

武器:Requests 接口封装与 Playwright UI 异步。

架构:POM 页面对象模式,实现极低维护成本。

防御:Mock 技术屏蔽外部干扰。

底线:SQL 数据库断言直击真相。

展示:Allure 深度定制的精美战报。

交付:Jenkins/GitLab CI 24小时无人值守流水线。

溢出价值:性能监控集成。

相关推荐
MageGojo8 分钟前
10 种主题随机诗词:一个 API 解决小程序的诗词内容源
python·小程序·古诗词·api 接入
cooldream200917 分钟前
使用 uv 管理 Python 虚拟环境:现代 Python 开发的高效实践
python·uv·mcp
一拳一个娘娘腔25 分钟前
【SRC漏洞挖掘系列】第15期:自动化与AI赋能 —— 打造你的专属“漏洞挖掘机”
运维·人工智能·自动化
zhangfeng113325 分钟前
国家超算中心 系统自带模型 和pytorch 和cuda版本
人工智能·pytorch·python
m0_7381207232 分钟前
渗透测试基础——黑盒测试下的Web漏洞挖掘与利用解析(二)
服务器·前端·python·网络协议·安全·网络安全
玫幽倩40 分钟前
2025FIC取证决赛wp(手机取证)
python·智能手机·手机·电子取证·计算机取证·手机取证·fic
多彩电脑41 分钟前
Kivy如何自定义事件
开发语言·python
java_cj42 分钟前
LangChain初入门 - 简化LLM开发难度的利器
开发语言·python·langchain
sleven fung1 小时前
llama-cpp-python 本地部署入门
开发语言·python·算法·llama
li星野1 小时前
RAG优化系列:基于用户反馈的检索权重调整(Feedback Loop)——让系统越用越聪明
python·学习