test-balance-check.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * 测试 errorHandling 条件匹配 + 弹充值网址逻辑
  3. */
  4. const fs = require('fs');
  5. const path = require('path');
  6. // 加载 api-config.json
  7. const config = JSON.parse(
  8. fs.readFileSync(path.join(__dirname, '..', 'jimeng', 'jimeng-img-v4', 'api-config.json'), 'utf-8')
  9. );
  10. // 条件匹配函数(同 skill-executor.js)
  11. function matchesErrorConditions(resp, errorDef) {
  12. if (!errorDef || !errorDef.conditions) return false;
  13. const results = errorDef.conditions.map(cond => {
  14. const v = resp[cond.responseField];
  15. if (v == null) return false;
  16. if (cond.operator === 'in') return Array.isArray(cond.value) && cond.value.includes(v);
  17. if (cond.operator === 'contains' && typeof v === 'string')
  18. return cond.value.some(k => v.toLowerCase().includes(k.toLowerCase()));
  19. return false;
  20. });
  21. return errorDef.matchMode === 'all' ? results.every(Boolean) : results.some(Boolean);
  22. }
  23. // 模板变量替换
  24. function resolveTemplate(tpl, vars) {
  25. return tpl.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] || '');
  26. }
  27. // 模拟各种 API 响应
  28. const testCases = [
  29. { code: -2, msg: '余额不足' },
  30. { code: -3, msg: 'quota exceeded' },
  31. { code: 402, msg: 'insufficient balance' },
  32. { code: 429, msg: 'rate limit' },
  33. { code: -10, message: 'balance not enough' },
  34. { code: 200, msg: 'ok' },
  35. { code: 500, msg: 'server error' },
  36. { code: 401, msg: 'unauthorized token' },
  37. ];
  38. console.log('=== 余额不足检测 测试 ===\n');
  39. const balanceDef = config.errorHandling.balanceInsufficient;
  40. const unauthDef = config.errorHandling.unauthorized;
  41. testCases.forEach(resp => {
  42. const isBalance = matchesErrorConditions(resp, balanceDef);
  43. const isUnauth = matchesErrorConditions(resp, unauthDef);
  44. const label = isBalance ? '⚡ 触发充值' : isUnauth ? '🔒 触发授权' : '✅ 正常放行';
  45. console.log(` code=${String(resp.code).padStart(4)} msg="${resp.msg || resp.message || ''}" => ${label}`);
  46. });
  47. // 演示生成充值 URL
  48. console.log('\n=== 生成充值网址 ===\n');
  49. const handler = config.tokenConfig.onBalanceInsufficient;
  50. const url = resolveTemplate(handler.qrCodeUrl, { user: 'E4KpGvTEto', apigid: 'Vo3ROWEvDy' });
  51. console.log(' URL:', url);
  52. console.log(' title:', handler.title);
  53. console.log(' message:', handler.message);