plugin_tester.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. import os
  2. import sys
  3. if hasattr(sys.stdout, 'reconfigure'):
  4. sys.stdout.reconfigure(encoding='utf-8', errors='replace')
  5. sys.stderr.reconfigure(encoding='utf-8', errors='replace')
  6. import json
  7. import time
  8. import argparse
  9. from typing import Optional, Dict, Any, List, Callable
  10. from dataclasses import dataclass, field
  11. from datetime import datetime
  12. project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  13. if project_root not in sys.path:
  14. sys.path.insert(0, project_root)
  15. from plugin import IPlugin
  16. from plugin_factory import PluginFactory
  17. from toolkit.proxy_manager import ProxyManager
  18. from core_types import (
  19. PluginConfig,
  20. Account,
  21. Proxy,
  22. AppointmentType,
  23. AvailabilityStatus,
  24. QueryResult,
  25. BookResult,
  26. PluginStatus
  27. )
  28. # 默认插件注册映射表
  29. DEFAULT_PLUGIN_MAP = {
  30. "tls_plugin": ("plugins/tls_plugin.py", "TlsPlugin"),
  31. "vfs_plugin": ("plugins/vfs_plugin.py", "VfsPlugin"),
  32. "usa_plugin": ("plugins/usa_plugin.py", "UsaPlugin"),
  33. "pol_plugin": ("plugins/pol_plugin.py", "PolPlugin"),
  34. "ita_plugin": ("plugins/ita_plugin.py", "ItaPlugin"),
  35. "bel_plugin": ("plugins/bel_plugin.py", "BelPlugin"),
  36. "de_plugin": ("plugins/de_plugin.py", "DePlugin"),
  37. "bls_plugin": ("plugins/bls_plugin.py", "BlsPlugin"),
  38. "grc_plugin": ("plugins/grc_plugin.py", "GrcPlugin"),
  39. }
  40. @dataclass
  41. class StepResult:
  42. name: str
  43. success: bool
  44. duration_sec: float
  45. message: str = ""
  46. data: Any = None
  47. error: Optional[Exception] = None
  48. class PluginTester:
  49. """
  50. 通用签证插件测试类
  51. """
  52. def __init__(
  53. self,
  54. plugin_name: str,
  55. group_id: str = "test.group",
  56. config: Optional[PluginConfig] = None,
  57. user_inputs: Optional[Dict[str, Any]] = None,
  58. appointment_types: Optional[List[AppointmentType]] = None,
  59. custom_module_path: Optional[str] = None,
  60. custom_class_name: Optional[str] = None,
  61. logger: Optional[Callable[[str], None]] = None
  62. ):
  63. self.plugin_name = plugin_name
  64. self.group_id = group_id
  65. self.config = config or self.create_default_config()
  66. self.user_inputs = user_inputs or {}
  67. self.appointment_types = appointment_types or []
  68. self.custom_module_path = custom_module_path
  69. self.custom_class_name = custom_class_name
  70. self.custom_logger = logger
  71. self.factory = PluginFactory()
  72. self._register_plugins()
  73. self.plugin: Optional[IPlugin] = None
  74. self.results: List[StepResult] = []
  75. def _log(self, message: str, level: str = "INFO"):
  76. tag = f"[PluginTester][{self.plugin_name}][{level}]"
  77. formatted_msg = f"{tag} {message}"
  78. if self.custom_logger:
  79. self.custom_logger(formatted_msg)
  80. else:
  81. print(formatted_msg)
  82. def _register_plugins(self):
  83. for name, (mod_path, cls_name) in DEFAULT_PLUGIN_MAP.items():
  84. full_path = os.path.join(project_root, mod_path)
  85. if os.path.exists(full_path):
  86. self.factory.register_plugin(name, full_path, cls_name)
  87. if self.custom_module_path and self.custom_class_name:
  88. self.factory.register_plugin(self.plugin_name, self.custom_module_path, self.custom_class_name)
  89. @staticmethod
  90. def parse_proxy_url(proxy_url: str) -> Proxy:
  91. """从字符串格式代理地址解析 Proxy 对象"""
  92. from urllib.parse import urlparse
  93. parsed = urlparse(proxy_url if "://" in proxy_url else f"http://{proxy_url}")
  94. return Proxy(
  95. id=1,
  96. proto=parsed.scheme or "http",
  97. ip=parsed.hostname or "127.0.0.1",
  98. port=parsed.port or 8080,
  99. username=parsed.username or "",
  100. password=parsed.password or ""
  101. )
  102. @staticmethod
  103. def create_default_config(
  104. username: str = "test_user@example.com",
  105. password: str = "TestPassword123!",
  106. proxy_url: Optional[str] = None,
  107. free_config: Optional[Dict[str, Any]] = None,
  108. debug: bool = True
  109. ) -> PluginConfig:
  110. """快速构建 PluginConfig 配置对象"""
  111. account = Account(
  112. id=1,
  113. username=username,
  114. password=password
  115. )
  116. proxy = Proxy()
  117. if proxy_url:
  118. proxy = PluginTester.parse_proxy_url(proxy_url)
  119. return PluginConfig(
  120. account=account,
  121. proxy=proxy,
  122. free_config=free_config or {},
  123. session_max_life=3600,
  124. debug=debug
  125. )
  126. @classmethod
  127. def from_json_config(
  128. cls,
  129. plugin_name: str,
  130. config_path: str,
  131. group_id: Optional[str] = None,
  132. user_override: Optional[str] = None,
  133. password_override: Optional[str] = None,
  134. proxy_override: Optional[str] = None
  135. ) -> 'PluginTester':
  136. """
  137. 从 JSON 配置文件加载并初始化测试器
  138. 支持单个插件配置或复合 test_conf.json (带 "default" 与 "plugins" 结构)
  139. """
  140. with open(config_path, "r", encoding="utf-8") as f:
  141. root_data = json.load(f)
  142. default_data = root_data.get("default", {})
  143. plugin_data = {}
  144. if "plugins" in root_data and isinstance(root_data["plugins"], dict):
  145. plugin_data = root_data["plugins"].get(plugin_name, {})
  146. elif plugin_name in root_data and isinstance(root_data[plugin_name], dict):
  147. plugin_data = root_data[plugin_name]
  148. else:
  149. plugin_data = root_data
  150. # 1. 账号解析 (优先使用 plugin 独立配置,回退到 default,再应用 CLI override)
  151. account_data = plugin_data.get("account") or default_data.get("account") or {}
  152. username = user_override or account_data.get("username", "")
  153. password = password_override or account_data.get("password", "")
  154. account = Account(
  155. id=account_data.get("id", 1),
  156. username=username,
  157. password=password
  158. )
  159. # 2. 代理解析 (CLI override > plugin/default 的 proxy_pool/proxy-pool > plugin/default 的 proxy 对象)
  160. if proxy_override:
  161. if proxy_override.startswith("local:") or proxy_override.startswith("cloud:"):
  162. raw_proxy = ProxyManager.Instance().get_next_proxy([proxy_override])
  163. proxy = Proxy(**raw_proxy)
  164. else:
  165. proxy = cls.parse_proxy_url(proxy_override)
  166. else:
  167. pools = plugin_data.get("proxy_pool") or plugin_data.get("proxy-pool") or default_data.get("proxy_pool") or default_data.get("proxy-pool")
  168. if pools:
  169. if isinstance(pools, str):
  170. pools = [pools]
  171. raw_proxy = ProxyManager.Instance().get_next_proxy(pools)
  172. proxy = Proxy(**raw_proxy)
  173. else:
  174. proxy_data = plugin_data.get("proxy") or default_data.get("proxy")
  175. proxy = Proxy()
  176. if proxy_data:
  177. proxy = Proxy(
  178. id=proxy_data.get("id", 1),
  179. proto=proxy_data.get("proto", "http"),
  180. ip=proxy_data.get("ip", ""),
  181. port=int(proxy_data.get("port", 8080)),
  182. username=proxy_data.get("username", ""),
  183. password=proxy_data.get("password", "")
  184. )
  185. free_config = plugin_data.get("free_config", {})
  186. session_max_life = plugin_data.get("session_max_life", default_data.get("session_max_life", 3600))
  187. debug = plugin_data.get("debug", default_data.get("debug", True))
  188. config = PluginConfig(
  189. account=account,
  190. proxy=proxy,
  191. free_config=free_config,
  192. session_max_life=session_max_life,
  193. debug=debug
  194. )
  195. resolved_group_id = group_id or plugin_data.get("group_id") or "test.group"
  196. user_inputs = plugin_data.get("user_inputs", {})
  197. # 3. 预约类型列表解析
  198. raw_apts = plugin_data.get("appointment_types", [])
  199. appointment_types = []
  200. for apt in raw_apts:
  201. if isinstance(apt, dict):
  202. appointment_types.append(AppointmentType(
  203. routing_key=apt.get("routing_key", ""),
  204. city=apt.get("city", ""),
  205. country=apt.get("country", ""),
  206. visa_type=apt.get("visa_type", ""),
  207. weight=apt.get("weight", 10)
  208. ))
  209. return cls(
  210. plugin_name=plugin_name,
  211. group_id=resolved_group_id,
  212. config=config,
  213. user_inputs=user_inputs,
  214. appointment_types=appointment_types
  215. )
  216. @classmethod
  217. def load_all_from_json(cls, config_path: str) -> List['PluginTester']:
  218. """从复合配置文件加载全部已定义的插件测试实例"""
  219. with open(config_path, "r", encoding="utf-8") as f:
  220. root_data = json.load(f)
  221. testers = []
  222. plugins_dict = root_data.get("plugins")
  223. if not plugins_dict or not isinstance(plugins_dict, dict):
  224. # 尝试直接检查顶层键
  225. plugins_dict = {k: v for k, v in root_data.items() if k != "default" and isinstance(v, dict)}
  226. for plg_name in plugins_dict.keys():
  227. tester = cls.from_json_config(plugin_name=plg_name, config_path=config_path)
  228. testers.append(tester)
  229. return testers
  230. # =========================================================================
  231. # 单步测试阶段 (Step Runners)
  232. # =========================================================================
  233. def test_init(self) -> StepResult:
  234. """测试 1: 实例化插件并设置配置与日志"""
  235. t0 = time.time()
  236. self._log("▶ [Step 1/7] Initializing plugin instance and configuration...")
  237. try:
  238. self.plugin = self.factory.create(self.group_id, self.plugin_name)
  239. if not self.plugin:
  240. raise RuntimeError(f"Factory failed to create instance for plugin '{self.plugin_name}'")
  241. self.plugin.set_config(self.config)
  242. self.plugin.set_log(self._log)
  243. info = self.plugin.get_plugin_info()
  244. self._log(f"✅ Plugin successfully initialized: {info}")
  245. res = StepResult(name="test_init", success=True, duration_sec=time.time() - t0, data=info)
  246. except Exception as e:
  247. self._log(f"❌ test_init failed: {e}", level="ERROR")
  248. res = StepResult(name="test_init", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  249. self.results.append(res)
  250. return res
  251. def test_create_session(self) -> StepResult:
  252. """测试 2: 建立会话并执行登录/绕过反爬"""
  253. t0 = time.time()
  254. self._log("▶ [Step 2/7] Testing create_session()...")
  255. if not self.plugin:
  256. res = StepResult(name="test_create_session", success=False, duration_sec=0, message="Plugin not initialized")
  257. self.results.append(res)
  258. return res
  259. try:
  260. self.plugin.create_session()
  261. self._log("✅ create_session() executed successfully.")
  262. res = StepResult(name="test_create_session", success=True, duration_sec=time.time() - t0)
  263. except Exception as e:
  264. self._log(f"❌ create_session() failed: {e}", level="ERROR")
  265. res = StepResult(name="test_create_session", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  266. self.results.append(res)
  267. return res
  268. def test_health_check(self) -> StepResult:
  269. """测试 3: 检查会话健康状态"""
  270. t0 = time.time()
  271. self._log("▶ [Step 3/7] Testing health_check()...")
  272. if not self.plugin:
  273. res = StepResult(name="test_health_check", success=False, duration_sec=0, message="Plugin not initialized")
  274. self.results.append(res)
  275. return res
  276. try:
  277. is_healthy = self.plugin.health_check()
  278. self._log(f"✅ health_check() returned: {is_healthy}")
  279. res = StepResult(name="test_health_check", success=is_healthy, duration_sec=time.time() - t0, data=is_healthy)
  280. except Exception as e:
  281. self._log(f"❌ health_check() failed: {e}", level="ERROR")
  282. res = StepResult(name="test_health_check", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  283. self.results.append(res)
  284. return res
  285. def test_query(self, routing_key: Optional[str] = None) -> StepResult:
  286. """测试 4: 查询预约号源"""
  287. t0 = time.time()
  288. self._log("▶ [Step 4/7] Testing query()...")
  289. if not self.plugin:
  290. res = StepResult(name="test_query", success=False, duration_sec=0, message="Plugin not initialized")
  291. self.results.append(res)
  292. return res
  293. try:
  294. # 根据 appointment_types 或 free_config 智能构建 AppointmentType
  295. if routing_key:
  296. apt_type = AppointmentType(
  297. routing_key=routing_key,
  298. country=self.config.free_config.get("country_code", "CHN"),
  299. city=self.config.free_config.get("center_code", "SHA"),
  300. visa_type="Tourist"
  301. )
  302. elif self.appointment_types:
  303. apt_type = self.appointment_types[0]
  304. else:
  305. apt_configs = self.config.free_config.get("apt_configs", {})
  306. first_key = list(apt_configs.keys())[0] if apt_configs else f"{self.group_id}.default"
  307. apt_type = AppointmentType(
  308. routing_key=first_key,
  309. country=self.config.free_config.get("country_code", "CHN"),
  310. city=self.config.free_config.get("center_code", "SHA"),
  311. visa_type="Tourist"
  312. )
  313. query_result: QueryResult = self.plugin.query(apt_type)
  314. self._log(f"✅ query() returned success={query_result.success}, status={query_result.availability_status}")
  315. if query_result.earliest_date:
  316. self._log(f"📅 Earliest Available Date: {query_result.earliest_date.strftime('%Y-%m-%d')}")
  317. res = StepResult(name="test_query", success=True, duration_sec=time.time() - t0, data=query_result)
  318. except Exception as e:
  319. self._log(f"❌ query() failed: {e}", level="ERROR")
  320. res = StepResult(name="test_query", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  321. self.results.append(res)
  322. return res
  323. def test_book(self, slot_info: Optional[QueryResult] = None, user_inputs: Optional[Dict] = None) -> StepResult:
  324. """测试 5: 执行预约锁定"""
  325. t0 = time.time()
  326. self._log("▶ [Step 5/7] Testing book()...")
  327. if not self.plugin:
  328. res = StepResult(name="test_book", success=False, duration_sec=0, message="Plugin not initialized")
  329. self.results.append(res)
  330. return res
  331. if not slot_info:
  332. target_apt = self.appointment_types[0] if self.appointment_types else AppointmentType(routing_key=f"{self.group_id}.default")
  333. slot_info = QueryResult(
  334. success=True,
  335. availability_status=AvailabilityStatus.Available,
  336. earliest_date=datetime.now(),
  337. apt_type=target_apt
  338. )
  339. inputs = user_inputs or self.user_inputs or {
  340. "first_name": "San",
  341. "last_name": "Zhang",
  342. "passport_no": "E12345678",
  343. "email": self.config.account.username if self.config and self.config.account else "test@example.com"
  344. }
  345. try:
  346. book_res: BookResult = self.plugin.book(slot_info=slot_info, user_inputs=inputs)
  347. self._log(f"✅ book() returned: success={book_res.success}, urn={book_res.urn}, date={book_res.book_date} {book_res.book_time}")
  348. res = StepResult(name="test_book", success=book_res.success, duration_sec=time.time() - t0, data=book_res)
  349. except Exception as e:
  350. self._log(f"❌ book() failed: {e}", level="ERROR")
  351. res = StepResult(name="test_book", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  352. self.results.append(res)
  353. return res
  354. def test_status(self) -> StepResult:
  355. """测试 6: 获取插件当前状态与指标"""
  356. t0 = time.time()
  357. self._log("▶ [Step 6/7] Testing get_plugin_status()...")
  358. if not self.plugin:
  359. res = StepResult(name="test_status", success=False, duration_sec=0, message="Plugin not initialized")
  360. self.results.append(res)
  361. return res
  362. try:
  363. status: PluginStatus = self.plugin.get_plugin_status()
  364. self._log(f"✅ get_plugin_status(): is_healthy={status.is_healthy}, account={status.account}, age={status.session_age_sec}s")
  365. res = StepResult(name="test_status", success=True, duration_sec=time.time() - t0, data=status)
  366. except Exception as e:
  367. self._log(f"❌ get_plugin_status() failed: {e}", level="ERROR")
  368. res = StepResult(name="test_status", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  369. self.results.append(res)
  370. return res
  371. def test_cleanup(self) -> StepResult:
  372. """测试 7: 销毁浏览器与释放临时文件资源"""
  373. t0 = time.time()
  374. self._log("▶ [Step 7/7] Testing cleanup()...")
  375. if not self.plugin:
  376. res = StepResult(name="test_cleanup", success=True, duration_sec=0, message="Plugin was not initialized")
  377. self.results.append(res)
  378. return res
  379. try:
  380. self.plugin.cleanup()
  381. self._log("✅ cleanup() executed successfully.")
  382. res = StepResult(name="test_cleanup", success=True, duration_sec=time.time() - t0)
  383. except Exception as e:
  384. self._log(f"❌ cleanup() failed: {e}", level="ERROR")
  385. res = StepResult(name="test_cleanup", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
  386. self.results.append(res)
  387. return res
  388. # =========================================================================
  389. # Pipeline 流水线全自动执行
  390. # =========================================================================
  391. def run_pipeline(
  392. self,
  393. test_book: bool = False,
  394. user_inputs: Optional[Dict] = None,
  395. auto_cleanup: bool = True,
  396. keep_on_error: bool = False
  397. ) -> bool:
  398. """
  399. 顺序执行完整流水线测试并打印汇总诊断报告
  400. """
  401. self.results.clear()
  402. self._log("=" * 60)
  403. self._log(f"🚀 Starting Full Test Pipeline for [{self.plugin_name}]")
  404. self._log("=" * 60)
  405. all_passed = True
  406. slot_info = None
  407. try:
  408. # 1. Init
  409. r = self.test_init()
  410. if not r.success:
  411. all_passed = False
  412. if keep_on_error and getattr(self, "plugin", None):
  413. self.plugin.keep_browser_on_error = True
  414. return False
  415. # 2. Create Session
  416. r = self.test_create_session()
  417. if not r.success:
  418. all_passed = False
  419. if keep_on_error and getattr(self, "plugin", None):
  420. self.plugin.keep_browser_on_error = True
  421. return False
  422. # 3. Health Check
  423. r = self.test_health_check()
  424. if not r.success:
  425. all_passed = False
  426. if keep_on_error and getattr(self, "plugin", None):
  427. self.plugin.keep_browser_on_error = True
  428. # 4. Status Check
  429. r = self.test_status()
  430. if not r.success:
  431. all_passed = False
  432. if keep_on_error and getattr(self, "plugin", None):
  433. self.plugin.keep_browser_on_error = True
  434. # 5. Query
  435. r = self.test_query()
  436. if not r.success:
  437. all_passed = False
  438. if keep_on_error and getattr(self, "plugin", None):
  439. self.plugin.keep_browser_on_error = True
  440. else:
  441. slot_info = r.data
  442. # 6. Book (Optional)
  443. if test_book:
  444. inputs = user_inputs or self.user_inputs
  445. r = self.test_book(slot_info=slot_info, user_inputs=inputs)
  446. if not r.success:
  447. all_passed = False
  448. if keep_on_error and getattr(self, "plugin", None):
  449. self.plugin.keep_browser_on_error = True
  450. # 7. Final Status
  451. self.test_status()
  452. except Exception as e:
  453. all_passed = False
  454. if keep_on_error and getattr(self, "plugin", None):
  455. self.plugin.keep_browser_on_error = True
  456. self._log(f"💥 Pipeline 发生未捕获异常: {e}", level="ERROR")
  457. finally:
  458. if not all_passed and keep_on_error:
  459. self._log("[PluginTester] ⚠️ 测试发生失败/异常且指定了 --keep-on-error,保留浏览器窗口以便排查分析(跳过 cleanup)。", level="WARN")
  460. elif auto_cleanup:
  461. self.test_cleanup()
  462. self._print_report()
  463. return all_passed
  464. def _print_report(self):
  465. """打印格式化测试结果报告"""
  466. print("\n" + "=" * 65)
  467. print(f"📊 [Test Report Summary] Plugin: {self.plugin_name} (Group: {self.group_id})")
  468. print("=" * 65)
  469. print(f"{'Step Name':<20} | {'Status':<10} | {'Duration (s)':<12} | {'Details'}")
  470. print("-" * 65)
  471. total_duration = 0.0
  472. all_ok = True
  473. for res in self.results:
  474. total_duration += res.duration_sec
  475. status_str = "✅ PASS" if res.success else "❌ FAIL"
  476. if not res.success:
  477. all_ok = False
  478. details = res.message or ""
  479. if res.data and not details:
  480. details = str(res.data)[:40]
  481. print(f"{res.name:<20} | {status_str:<10} | {res.duration_sec:<12.2f} | {details}")
  482. print("-" * 65)
  483. overall_status = "🎉 ALL TESTS PASSED" if all_ok else "💥 SOME TESTS FAILED"
  484. print(f"Overall Result: {overall_status} | Total Time: {total_duration:.2f}s")
  485. print("=" * 65 + "\n")
  486. # =============================================================================
  487. # CLI 命令行入口
  488. # =============================================================================
  489. def resolve_config_path(config_arg: Optional[str]) -> Optional[str]:
  490. """
  491. 智能解析配置文件路径:
  492. 1. 传入路径存在则直接使用
  493. 2. 检查相对于 project_root 的路径
  494. 3. 检查 project_root/config/ 下同名文件
  495. 4. 回退到 project_root/config/test_conf.json 或 test_conf.json
  496. """
  497. if config_arg:
  498. candidates = [
  499. config_arg,
  500. os.path.join(project_root, config_arg),
  501. os.path.join(project_root, "config", config_arg),
  502. os.path.join(project_root, "config", os.path.basename(config_arg)),
  503. ]
  504. for c in candidates:
  505. if c and os.path.exists(c) and os.path.isfile(c):
  506. return os.path.abspath(c)
  507. # 默认搜索位置
  508. defaults = [
  509. os.path.join(project_root, "config", "test_conf.json"),
  510. os.path.join(project_root, "test_conf.json"),
  511. os.path.join(os.getcwd(), "config", "test_conf.json"),
  512. os.path.join(os.getcwd(), "test_conf.json")
  513. ]
  514. for d in defaults:
  515. if os.path.exists(d) and os.path.isfile(d):
  516. return os.path.abspath(d)
  517. return None
  518. def main():
  519. parser = argparse.ArgumentParser(description="Universal Plugin Test Runner (PluginTester)")
  520. parser.add_argument("plugin_pos", nargs="?", default=None, help="Plugin identifier (positional, e.g. vfs_plugin, tls_plugin)")
  521. parser.add_argument("--plugin", "-p", help="Plugin identifier (e.g., vfs_plugin, tls_plugin, or 'all')")
  522. parser.add_argument("--group", "-g", help="Group identifier override")
  523. parser.add_argument("--config", "-c", default=None, help="Path to JSON configuration file (default: config/test_conf.json)")
  524. parser.add_argument("--user", "-u", help="Username / Email credential override")
  525. parser.add_argument("--password", "-pwd", help="Password credential override")
  526. parser.add_argument("--proxy", help="Proxy URL override (e.g. http://user:pass@ip:port)")
  527. parser.add_argument("--book", action="store_true", help="Run booking test step")
  528. parser.add_argument("--no-cleanup", action="store_true", help="Do not automatically cleanup browser on finish")
  529. parser.add_argument("--keep-on-error", action="store_true", default=False, help="Do not close browser if any error/exception occurs during test (default: False)")
  530. parser.add_argument("--only-init", action="store_true", help="Only test initialization and exit")
  531. args = parser.parse_args()
  532. target_plugin = args.plugin or args.plugin_pos
  533. config_path = resolve_config_path(args.config)
  534. if config_path:
  535. print(f"[PluginTester] Using configuration file: {config_path}")
  536. elif args.config:
  537. print(f"[PluginTester] Error: Specified config file '{args.config}' not found.")
  538. sys.exit(1)
  539. # 如果指定了单个 plugin
  540. if target_plugin and target_plugin.lower() != "all":
  541. if config_path:
  542. tester = PluginTester.from_json_config(
  543. plugin_name=target_plugin,
  544. config_path=config_path,
  545. group_id=args.group,
  546. user_override=args.user,
  547. password_override=args.password,
  548. proxy_override=args.proxy
  549. )
  550. else:
  551. print("[PluginTester] Warning: No test_conf.json found, using basic default config.")
  552. cfg = PluginTester.create_default_config(
  553. username=args.user or "test_user@example.com",
  554. password=args.password or "TestPassword123!",
  555. proxy_url=args.proxy
  556. )
  557. tester = PluginTester(plugin_name=target_plugin, group_id=args.group or "test.group", config=cfg)
  558. if args.only_init:
  559. res = tester.test_init()
  560. sys.exit(0 if res.success else 1)
  561. passed = tester.run_pipeline(
  562. test_book=args.book,
  563. auto_cleanup=not args.no_cleanup,
  564. keep_on_error=args.keep_on_error
  565. )
  566. sys.exit(0 if passed else 1)
  567. # 如果未指定 plugin 或 target_plugin == all,且存在配置文件,则遍历执行所有插件
  568. elif config_path:
  569. testers = PluginTester.load_all_from_json(config_path)
  570. if not testers:
  571. print(f"[PluginTester] No plugins found in {config_path}")
  572. sys.exit(1)
  573. overall_passed = True
  574. for tester in testers:
  575. if args.group:
  576. tester.group_id = args.group
  577. if args.user:
  578. tester.config.account.username = args.user
  579. if args.password:
  580. tester.config.account.password = args.password
  581. if args.proxy:
  582. tester.config.proxy = PluginTester.parse_proxy_url(args.proxy)
  583. if args.only_init:
  584. res = tester.test_init()
  585. if not res.success:
  586. overall_passed = False
  587. else:
  588. passed = tester.run_pipeline(
  589. test_book=args.book,
  590. auto_cleanup=not args.no_cleanup,
  591. keep_on_error=args.keep_on_error
  592. )
  593. if not passed:
  594. overall_passed = False
  595. sys.exit(0 if overall_passed else 1)
  596. else:
  597. print("[PluginTester] Error: Please specify --plugin or provide a valid --config JSON file.")
  598. parser.print_help()
  599. sys.exit(1)
  600. if __name__ == "__main__":
  601. main()