ai:把用例捡起来!把用例捡起来!
给大模型需求文档,让它完成设计用例,编写用例,包括功能用例、接口用例、自动化测试用例,自执行~最后发送至工作群中
直接使用deepseek即可
执行一下看看:
调用ds分析需求:
生成功能/接口用例:
生成自动化用例:
看一下自动生成的功能用例和接口用例:
# 为了验证用户登录功能,我们将使用 `pytest` 框架和 `requests` 库来进行 API 测试。以下是一个示例代码,展示了如何实现这个测试用例。
#
# ### 安装依赖
# 首先,确保你已经安装了 `pytest` 和 `requests` 库。如果没有安装,可以使用以下命令进行安装:
#
# ```bash
# pip install pytest requests
# ```
#
# ### 测试代码
#
# ```python
import pytest
import requests# 定义登录API的URL
LOGIN_URL = "http://127.0.0.1:5000/login"# 测试用例:验证用户登录功能
def test_user_login():# 定义测试数据username = "user1"password = "password1"# 构造请求体payload = {"username": username,"password": password}# 发送POST请求到登录API端点response = requests.post(LOGIN_URL, json=payload)# 验证响应状态码是否为200assert response.status_code == 200, f"Expected status code 200, but got {response.status_code}"# 解析API响应response_data = response.json()# 验证响应中是否包含预期的字段assert "token" in response_data, "Response does not contain 'token' field"assert "user_id" in response_data, "Response does not contain 'user_id' field"# 验证token和user_id是否有效assert isinstance(response_data["token"], str), "Token is not a string"assert isinstance(response_data["user_id"], int), "User ID is not an integer"# 运行测试
if __name__ == "__main__":pytest.main()
# ```
#
# ### 代码说明
#
# 1. **LOGIN_URL**: 这是登录API的URL,你需要将其替换为实际的API端点。
#
# 2. **test_user_login**: 这是测试函数,使用 `pytest` 框架进行测试。
#
# 3. **payload**: 这是发送到API的请求体,包含用户名和密码。
#
# 4. **requests.post**: 发送POST请求到登录API端点。
#
# 5. **assert response.status_code == 200**: 验证响应状态码是否为200,表示请求成功。
#
# 6. **response.json()**: 解析API响应为JSON格式。
#
# 7. **assert "token" in response_data**: 验证响应中是否包含 `token` 字段。
#
# 8. **assert "user_id" in response_data**: 验证响应中是否包含 `user_id` 字段。
#
# 9. **assert isinstance(response_data["token"], str)**: 验证 `token` 是否为字符串类型。
#
# 10. **assert isinstance(response_data["user_id"], int)**: 验证 `user_id` 是否为整数类型。
#
# ### 运行测试
#
# 你可以通过以下命令运行测试:
#
# ```bash
# pytest test_login.py
# ```
#
# 如果所有断言都通过,测试将成功完成。如果有任何断言失败,`pytest` 将输出详细的错误信息,帮助你定位问题。"""
自动化测试执行器
"""
import pytest
import os
import sys
from datetime import datetime
from typing import List, Dict
import json
from dotenv import load_dotenv# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "../../../.."))
src_dir = os.path.join(project_root, "ai-test-generator", "src")
sys.path.insert(0, src_dir)# 加载环境变量
env_path = os.path.join(project_root, "ai-test-generator", ".env")
print(f"正在加载环境变量文件: {env_path}")
load_dotenv(env_path)try:from test_reporter import TestReporter, TestResult
except ImportError as e:print(f"错误:无法导入test_reporter模块。请确保项目结构正确。")print(f"当前目录: {current_dir}")print(f"项目根目录: {project_root}")print(f"src目录: {src_dir}")print(f"Python路径: {sys.path}")raise edef run_tests(test_files: List[str] = None) -> bool:"""
运行测试用例并生成报告Args:test_files: 要运行的测试文件列表,如果为None则运行所有测试Returns:bool: 所有测试是否通过"""
print("\n开始执行测试...")# 初始化测试报告器reporter = TestReporter()# 如果没有指定测试文件,则运行所有测试if test_files is None:test_files = [f for f in os.listdir(os.path.dirname(__file__)) if f.endswith('_test.py') and f != '_automation.py']print(f"将运行所有测试文件: {test_files}")all_passed = Truefor test_file in test_files:test_path = os.path.join(os.path.dirname(__file__), test_file)test_id = os.path.splitext(test_file)[0]print(f"\n执行测试文件: {test_file}")# 记录测试执行start_time = datetime.now()try:# 运行测试result = pytest.main([test_path, '-v'])status = 'passed' if result == 0 else 'failed'error_msg = None if result == 0 else 'Test execution failed'if result != 0:all_passed = Falseprint(f"测试执行结果: {status}")except Exception as e:status = 'error'error_msg = str(e)all_passed = Falseprint(f"测试执行出错: {e}")duration = (datetime.now() - start_time).total_seconds()# 记录测试结果reporter.add_test_result(TestResult(test_id=test_id,test_name=test_file,test_type='api',status=status,duration=duration,error_message=error_msg,start_time=start_time.isoformat(),end_time=datetime.now().isoformat()))# 生成并保存报告reports_dir = os.path.join(project_root, "ai-test-generator", "test_cases", "reports")reporter.save_report(reports_dir)# 发送钉钉通知print("\n准备发送测试报告...")reporter.send_dingtalk_notification()print(f"\n测试执行完成,{'全部通过' if all_passed else '存在失败'}")return all_passedif __name__ == "__main__":# 获取命令行参数中的测试文件test_files = sys.argv[1:] if len(sys.argv) > 1 else None# 运行测试success = run_tests(test_files)# 设置退出码sys.exit(0 if success else 1)
metadata:id: FUNC_1__20250313_155452type: functionalfeature: 1._**用户登录功能**:generated_time: '2025-03-13T15:54:52.411287'
test_case:title: 用户登录功能测试description: 验证用户登录功能是否正常工作,确保用户能够通过正确的用户名和密码成功登录系统。test_type: functionalprerequisites:- 系统已安装并运行- 用户已注册并拥有有效的用户名和密码steps:- 打开登录页面- 输入有效的用户名- 输入有效的密码- 点击登录按钮expected_results:- 登录页面成功加载- 用户名和密码输入框接受输入- 登录按钮可点击- 用户成功登录并跳转到主页test_data:username: testuserpassword: testpassword
本地简单写了个登录接口,用生成的用例跑一下,看看收集结果以及发送结果的功能
接口:
改改用例里面的url和参数:
report中的内容:
发送的wehook通知: