# api_automation_framework **Repository Path**: lldhsds/api_automation_framework ## Basic Information - **Project Name**: api_automation_framework - **Description**: 接口自动化框架:多项目接口管理的最佳实践 - **Primary Language**: Python - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-12-26 - **Last Updated**: 2025-04-17 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # api_automation_framework ## 介绍 接口自动化框架:多项目接口管理的最佳实践。 原文: ## 目录结构 ```bash api_automation_framework/ │ ├── config/ # 配置文件存放位置 │ ├── settings.py # 全局配置 │ └── environments.yaml # 环境配置(如开发、测试、生产) │ ├── logs/ # 日志文件存放位置 │ ├── reports/ # 测试报告存放位置 │ ├── tests/ # 测试用例存放位置 │ ├── __init__.py │ ├── conftest.py # pytest fixtures 和钩子函数 │ ├── test_project_a/ # 项目 A 的测试用例 │ │ ├── __init__.py │ │ └── test_api.py │ ├── test_project_b/ # 项目 B 的测试用例 │ │ ├── __init__.py │ │ └── test_api.py │ └── ... │ ├── utils/ # 工具类和辅助函数 │ ├── __init__.py │ ├── api_client.py # 封装的 HTTP 客户端 │ ├── data_generator.py # 数据生成器 │ └── helpers.py # 辅助函数 │ ├── requirements.txt # 依赖包列表 └── run_tests.sh # 执行测试的脚本 ``` ## 配置管理 (config/settings.py) 全局配置文件用于设置通用参数,例如默认的日志级别、超时时间等。 ```python # config/settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # 默认配置 DEFAULT_LOG_LEVEL = 'INFO' DEFAULT_TIMEOUT = 30 # seconds # 获取环境变量或使用默认值 ENVIRONMENT = os.getenv('ENV', 'development') # 根据环境加载不同的配置 if ENVIRONMENT == 'production': from .environments_production import * elif ENVIRONMENT == 'testing': from .environments_testing import * else: from .environments_development import * ``` ## HTTP 客户端封装 (utils/http_client.py) 封装 requests 库以简化 API 请求并处理异常。 ```bash # utils/api_client.py import requests import logging from requests.exceptions import RequestException class HttpClient: def __init__(self, base_url, headers=None): self.base_url = base_url.rstrip('/') self.headers = headers or {} self.session = requests.Session() self.session.headers.update(self.headers) def get(self, endpoint, params=None, **kwargs): return self._request('GET', endpoint, params=params, **kwargs) def post(self, endpoint, data=None, json=None, **kwargs): return self._request('POST', endpoint, data=data, json=json, **kwargs) def _request(self, method, endpoint, **kwargs): url = f'{self.base_url}/{endpoint.lstrip("/")}' try: response = self.session.request(method, url, **kwargs) response.raise_for_status() logging.info(f"{method} {url} - Response Status: {response.status_code}") return response except RequestException as e: logging.error(f"Error during {method} request to {url}: {e}") return None def close(self): self.session.close() ``` ## 测试用例 (tests/test_project_a/test_api.py) 编写具体的测试用例,利用 pytest 框架进行参数化测试。 ```python # tests/test_project_a/test_api.py import pytest from utils.api_client import HttpClient @pytest.fixture(scope='module') def client(): base_url = "https://api.project-a.com" headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'} return HttpClient(base_url, headers) def test_get_user_info(client): response = client.get('/user/123') assert response.status_code == 200 user_data = response.json() assert 'id' in user_data and user_data['id'] == 123 @pytest.mark.parametrize("payload", [ {"name": "Alice", "email": "alice@example.com"}, {"name": "Bob", "email": "bob@example.com"} ]) def test_create_user(client, payload): response = client.post('/users', json=payload) assert response.status_code == 201 created_user = response.json() assert created_user['name'] == payload['name'] ``` ## pytest配置文件 pytest配置文件用于配置 pytest 的行为,包括测试的目录、插件、报告格式等。 配置文件位于项目根目录下`pytest.ini`,根据需求进行调整。 ## 运行测试 可以实用脚本启动测试、或者使用pytest命令启动。 ### 脚本启动 编写一个简单的 shell 脚本`run_test.sh`来安装依赖并运行所有测试。 ```bash #!/bin/bash # 安装依赖 pip install -r requirements.txt # 运行测试并生成 HTML 报告 pytest --html=reports/report.html ``` 运行脚本:`sh run_tests.sh` ### pytest测试 如果已经安装了依赖,可以在项目根路径下直接运行 pytest 命令来运行所有测试。 也可以运行某一个测试用例: ```bash pytest tests/anything/test_anything.py pytest tests/anything/test_anything.py::test_get_anything ``` ## 最佳实践总结 - 模块化:每个功能都被封装在独立的模块中,提高了代码复用性和维护性。 - 配置管理:使用配置文件和环境变量分离不同环境下的配置信息。 - 测试用例组织:按照项目或功能模块划分测试用例,保持良好的代码结构。 - 日志记录:通过 logging 模块记录详细的日志信息,便于调试和追踪问题。 - 报告生成:集成 pytest-html 插件自动生成美观且详细的测试报告。 - 持续改进:定期回顾框架的表现,根据项目需求和技术发展不断优化和完善。 ## 相关工具 1. httpbin:一个用于测试 HTTP 请求和响应的网站。 - github: - - - - - - ## 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request