ubuntu

ubuntu swagger如何进行API测试覆盖率

小樊
33
2025-12-18 04:35:18
栏目: 智能运维

Ubuntu下基于Swagger的API测试覆盖率实践

一、总体思路与覆盖维度

二、快速落地流程

三、示例脚本与计算方式

import requests, json

def load_swagger(url):
    r = requests.get(url, timeout=10)
    r.raise_for_status()
    return r.json()

def extract_operations(spec):
    ops = set()
    for path, methods in spec.get("paths", {}).items():
        for method in methods:
            if method.lower() in {"get","post","put","patch","delete","head","options","trace"}:
                ops.add((method.upper(), path))
    return ops

spec = load_swagger("http://localhost:8080/v2/api-docs")  # 或 /swagger.json
total_ops = extract_operations(spec)
print("Total operations:", len(total_ops))
# 假设在测试执行过程中收集到
called_ops = {
    ("GET", "/users"), ("GET", "/users/{id}"), ("POST", "/login")
}

covered = len(called_ops & total_ops)
coverage = covered / len(total_ops) * 100
print(f"Coverage: {coverage:.2f}%")
uncovered = total_ops - called_ops
print("Uncovered:", uncovered)

四、提升覆盖率的关键做法

五、工具与CI集成建议

0
看了该问题的人还看了