add:flask app

This commit is contained in:
gongwenxin
2025-06-06 14:52:08 +08:00
parent b72406df99
commit adc1a0053f
18 changed files with 4726 additions and 3468 deletions
+68 -56
View File
@@ -12,7 +12,7 @@
<div class="configuration-section">
<h2>测试配置</h2>
<form id="test-config-form">
<form id="test-form">
<div class="form-group">
<label for="base_url">API 基础URL (必填):</label>
<input type="text" id="base_url" name="base_url" required placeholder="例如:http://localhost:8080/api/v1">
@@ -21,73 +21,85 @@
<fieldset>
<legend>API 定义源 (选择一个)</legend>
<div class="form-group">
<label for="yapi_file_path">YAPI 文件路径:</label>
<input type="text" id="yapi_file_path" name="yapi_file_path" placeholder="例如:./assets/doc/yapi_spec.json">
<button type="button" class="action-button" onclick="fetchYapiCategories()">加载分类</button>
<div id="yapi-categories-container" class="categories-tags-container"></div>
<label for="api_spec_type">API 规范类型:</label>
<select id="api_spec_type" name="api_spec_type">
<option value="YAPI">YAPI (.json)</option>
<option value="Swagger">Swagger/OpenAPI (.json, .yaml)</option>
</select>
</div>
<div class="form-group">
<label for="swagger_file_path">Swagger/OpenAPI 文件路径:</label>
<input type="text" id="swagger_file_path" name="swagger_file_path" placeholder="例如:./assets/doc/swagger_spec.json">
<button type="button" class="action-button" onclick="fetchSwaggerTags()">加载标签</button>
<div id="swagger-tags-container" class="categories-tags-container"></div>
<label for="api_spec_file">上传 API 规范文件:</label>
<input type="file" id="api_spec_file" name="api_spec_file" accept=".json,.yaml,.yml" required>
</div>
<div class="form-group">
<button type="button" id="load-spec-btn">加载分类/标签</button>
</div>
<div id="yapi-categories-container" class="checkbox-container"></div>
<div id="swagger-tags-container" class="checkbox-container"></div>
</fieldset>
<div class="form-group">
<label for="custom_test_cases_dir">自定义测试用例目录:</label>
<input type="text" id="custom_test_cases_dir" name="custom_test_cases_dir" placeholder="例如:./custom_testcases">
</div>
<div class="form-group">
<label for="scenarios_dir">自定义场景目录:</label>
<input type="text" id="scenarios_dir" name="scenarios_dir" placeholder="例如:./custom_scenarios">
</div>
<div class="form-group">
<label for="output_dir">报告输出目录:</label>
<input type="text" id="output_dir" name="output_dir" placeholder="例如:./test_reports">
</div>
<details>
<summary>高级配置 (点击展开)</summary>
<div class="form-group">
<label for="custom_test_cases_dir">自定义测试用例目录:</label>
<input type="text" id="custom_test_cases_dir" name="custom_test_cases_dir" placeholder="例如:./custom_testcases" value="./custom_testcases">
</div>
<div class="form-group">
<label for="stages_dir">自定义阶段目录:</label>
<input type="text" id="stages_dir" name="stages_dir" placeholder="例如:./custom_stages" value="./custom_stages">
</div>
<div class="form-group">
<label for="output_dir">报告输出目录:</label>
<input type="text" id="output_dir" name="output_dir" placeholder="例如:./test_reports" value="./test_reports">
</div>
</details>
<fieldset>
<legend>LLM 配置 (可选)</legend>
<div class="form-group">
<label for="llm_api_key">LLM API Key:</label>
<input type="password" id="llm_api_key" name="llm_api_key" placeholder="留空则尝试读取环境变量">
</div>
<div class="form-group">
<label for="llm_base_url">LLM Base URL:</label>
<input type="text" id="llm_base_url" name="llm_base_url" placeholder="例如:https://dashscope.aliyuncs.com/compatible-mode/v1">
</div>
<div class="form-group">
<label for="llm_model_name">LLM 模型名称:</label>
<input type="text" id="llm_model_name" name="llm_model_name" placeholder="例如:qwen-plus">
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_request_body" name="use_llm_for_request_body">
<label for="use_llm_for_request_body">使用LLM生成请求体</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_path_params" name="use_llm_for_path_params">
<label for="use_llm_for_path_params">使用LLM生成路径参数</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_query_params" name="use_llm_for_query_params">
<label for="use_llm_for_query_params">使用LLM生成查询参数</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_headers" name="use_llm_for_headers">
<label for="use_llm_for_headers">使用LLM生成头部参数</label>
</div>
</fieldset>
<details>
<summary>LLM 配置 (可选, 点击展开)</summary>
<fieldset>
<legend>LLM 配置 (可选)</legend>
<div class="form-group">
<label for="llm_api_key">LLM API Key:</label>
<input type="password" id="llm_api_key" name="llm_api_key" placeholder="留空则尝试读取环境变量">
</div>
<div class="form-group">
<label for="llm_base_url">LLM Base URL:</label>
<input type="text" id="llm_base_url" name="llm_base_url" placeholder="例如:https://dashscope.aliyuncs.com/compatible-mode/v1">
</div>
<div class="form-group">
<label for="llm_model_name">LLM 模型名称:</label>
<input type="text" id="llm_model_name" name="llm_model_name" placeholder="例如:qwen-plus">
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_request_body" name="use_llm_for_request_body">
<label for="use_llm_for_request_body">使用LLM生成请求体</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_path_params" name="use_llm_for_path_params">
<label for="use_llm_for_path_params">使用LLM生成路径参数</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_query_params" name="use_llm_for_query_params">
<label for="use_llm_for_query_params">使用LLM生成查询参数</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="use_llm_for_headers" name="use_llm_for_headers">
<label for="use_llm_for_headers">使用LLM生成头部参数</label>
</div>
</fieldset>
</details>
<button type="submit" class="submit-button">运行测试</button>
</form>
</div>
<div class="results-section">
<h2>测试状态与结果</h2>
<div id="status-area">等待配置并运行测试...</div>
<pre id="results-output"></pre>
<div id="report-link-area"></div>
<h2>测试日志与结果</h2>
<label for="log-output">实时日志:</label>
<textarea id="log-output" readonly style="width:100%"></textarea>
<div id="results-container">
<!-- 测试结果将在此处动态生成 -->
</div>
</div>
</div>
+123 -124
View File
@@ -1,140 +1,139 @@
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('test-config-form');
const statusArea = document.getElementById('status-area');
const resultsOutput = document.getElementById('results-output');
const reportLinkArea = document.getElementById('report-link-area');
const form = document.getElementById('test-form');
const logOutput = document.getElementById('log-output');
const resultsContainer = document.getElementById('results-container');
const loadSpecBtn = document.getElementById('load-spec-btn');
const apiSpecFileInput = document.getElementById('api_spec_file');
const apiSpecTypeSelect = document.getElementById('api_spec_type');
const yapiCategoriesContainer = document.getElementById('yapi-categories-container');
const swaggerTagsContainer = document.getElementById('swagger-tags-container');
// Make the log output area larger as per user request
if (logOutput) {
logOutput.rows = 25;
}
// Event listener for the new "Load Categories/Tags" button
if (loadSpecBtn) {
loadSpecBtn.addEventListener('click', async () => {
const specType = apiSpecTypeSelect.value;
const file = apiSpecFileInput.files[0];
if (!file) {
alert('请先选择一个 API 规范文件。');
return;
}
const formData = new FormData();
formData.append('api_spec_file', file);
let url = '';
let container = null;
if (specType === 'YAPI') {
url = '/list-yapi-categories';
container = yapiCategoriesContainer;
swaggerTagsContainer.style.display = 'none';
yapiCategoriesContainer.style.display = 'block';
} else { // Swagger
url = '/list-swagger-tags';
container = swaggerTagsContainer;
yapiCategoriesContainer.style.display = 'none';
swaggerTagsContainer.style.display = 'block';
}
container.innerHTML = '<p>正在加载...</p>';
try {
const response = await fetch(url, {
method: 'POST',
body: formData, // Send FormData directly
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: '无法解析错误响应' }));
throw new Error(errorData.error || `请求 ${specType} 分类/标签时出错`);
}
const data = await response.json();
renderItemsList(container, data, specType); // Using a simplified renderer
} catch (error) {
console.error(`请求${specType}分类时出错:`, error);
container.innerHTML = `<p class="error">加载失败: ${error.message}</p>`;
}
});
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
statusArea.textContent = '正在运行测试,请稍候...';
resultsOutput.textContent = '';
reportLinkArea.innerHTML = '';
logOutput.value = '正在开始测试...\n';
resultsContainer.innerHTML = '';
// FormData will correctly handle all form fields, including the file upload
const formData = new FormData(form);
const config = {};
formData.forEach((value, key) => {
// 处理复选框
if (key.startsWith('use_llm_for_')) {
config[key] = form.elements[key].checked;
} else if (value.trim() !== '') { // 只添加非空值
config[key] = value.trim();
}
});
// 如果复选框未被选中,FormData 不会包含它们,所以要确保它们是 false
['use_llm_for_request_body', 'use_llm_for_path_params', 'use_llm_for_query_params', 'use_llm_for_headers'].forEach(key => {
if (!(key in config)) {
config[key] = false;
}
});
// 从 YAPI 分类和 Swagger 标签中获取选中的项
const selectedYapiCategories = Array.from(document.querySelectorAll('#yapi-categories-container input[type="checkbox"]:checked'))
.map(cb => cb.value);
if (selectedYapiCategories.length > 0) {
config['categories'] = selectedYapiCategories.join(',');
}
const selectedSwaggerTags = Array.from(document.querySelectorAll('#swagger-tags-container input[type="checkbox"]:checked'))
.map(cb => cb.value);
if (selectedSwaggerTags.length > 0) {
config['tags'] = selectedSwaggerTags.join(',');
}
try {
const response = await fetch('/run-tests', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(config)
// For FormData, the browser sets the Content-Type to multipart/form-data with the correct boundary.
// Do not set the 'Content-Type' header manually.
body: formData,
});
const result = await response.json();
if (response.ok) {
statusArea.textContent = `测试完成: ${result.message || '成功'}`;
resultsOutput.textContent = JSON.stringify(result.summary, null, 2);
if (result.report_file) {
reportLinkArea.innerHTML = `<p>测试报告已保存到: <strong>${result.report_file}</strong></p>`;
}
} else {
statusArea.textContent = `测试失败: ${result.error || '未知错误'}`;
resultsOutput.textContent = JSON.stringify(result, null, 2);
if (!response.ok) {
// Try to parse the error, provide a fallback message.
const errorMessage = result.error || '运行测试时发生未知错误';
logOutput.value += `\n错误: ${errorMessage}`;
throw new Error(errorMessage);
}
// Restore summary to the log output
logOutput.value += '\n测试执行完成。\n\n';
logOutput.value += '--- 测试摘要 ---\n';
logOutput.value += JSON.stringify(result.summary, null, 2);
displayResults(result);
} catch (error) {
statusArea.textContent = '运行测试时发生网络错误或服务器内部错误。';
resultsOutput.textContent = error.toString();
console.error('运行测试出错:', error);
console.error('运行测试时捕获到错误:', error);
logOutput.value += `\n\n发生严重错误: ${error.message}`;
resultsContainer.innerHTML = `<p class="error">测试运行失败: ${error.message}</p>`;
}
});
// A simplified function to render categories/tags as a list
function renderItemsList(container, items, type) {
if (!items || items.length === 0) {
container.innerHTML = '<p>未找到任何项。</p>';
return;
}
let html = `<h4>${type} ${type === 'YAPI' ? '分类' : '标签'}:</h4><ul>`;
items.forEach(item => {
html += `<li><strong>${item.name}</strong>: ${item.description || '无描述'}</li>`;
});
html += '</ul>';
container.innerHTML = html;
}
function displayResults(result) {
// Per user request, only show download links and remove the summary view.
let linksHtml = '<h3>下载报告</h3>';
if (result.summary_report_path) {
linksHtml += `<p><a href="${result.summary_report_path}" target="_blank" class="report-link">摘要报告 (JSON)</a></p>`;
}
if (result.details_report_path) {
linksHtml += `<p><a href="${result.details_report_path}" target="_blank" class="report-link">API 调用详情 (Markdown)</a></p>`;
}
if (!result.summary_report_path && !result.details_report_path) {
linksHtml += '<p>没有可用的报告文件。</p>';
}
resultsContainer.innerHTML = linksHtml;
}
});
async function fetchYapiCategories() {
const yapiFilePath = document.getElementById('yapi_file_path').value;
const container = document.getElementById('yapi-categories-container');
container.innerHTML = '正在加载分类...';
if (!yapiFilePath) {
container.innerHTML = '<p style="color: red;">请输入YAPI文件路径。</p>';
return;
}
try {
const response = await fetch('/list-yapi-categories', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ yapi_file_path: yapiFilePath })
});
const categories = await response.json();
if (response.ok) {
renderCheckboxes(container, categories, 'yapi_category');
} else {
container.innerHTML = `<p style="color: red;">加载YAPI分类失败: ${categories.error || '未知错误'}</p>`;
}
} catch (error) {
container.innerHTML = `<p style="color: red;">请求YAPI分类时出错: ${error}</p>`;
}
}
async function fetchSwaggerTags() {
const swaggerFilePath = document.getElementById('swagger_file_path').value;
const container = document.getElementById('swagger-tags-container');
container.innerHTML = '正在加载标签...';
if (!swaggerFilePath) {
container.innerHTML = '<p style="color: red;">请输入Swagger文件路径。</p>';
return;
}
try {
const response = await fetch('/list-swagger-tags', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ swagger_file_path: swaggerFilePath })
});
const tags = await response.json();
if (response.ok) {
renderCheckboxes(container, tags, 'swagger_tag');
} else {
container.innerHTML = `<p style="color: red;">加载Swagger标签失败: ${tags.error || '未知错误'}</p>`;
}
} catch (error) {
container.innerHTML = `<p style="color: red;">请求Swagger标签时出错: ${error}</p>`;
}
}
function renderCheckboxes(container, items, groupName) {
if (!items || items.length === 0) {
container.innerHTML = '<p>未找到任何项。</p>';
return;
}
let html = items.map((item, index) => {
const id = `${groupName}_${index}`;
return `<div>
<input type="checkbox" id="${id}" name="${groupName}[]" value="${item.name}">
<label for="${id}">${item.name} ${item.description ? '(' + item.description + ')' : ''}</label>
</div>`;
}).join('');
container.innerHTML = html;
}
// The old functions fetchYapiCategories, fetchSwaggerTags, and renderCheckboxes are no longer needed
// and should be removed if they exist elsewhere in this file.