plugin_tester.py 27 KB

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