#!/usr/bin/env python3 """ AIBridge API 集成测试 配置来源:aibridge/config.py(通过 JNPFConfig 读取) 用法: cd $ccWorkDir python3 aibridge/utils/api_test.py # 运行全部测试 python3 api_test.py auth # 仅认证 python3 api_test.py menu # 仅菜单 python3 api_test.py visualDev # 仅可视化开发 python3 api_test.py workflow # 仅工作流 python3 api_test.py dataInterface # 仅数据接口 python3 api_test.py dataModel # 仅数据模型 python3 api_test.py oauth # 仅接口认证(OAuth) python3 api_test.py oauthBind # 仅接口认证绑定 """ import sys import os import json import time import argparse from datetime import datetime # 配置路径 AIBRIDGE_ROOT = os.environ['ccWorkDir'] sys.path.insert(0, AIBRIDGE_ROOT) from aibridge import JNPFClient, JNPFConfig def load_config(): """从 aibridge/config.py 读取配置""" config = JNPFConfig() if not config.app_code: print("\n[ERROR] aibridge/config.py 中 app_code 为空!") print(" 原因:硬编码默认 app_code 会导致登录到系统控制后台(错误应用)。") print(" 解决:在 aibridge/config.py 中正确配置 app_code\n") sys.exit(1) return config def run_tests(client, targets): """执行测试用例""" results = [] all_tests = { 'auth': test_auth, 'menu': test_menu_list, 'menuCreate': test_menu_create, 'visualDev': test_visual_dev, 'workflow': test_workflow, 'dataInterface': test_data_interface, 'dataModel': test_data_model, 'oauth': test_oauth, 'oauthBind': test_oauth_bind, } to_run = list(targets) if targets else list(all_tests.keys()) for name in to_run: if name in all_tests: try: print(f"\n[{name}] 测试中...") ok, msg = all_tests[name](client) results.append({'name': name, 'ok': ok, 'msg': msg}) print(f" 结果: {'✓ 通过' if ok else '✗ 失败'} {msg}") except Exception as e: print(f" 异常: {e}") results.append({'name': name, 'ok': False, 'msg': str(e)}) else: print(f" 未知测试: {name}") return results def print_summary(results, config): """打印汇总""" print("\n" + "=" * 50) print("测试汇总") print("=" * 50) print(f"配置来源: aibridge/config.py") print(f"base_url: {config.base_url}") print(f"app_code: {config.app_code}") print(f"account: {config.account}") print("=" * 50) passed = sum(1 for r in results if r['ok']) for r in results: print(f" {'✓' if r['ok'] else '✗'} {r['name']}: {'通过' if r['ok'] else '失败'} {r['msg']}") print(f"\n通过: {passed} / {len(results)}") print("=" * 50) # 保存结果 ts = datetime.now().strftime('%Y%m%d_%H%M%S') results_dir = os.path.join(os.path.dirname(__file__), 'results') os.makedirs(results_dir, exist_ok=True) report_path = os.path.join(results_dir, f'api-test-summary_{ts}.json') with open(report_path, 'w', encoding='utf-8') as f: json.dump({ 'config': { 'base_url': config.base_url, 'app_code': config.app_code, 'account': config.account, }, 'results': results, 'timestamp': ts, }, f, ensure_ascii=False, indent=2) print(f"结果已保存: {results_dir}/api-test-summary_{ts}.json") return passed == len(results) # ── 测试用例 ───────────────────────────────────────── def test_auth(client): """TC-Auth-001: 认证""" result = client.get_user_info() return result.success, f"用户: {result.data.get('userName', 'N/A')}" def test_menu_list(client): """TC-Menu-001: 获取菜单列表""" resp = client.menu.get_list({"currentPage": 1, "pageSize": 50}) count = len(resp.data.get("list", [])) if resp.data else 0 return resp.success, f"菜单数: {count}" def test_menu_create(client): """TC-Menu-002: 创建目录菜单""" test_name = f"E2E测试目录_{int(time.time())}" resp = client.menu.create_directory_menu( full_name=test_name, en_code=f"e2e_test_dir_{int(time.time())}", icon="icon-ym icon-ym-folder", sort_code=999, parent_id="-1", ) return resp.success, f"id={resp.id}" if resp.id else resp.msg def test_visual_dev(client): """TC-VisualDev-001: 获取已发布表单""" resp = client.visual_dev.get_list({"currentPage": 1, "pageSize": 10}) forms = resp.data.get("list", []) if resp.data else [] published = [f for f in forms if f.get("state") == 1] return resp.success, f"总数={len(forms)}, 已发布={len(published)}" def test_workflow(client): """TC-Workflow-001: 获取流程模板""" resp = client.workflow.get_template_list({"currentPage": 1, "pageSize": 10}) count = len(resp.data.get("list", [])) if resp.data else 0 return resp.success, f"流程数: {count}" def test_data_interface(client): """TC-DI-001: 获取数据接口""" resp = client.data_interface.get_list({"currentPage": 1, "pageSize": 3}) count = len(resp.data.get("list", [])) if resp.data else 0 return resp.success, f"接口数: {count}" def test_data_model(client): """TC-DataModel-001: 数据模型 - 获取业务库连接列表""" resp = client.data_source.get_list() count = len(resp.data.get("list", [])) if resp.data else 0 return resp.success, f"数据源数: {count}" def test_oauth(client): """TC-OAuth-001: 接口认证 - 创建认证""" oauth = client.interface_oauth # 获取新秘钥 secret_resp = oauth.get_app_secret() if not secret_resp.success: return False, f"获取秘钥失败: {secret_resp.msg}" app_secret = secret_resp.data # 创建认证 test_app_id = f"e2e_test_app_{int(time.time())}" resp = oauth.create({ "appId": test_app_id, "appName": "E2E测试应用", "appSecret": app_secret, "verifySignature": 0, "enabledMark": 1, }) return resp.success, f"appId={test_app_id}, msg={resp.msg}" def test_oauth_bind(client): """TC-OAuth-002: 接口认证 - 绑定授权接口""" oauth = client.interface_oauth # 先获取列表找一个认证 list_resp = oauth.get_list({"currentPage": 1, "pageSize": 10}) if not list_resp.success or not list_resp.data: return False, "获取认证列表失败" items = list_resp.data.get("list", []) if not items: return False, "认证列表为空" oauth_id = items[0].get("id") # 获取数据接口列表 di_resp = client.data_interface.get_list({"currentPage": 1, "pageSize": 3}) if not di_resp.success or not di_resp.data: return False, "获取接口列表失败" di_items = di_resp.data.get("list", []) if not di_items: return False, "接口列表为空" di_ids = [di_items[0].get("id")] # 绑定接口 bind_resp = oauth.bind_interfaces(oauth_id, di_ids) return bind_resp.success, f"oauth_id={oauth_id}, di_id={di_ids[0]}, msg={bind_resp.msg}" # ── 主入口 ───────────────────────────────────────── def main(): parser = argparse.ArgumentParser(description='AIBridge API 集成测试') parser.add_argument('targets', nargs='*', help='测试目标: auth menu menuCreate visualDev workflow dataInterface dataModel') args = parser.parse_args() print("=" * 50) print("AIBridge API 集成测试") print("=" * 50) config = load_config() print(f"base_url: {config.base_url}") print(f"app_code: {config.app_code}") print(f"account: {config.account}") print("=" * 50) client = JNPFClient.from_config(config) print("\n登录中...") login_resp = client.login() if not login_resp.success: print(f"登录失败: {login_resp.msg}") sys.exit(1) print("登录成功") targets = args.targets if args.targets else [] results = run_tests(client, targets) ok = print_summary(results, config) sys.exit(0 if ok else 1) if __name__ == '__main__': main()