Files
AI-cut/tests/providers.test.mjs
T

13 lines
1.9 KiB
JavaScript

import {test} from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import {complete,listModels,parseJson} from '../desktop/core/providers.mjs';
test('适配器协议合约(本机测试服务器,不代表云端联调)',async()=>{
let body,url,headers;const server=http.createServer(async(req,res)=>{let data='';for await(const part of req)data+=part;body=data?JSON.parse(data):null;url=req.url;headers=req.headers;res.setHeader('Content-Type','application/json');if(req.url==='/api/chat')res.end(JSON.stringify({message:{content:'{"ok":true}'},eval_count:4}));else if(req.url==='/messages')res.end(JSON.stringify({content:[{type:'text',text:'{"ok":true}'}]}));else if(req.url.includes('generateContent'))res.end(JSON.stringify({candidates:[{content:{parts:[{text:'{"ok":true}'}]}}]}));else if(req.url==='/models')res.end(JSON.stringify({data:[{id:'test-only'}]}));else res.end(JSON.stringify({choices:[{message:{content:'{"ok":true}'}}]}));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const baseUrl=`http://127.0.0.1:${server.address().port}`;
try{for(const protocol of ['ollama','openai','anthropic','gemini']){const r=await complete({protocol,baseUrl,model:'test-only',key:'contract-secret'},'json');assert.equal(r.data.ok,true);if(protocol==='anthropic'){assert.equal(headers['x-api-key'],'contract-secret');assert.equal(body.max_tokens,8192);}if(protocol==='gemini'){assert.ok(url.endsWith(':generateContent'));assert.equal(headers['x-goog-api-key'],'contract-secret');}if(protocol==='ollama')assert.equal(body.stream,false);}assert.equal((await listModels({protocol:'openai',baseUrl}))[0].id,'test-only');}
finally{server.closeAllConnections();server.close();}
await assert.rejects(complete({protocol:'openai',baseUrl:'https://example.com',model:'x',allowText:false},'private'),/未授权/);
assert.deepEqual(parseJson('```json\n{"ok":true}\n```'),{ok:true});
});