云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

swagger自动化测试

jxf315 2025-05-28 18:07:27 教程文章 14 ℃

首先,我需要确认用户对Swagger的了解程度。Swagger,也就是现在的OpenAPI,常用于API的设计和文档生成。自动化测试可能指的是如何利用Swagger文档来自动生成测试用例,或者集成到测试流程中。

用户可能是开发人员或者测试人员,希望提高API测试的效率,减少手动工作。他们可能已经使用Swagger来编写API文档,现在想进一步自动化测试流程。可能的深层需求包括节省时间、确保API的稳定性和一致性,或者在持续集成/持续部署(CI/CD)中集成自动化测试。

接下来,我需要介绍Swagger自动化测试的基本概念,可能提到的工具如Swagger UI、Postman、Newman等。还要说明如何将Swagger文档转换为测试用例,可能需要用到Swagger Codegen或相关的测试框架。另外,持续集成部分需要提到如何与Jenkins、GitHub Actions等工具结合。

需要注意的几点:用户可能对不同的工具不熟悉,需要简要说明每个工具的作用;可能遇到如何验证响应数据、处理认证的问题,需要给出解决方案;性能测试和模拟服务也是高级需求,可以稍微提及。

最后,要确保内容结构清晰,分步骤解释,提供示例命令或代码片段,帮助用户实际操作。可能还需要提醒用户注意维护测试用例与API变更同步,避免过时的测试。

当然,最主要的还是要解决开发人员懒得手动测试的问题。

这个东西比较费token,所以,最好还是用的免费的,推荐用
https://bailian.console.aliyun.com/#/home


没有的先获取免费的


import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"), # 如何获取API Key:https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen-plus", # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': '你是谁?'}
        ]
)
print(completion.choices[0].message.content)

先测试下,确定本地环境好用。

首先我们会通过swagger的地址,一般是:
http://localhost:8080/v3/api-docs/1

具体要看代码的配置文件。

通过这个地址我们可以抓取,需要测试的接口,入参以及约束等等。

    def _load_swagger_spec(self):
        """
        加载并解析Swagger文档
        """
        try:
            response = requests.get(self)
            response.raise_for_status()
            return response.json()  # 假设Swagger文档返回JSON格式(YAML需额外解析)
        except Exception as e:
            raise ValueError(f"加载Swagger文档失败: {str(e)}")

然后,我们可以通过大语音模型自动生成测试数据。当然,要针对定义的入参进行约束。

        """
        使用OpenAI生成符合schema的测试数据(严格遵循Swagger类型定义)
        
        :param schema: 参数的JSON Schema定义(包含type、properties、required等字段)
        :return: 生成的测试数据字典(严格符合Schema的属性定义)
        """
        # 提取Schema关键约束信息(类型、属性、必填项、格式)
        schema_type = schema.get("type", "object")
        schema_properties = schema.get("properties", {})
        schema_required = schema.get("required", [])
        schema_format = schema.get("format", "")

还需要针对特殊的类型进行一系列的转换。未了避免token的浪费,针对集合的数据,我们一般会少给几条数据。


        # 处理时间格式的特殊情况
        if schema_format == "date-time":
            # 生成符合yyyy-mm-dd hh:mm:ss格式的示例时间
            example_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            return example_time

            # 处理数组类型参数(集合)
        if schema_type == "array":
            items_schema = schema.get("items", {})
            # 生成2-3条符合items schema的数据
            return [
                self._generate_test_data(items_schema),
                self._generate_test_data(items_schema),
                self._generate_test_data(items_schema)
            ]

大模型的提示,以及校验。

        # 构造更详细的提示,明确要求生成符合类型/属性/必填项的JSON
        prompt = f"""请根据以下JSON Schema严格生成测试数据:
        - 类型: {schema_type}
        - 属性定义: {json.dumps(schema_properties, indent=2)}
        - 必填属性: {schema_required if schema_required else "无"}
        - 格式要求: {schema_format if schema_format else "无"}
        要求返回的JSON对象必须:
        1. 包含所有必填属性({schema_required})
        2. 每个属性的类型与Schema中定义的type完全一致
        3. 字符串类型属性若有format(如date、email)需符合对应格式
        仅输出JSON内容,无需额外说明。"""

        try:
            # 调用LLM生成数据
            chat_response = self.openai_client.invoke(
                [{"role": "user", "content": prompt}]
            )
            generated_data = json.loads(chat_response.content)
            
            # 验证生成的数据是否符合Schema(补充数据验证逻辑)
            self.validator.validate(generated_data, schema)  # 直接验证数据与目标Schema的匹配性
            return generated_data
        except Exception as e:
            raise ValueError(f"OpenAI生成测试数据失败(不符合Schema约束): {str(e)}")

最后对测试数据进行一个本地化的保存,这个随便吧。

        """
        执行所有接口测试并输出结果(含本地文件保存)
        """
        # 创建测试结果目录(Windows路径格式)
        result_dir = os.path.join(os.getcwd(), "test_results")
        os.makedirs(result_dir, exist_ok=True)  # 自动创建目录(若不存在)

        # 遍历Swagger中的所有接口路径
        for path, path_item in self.swagger_spec.get("paths", {}).items():
            # 遍历路径的所有HTTP方法(如get/post)
            for method, operation in path_item.items():
                print(f"\n===== 开始测试接口:{method.upper()} {path} =====")
                
                # 构造测试用例基础信息
                test_case = {
                    "接口路径": path,
                    "请求方法": method.upper(),
                    "描述": operation.get("summary", "无描述")
                }

                # 处理请求参数(这里简化处理请求体参数,实际需处理path/query/header等参数类型)
                request_body = None
                if "requestBody" in operation:
                    # 获取application/json类型的请求体schema
                    json_media_type = operation["requestBody"]["content"].get("application/json")
                    if json_media_type:
                        schema = json_media_type["schema"]
                        # 验证schema有效性
                        self.validator.validate(schema)
                        # 生成测试数据
                        request_body = self._generate_test_data(schema)
                        test_case["入参数据"] = request_body

                # 执行请求(简化示例,实际需处理路径参数替换、认证等)
                try:
                    response = requests.request(
                        method=method,
                        url=f"{self.swagger_spec.get('servers', [{'url': ''}])[0]['url']}{path}",
                        json=request_body
                    )
                    test_case["响应状态码"] = response.status_code
                    test_case["响应内容"] = response.json() if response.headers.get("Content-Type") == "application/json" else response.text
                    
                    # 检查是否出错(示例判断状态码是否非2xx)
                    if not 200 <= response.status_code < 300:
                        test_case["错误信息"] = "接口返回非成功状态码"
                except Exception as e:
                    test_case["错误信息"] = f"请求执行失败: {str(e)}"

                # 输出测试结果到终端并保存到文件
                print("测试用例信息:")
                print(json.dumps(test_case, indent=2, ensure_ascii=False))

                # 生成带时间戳的文件名(Windows兼容格式)
                timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
                filename = f"{timestamp}_{method.upper()}_{path.replace('/', '_')}.json"
                file_path = os.path.join(result_dir, filename)

                # 写入本地文件(UTF-8编码避免中文乱码)
                with open(file_path, "w", encoding="utf-8") as f:
                    json.dump(test_case, f, indent=2, ensure_ascii=False)
                    print(f"测试结果已保存至:{file_path}")

嗯,最后,要谨慎,要不送的那点免费的token,几天就用没了。

Tags:

最近发表
标签列表