Files

134 lines
7.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// 服务器地址测速(src/generation-provider-ping.js)行为测试 —— 独立文件
//
// 背景(2026-11-12,用户报「设置里三个地址测速全是 ✗ 失败」):
// 测速直连 provider 的 `GET {base}/models`。tu-zi 这套 one-api 部署的 CORS 只加在
// 预检 OPTIONS 与生图 POST 上,`GET /models` 的真实响应**没有** Access-Control-Allow-Origin
// ⇒ 浏览器 net::ERR_FAILED,三行全红;而服务本身是好的(curl = 401 + 146ms)。
// 修法:普通请求失败后退一次 `mode:'no-cors'` —— 读不到状态码,但「连得上 + 耗时」够用。
//
// 本文件钉住四件事:
// ① CORS 被拦 ≠ 服务不可达:必须退 no-cors 并判为可达(否则又是全红);
// ② 超时**不允许**再退 no-cors(会把 6s 超时翻倍成 12s,用户以为卡死);
// ③ 真失败(DNS/证书/no-cors 也不通)必须带可读原因,不能只给一个 ✗;
// ④ 排序按耗时升序,且最多打 10 个地址。
const path = require('path')
const fs = require('fs')
const root = path.join(__dirname, '..')
const SRC = fs.readFileSync(path.join(root, 'src/generation-provider-ping.js'), 'utf8')
let clock = 0
const FakeDate = { now: () => (clock += 10) }
const timers = []
const fakeSetTimeout = (fn, ms) => { const t = { fn, ms, cleared: false }; timers.push(t); return t }
const fakeClearTimeout = (t) => { if (t) t.cleared = true }
// fetch mock:由用例设置 calls 队列,按顺序消费
let script = []
const calls = []
const fakeFetch = (url, init) => {
calls.push({ url, init: init || {} })
const next = script.shift()
if (!next) return Promise.reject(new Error('mock 队列已空'))
return next(url, init || {})
}
const box = {}
const factory = new Function(
'window', 'globalThis', 'fetch', 'AbortController', 'setTimeout', 'clearTimeout', 'Date',
SRC.replace(/^;\(function \(global\) \{/, '(function (global) {'), // 去掉行首分号,保持 IIFE 可执行
)
factory(box, box, fakeFetch, global.AbortController, fakeSetTimeout, fakeClearTimeout, FakeDate)
const P = box.IWBProviderPing
let pass = 0
let fail = 0
const ok = (name, cond, extra) => {
if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name + (extra ? ' → ' + extra : '')) }
}
const eq = (name, got, want) => ok(name + '(' + JSON.stringify(got) + ' === ' + JSON.stringify(want) + ')', got === want, 'got ' + JSON.stringify(got))
const reset = () => { script = []; calls.length = 0; timers.length = 0; clock = 0 }
const okResp = (status) => () => Promise.resolve({ status })
const okRespAfter = (delayMs) => () => { clock += delayMs; return Promise.resolve({ status: 200 }) }
const throwErr = (msg) => () => Promise.reject(new Error(msg))
;(async () => {
ok('模块加载并导出 IWBProviderPing', !!P && typeof P.pingOne === 'function' && typeof P.pingAll === 'function')
ok('导出对象冻结(外部改不动)', Object.isFrozen(P))
eq('默认超时常量', P.PING_TIMEOUT_MS, 6000)
// ---- ① URL 拼装 ----
eq('modelsUrlOf 去尾部斜杠', P.modelsUrlOf('https://a.example/v1/'), 'https://a.example/v1/models')
eq('modelsUrlOf 空值 → 空串', P.modelsUrlOf(' '), '')
eq('modelsUrlOf 走 normalizeEndpointBase 钩子', P.modelsUrlOf('https://a.example', (b) => b + '/v1'), 'https://a.example/v1/models')
reset()
const emptyRes = await P.pingOne(' ')
ok('空地址直接判失败且不发请求', emptyRes.ok === false && calls.length === 0 && emptyRes.error === '地址为空')
// ---- ② 服务端带 CORS:一次请求读完状态码 ----
reset()
script = [okResp(401)]
const r1 = await P.pingOne('https://api.example/v1')
ok('带 CORS 时 ok=true 且能读到状态码', r1.ok === true && r1.status === 401 && r1.cors === true, JSON.stringify(r1))
eq('只发了 1 次请求', calls.length, 1)
eq('请求打到 /models', calls[0].url, 'https://api.example/v1/models')
ok('普通请求没有 mode:no-cors', calls[0].init.mode === undefined)
ok('定时器被正常清理', timers.length === 1 && timers[0].cleared === true)
// ---- ③ 被 CORS 拦:必须退 no-cors 并判为可达(这就是这次用户报的故障) ----
reset()
script = [throwErr('Failed to fetch'), okResp(0)]
const r2 = await P.pingOne('https://api.tu-zi.com/v1')
ok('CORS 被拦但 no-cors 通了 ⇒ 判为可达', r2.ok === true, JSON.stringify(r2))
eq('标记 cors=false(UI 据此提示是估算值)', r2.cors, false)
eq('opaque 响应没有状态码', r2.status, 0)
eq('退了一次重试(共 2 次请求)', calls.length, 2)
eq('第二次是 no-cors', calls[1].init.mode, 'no-cors')
// ---- ④ 超时:必须直接失败,不许再退 no-cors ----
reset()
const abortErr = new Error('The operation was aborted')
abortErr.name = 'AbortError'
script = [() => Promise.reject(abortErr)]
const r3 = await P.pingOne('https://slow.example/v1', { timeoutMs: 1234 })
ok('超时判失败', r3.ok === false)
ok('超时原因可读(含「超时」)', /超时/.test(String(r3.error)), String(r3.error))
eq('超时不再重试(只有 1 次请求)', calls.length, 1)
eq('超时时间取调用方传入值', timers[0].ms, 1234)
// ---- ⑤ 真失败:两次都不通,原因必须带出来 ----
reset()
script = [throwErr('Failed to fetch'), throwErr('net::ERR_NAME_NOT_RESOLVED')]
const r4 = await P.pingOne('https://nope.example/v1')
ok('两次都不通 ⇒ ok=false', r4.ok === false)
ok('失败原因非空且可读', /ERR_NAME_NOT_RESOLVED/.test(String(r4.error)), String(r4.error))
// ---- ⑥ 并发 + 排序 + 上限 ----
// ⚠️ 只断言「耗时非递减」,不断言具体 URL 顺序:三个 pingOne 是并发的,共享同一个假时钟,
// t0 与结束时刻会互相串扰,URL 顺序不可控(第一版就是这么假红/假绿的)。
// 「非递减」在排序反了的负例下必然打红(实测 [90,60,50]),判别力够。
reset()
script = [okRespAfter(30), okRespAfter(10), okRespAfter(20)]
const all = await P.pingAll(['https://a/v1', 'https://b/v1', 'https://c/v1'])
eq('3 个地址 3 条结果', all.results.length, 3)
const mss = all.results.map((x) => x.ms)
ok('结果按耗时非递减排列', mss.every((v, i) => i === 0 || mss[i - 1] <= v), JSON.stringify(mss))
eq('URL 没被改写', all.results.map((x) => x.url).sort().join(','), 'https://a/v1,https://b/v1,https://c/v1')
reset()
const many = Array.from({ length: 25 }, (_, i) => 'https://h' + i + '.example/v1')
script = many.map(() => okResp(200))
const capped = await P.pingAll(many)
eq('最多只打 10 个地址', capped.results.length, 10)
reset()
script = [okResp(200)]
const weird = await P.pingAll(['https://ok.example/v1', null, undefined])
eq('空项也进结果(不会整体 reject)', weird.results.length, 3)
ok('空项判失败', weird.results.filter((x) => !x.ok).length === 2, JSON.stringify(weird.results))
console.log('\nprovider-ping: ' + pass + ' 通过 / ' + fail + ' 失败')
process.exitCode = fail ? 1 : 0
})()