plugin_tester.py 28 KB

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