33"""
44数据驱动测试API
55"""
6- from typing import Dict , List , Optional , Any
6+ from typing import Dict , List , Optional , Any , Coroutine
77
88from fastapi import APIRouter , Body , Path , Query , UploadFile , File , Form
99from fastapi .responses import JSONResponse
1212import os
1313import tempfile
1414
15- from backend .common .response .response_schema import response_base
15+ from backend .common .response .response_schema import response_base , ResponseModel , ResponseSchemaModel
1616from backend .plugin .api_testing .utils .data_driven import (
1717 DataDriverManager , DataDrivenConfig , DataSourceConfig ,
1818 DataSourceType , DatabaseType , TestCaseParameter , TestIteration
2222
2323
2424@router .post ("/config" , summary = "创建或更新数据驱动测试配置" )
25- async def create_data_driven_config (config : DataDrivenConfig ) -> JSONResponse :
25+ async def create_data_driven_config (config : DataDrivenConfig ) -> ResponseModel | ResponseSchemaModel :
2626 """
2727 创建或更新数据驱动测试配置
2828 """
@@ -34,24 +34,24 @@ async def create_data_driven_config(config: DataDrivenConfig) -> JSONResponse:
3434 if not os .path .isabs (file_path ):
3535 from backend .core .path_conf import PLUGIN_DIR
3636 file_path = os .path .join (PLUGIN_DIR , 'api_testing' , file_path )
37-
37+
3838 if not os .path .exists (file_path ):
39- return response_base .fail (msg = f"文件不存在: { file_path } " )
40-
39+ return response_base .fail (data = f"文件不存在: { file_path } " )
40+
4141 # 准备测试迭代数据
4242 iterations = await DataDriverManager .prepare_iterations (config )
4343 config .iterations = iterations
44-
45- return response_base .success (data = config .model_dump (), msg = "数据驱动测试配置创建成功" )
44+
45+ return response_base .success (data = config .model_dump ())
4646 except Exception as e :
47- return response_base .fail (msg = f"数据驱动测试配置创建失败: { str (e )} " )
47+ return response_base .fail (data = f"数据驱动测试配置创建失败: { str (e )} " )
4848
4949
5050@router .post ("/upload/csv" , summary = "上传CSV数据文件" )
5151async def upload_csv_file (
52- file : UploadFile = File (...),
53- directory : str = Form ("data" )
54- ) -> JSONResponse :
52+ file : UploadFile = File (...),
53+ directory : str = Form ("data" )
54+ ) -> ResponseModel | ResponseSchemaModel :
5555 """
5656 上传CSV数据文件
5757
@@ -62,35 +62,34 @@ async def upload_csv_file(
6262 from backend .core .path_conf import PLUGIN_DIR
6363 save_dir = os .path .join (PLUGIN_DIR , 'api_testing' , directory )
6464 os .makedirs (save_dir , exist_ok = True )
65-
65+
6666 # 保存文件
6767 file_path = os .path .join (save_dir , file .filename )
6868 with open (file_path , "wb" ) as f :
6969 content = await file .read ()
7070 f .write (content )
71-
71+
7272 # 读取CSV预览数据
7373 df = pd .read_csv (file_path , nrows = 5 )
7474 preview = df .to_dict (orient = 'records' )
75-
75+
7676 return response_base .success (
7777 data = {
7878 "file_path" : os .path .join (directory , file .filename ),
7979 "columns" : list (df .columns ),
8080 "preview" : preview ,
8181 "rows" : len (pd .read_csv (file_path ))
82- },
83- msg = "CSV文件上传成功"
82+ }
8483 )
8584 except Exception as e :
86- return response_base .fail (msg = f"CSV文件上传失败: { str (e )} " )
85+ return response_base .fail (data = f"CSV文件上传失败: { str (e )} " )
8786
8887
8988@router .post ("/upload/excel" , summary = "上传Excel数据文件" )
9089async def upload_excel_file (
91- file : UploadFile = File (...),
92- directory : str = Form ("data" )
93- ) -> JSONResponse :
90+ file : UploadFile = File (...),
91+ directory : str = Form ("data" )
92+ ) -> ResponseModel | ResponseSchemaModel :
9493 """
9594 上传Excel数据文件
9695
@@ -101,41 +100,40 @@ async def upload_excel_file(
101100 from backend .core .path_conf import PLUGIN_DIR
102101 save_dir = os .path .join (PLUGIN_DIR , 'api_testing' , directory )
103102 os .makedirs (save_dir , exist_ok = True )
104-
103+
105104 # 保存文件
106105 file_path = os .path .join (save_dir , file .filename )
107106 with open (file_path , "wb" ) as f :
108107 content = await file .read ()
109108 f .write (content )
110-
109+
111110 # 读取Excel预览数据
112111 xls = pd .ExcelFile (file_path )
113112 sheet_info = {}
114-
113+
115114 for sheet_name in xls .sheet_names :
116115 df = pd .read_excel (file_path , sheet_name = sheet_name , nrows = 5 )
117116 sheet_info [sheet_name ] = {
118117 "columns" : list (df .columns ),
119118 "preview" : df .to_dict (orient = 'records' ),
120119 "rows" : len (pd .read_excel (file_path , sheet_name = sheet_name ))
121120 }
122-
121+
123122 return response_base .success (
124123 data = {
125124 "file_path" : os .path .join (directory , file .filename ),
126125 "sheets" : sheet_info
127- },
128- msg = "Excel文件上传成功"
126+ }
129127 )
130128 except Exception as e :
131- return response_base .fail (msg = f"Excel文件上传失败: { str (e )} " )
129+ return response_base .fail (data = f"Excel文件上传失败: { str (e )} " )
132130
133131
134132@router .post ("/upload/json" , summary = "上传JSON数据文件" )
135133async def upload_json_file (
136- file : UploadFile = File (...),
137- directory : str = Form ("data" )
138- ) -> JSONResponse :
134+ file : UploadFile = File (...),
135+ directory : str = Form ("data" )
136+ ) -> ResponseModel | ResponseSchemaModel :
139137 """
140138 上传JSON数据文件
141139
@@ -146,43 +144,42 @@ async def upload_json_file(
146144 from backend .core .path_conf import PLUGIN_DIR
147145 save_dir = os .path .join (PLUGIN_DIR , 'api_testing' , directory )
148146 os .makedirs (save_dir , exist_ok = True )
149-
147+
150148 # 保存文件
151149 file_path = os .path .join (save_dir , file .filename )
152150 with open (file_path , "wb" ) as f :
153151 content = await file .read ()
154152 f .write (content )
155-
153+
156154 # 读取JSON预览数据
157155 with open (file_path , "r" , encoding = "utf-8" ) as f :
158156 json_data = json .load (f )
159-
157+
160158 # 如果是数组,取前5个元素作为预览
161159 preview = json_data
162160 items_count = 1
163-
161+
164162 if isinstance (json_data , list ):
165163 items_count = len (json_data )
166164 preview = json_data [:5 ] if len (json_data ) > 5 else json_data
167-
165+
168166 # 如果不是数组,则包装成数组方便处理
169167 elif isinstance (json_data , dict ):
170168 preview = [json_data ]
171-
169+
172170 return response_base .success (
173171 data = {
174172 "file_path" : os .path .join (directory , file .filename ),
175173 "preview" : preview ,
176174 "items_count" : items_count
177- },
178- msg = "JSON文件上传成功"
175+ }
179176 )
180177 except Exception as e :
181- return response_base .fail (msg = f"JSON文件上传失败: { str (e )} " )
178+ return response_base .fail (data = f"JSON文件上传失败: { str (e )} " )
182179
183180
184181@router .post ("/validate-data-source" , summary = "验证数据源配置" )
185- async def validate_data_source (config : DataSourceConfig ) -> JSONResponse :
182+ async def validate_data_source (config : DataSourceConfig ) -> ResponseModel | ResponseSchemaModel :
186183 """
187184 验证数据源配置
188185
@@ -192,46 +189,43 @@ async def validate_data_source(config: DataSourceConfig) -> JSONResponse:
192189 # 加载前5条数据
193190 data = await DataDriverManager .load_data_source (config )
194191 preview = data [:5 ] if len (data ) > 5 else data
195-
192+
196193 return response_base .success (
197194 data = {
198195 "valid" : True ,
199196 "rows_count" : len (data ),
200197 "preview" : preview ,
201198 "columns" : list (preview [0 ].keys ()) if preview else []
202- },
203- msg = "数据源配置验证成功"
199+ }
204200 )
205201 except Exception as e :
206202 return response_base .fail (
207- data = {"valid" : False },
208- msg = f"数据源配置验证失败: { str (e )} "
203+ data = f"数据源配置验证失败: { str (e )} "
209204 )
210205
211206
212207@router .post ("/prepare-iterations" , summary = "准备测试迭代数据" )
213- async def prepare_iterations (config : DataDrivenConfig ) -> JSONResponse :
208+ async def prepare_iterations (config : DataDrivenConfig ) -> ResponseModel | ResponseSchemaModel :
214209 """
215210 准备测试迭代数据
216211
217212 根据数据驱动配置生成测试迭代数据
218213 """
219214 try :
220215 iterations = await DataDriverManager .prepare_iterations (config )
221-
216+
222217 return response_base .success (
223218 data = {
224219 "iterations_count" : len (iterations ),
225220 "iterations" : [iter .model_dump () for iter in iterations ]
226- },
227- msg = "测试迭代数据准备成功"
221+ }
228222 )
229223 except Exception as e :
230- return response_base .fail (msg = f"测试迭代数据准备失败: { str (e )} " )
224+ return response_base .fail (data = f"测试迭代数据准备失败: { str (e )} " )
231225
232226
233227@router .get ("/data-directories" , summary = "获取数据目录列表" )
234- async def get_data_directories () -> JSONResponse :
228+ async def get_data_directories () -> ResponseModel | ResponseSchemaModel :
235229 """
236230 获取数据目录列表
237231
@@ -241,25 +235,25 @@ async def get_data_directories() -> JSONResponse:
241235 # 插件根目录
242236 from backend .core .path_conf import PLUGIN_DIR
243237 plugin_dir = os .path .join (PLUGIN_DIR , 'api_testing' )
244-
238+
245239 # 默认数据目录
246240 data_dir = os .path .join (plugin_dir , 'data' )
247241 os .makedirs (data_dir , exist_ok = True )
248-
242+
249243 # 获取所有目录
250244 directories = []
251245 for root , dirs , files in os .walk (plugin_dir ):
252246 if os .path .abspath (root ) != os .path .abspath (plugin_dir ):
253247 rel_path = os .path .relpath (root , plugin_dir )
254248 directories .append (rel_path )
255-
256- return response_base .success (data = directories , msg = "获取数据目录列表成功" )
249+
250+ return response_base .success (data = directories )
257251 except Exception as e :
258- return response_base .fail (msg = f"获取数据目录列表失败: { str (e )} " )
252+ return response_base .fail (data = f"获取数据目录列表失败: { str (e )} " )
259253
260254
261255@router .get ("/data-files/{directory}" , summary = "获取数据目录下的文件" )
262- async def get_data_files (directory : str = Path (..., description = "目录路径" )) -> JSONResponse :
256+ async def get_data_files (directory : str = Path (..., description = "目录路径" )) -> ResponseModel | ResponseSchemaModel :
263257 """
264258 获取数据目录下的文件
265259
@@ -269,22 +263,24 @@ async def get_data_files(directory: str = Path(..., description="目录路径"))
269263 # 插件目录下的指定目录
270264 from backend .core .path_conf import PLUGIN_DIR
271265 dir_path = os .path .join (PLUGIN_DIR , 'api_testing' , directory )
272-
266+
273267 if not os .path .exists (dir_path ) or not os .path .isdir (dir_path ):
274- return response_base .fail (msg = f"目录不存在: { directory } " )
275-
268+ return response_base .fail (data = f"目录不存在: { directory } " )
269+
276270 # 获取目录下的所有文件
277271 files = []
278272 for filename in os .listdir (dir_path ):
279273 file_path = os .path .join (dir_path , filename )
280274 if os .path .isfile (file_path ):
281- files .append ({
282- "name" : filename ,
283- "path" : os .path .join (directory , filename ),
284- "size" : os .path .getsize (file_path ),
285- "type" : os .path .splitext (filename )[1 ].lstrip ('.' )
286- })
287-
288- return response_base .success (data = files , msg = "获取数据文件列表成功" )
275+ files .append (
276+ {
277+ "name" : filename ,
278+ "path" : os .path .join (directory , filename ),
279+ "size" : os .path .getsize (file_path ),
280+ "type" : os .path .splitext (filename )[1 ].lstrip ('.' )
281+ }
282+ )
283+
284+ return response_base .success (data = files )
289285 except Exception as e :
290- return response_base .fail (msg = f"获取数据文件列表失败: { str (e )} " )
286+ return response_base .fail (data = f"获取数据文件列表失败: { str (e )} " )
0 commit comments