78 行
2.9 KiB
TypeScript
78 行
2.9 KiB
TypeScript
import { DeepSeekService } from '../../../src/modules/ai/service/deepseek';
|
|
import { CoolCommException } from '@cool-midway/core';
|
|
|
|
describe('智能服务模块: 多租户 BYOK 配置隔离与 Token 成本风控', () => {
|
|
let service: DeepSeekService;
|
|
|
|
beforeEach(() => {
|
|
delete process.env.DEEPSEEK_API_KEY;
|
|
delete process.env.DEEPSEEK_BASE_URL;
|
|
service = new DeepSeekService();
|
|
});
|
|
|
|
describe('1. 租户专属配置隔离 (Tenant BYOK)', () => {
|
|
it('未单独配置的租户,获取配置时应优雅回退至平台公共默认配置', () => {
|
|
const tenantConfig = service.getTenantConfig(88);
|
|
expect(tenantConfig.baseUrl).toBe('https://api.deepseek.com');
|
|
expect(tenantConfig.model).toBe('deepseek-chat');
|
|
expect(service.hasTenantConfig(88)).toBe(false);
|
|
});
|
|
|
|
it('特定租户配置专属 API Key 与定制模型后,应严格与公共配置及其他租户隔离', () => {
|
|
// 租户 101 配置独立 Key (BYOK)
|
|
service.updateTenantConfig(101, {
|
|
apiKey: 'sk-tenant-101-custom-key',
|
|
model: 'deepseek-reasoner',
|
|
baseUrl: 'https://gateway.company101.com',
|
|
});
|
|
|
|
expect(service.hasTenantConfig(101)).toBe(true);
|
|
const config101 = service.getTenantConfig(101);
|
|
expect(config101.apiKey).toBe('sk-tenant-101-custom-key');
|
|
expect(config101.model).toBe('deepseek-reasoner');
|
|
expect(config101.baseUrl).toBe('https://gateway.company101.com');
|
|
|
|
// 租户 202 保持未受影响
|
|
expect(service.hasTenantConfig(202)).toBe(false);
|
|
const config202 = service.getTenantConfig(202);
|
|
expect(config202.apiKey).toBeUndefined();
|
|
expect(config202.baseUrl).toBe('https://api.deepseek.com');
|
|
});
|
|
});
|
|
|
|
describe('2. 租户 Token 消耗度量与限流风控 (Token Metering & Quota)', () => {
|
|
it('调用 recordTokenUsage 应准确累计指定租户的 Token 消耗流水', () => {
|
|
service.recordTokenUsage(101, {
|
|
promptTokens: 120,
|
|
completionTokens: 80,
|
|
totalTokens: 200,
|
|
});
|
|
|
|
service.recordTokenUsage(101, {
|
|
promptTokens: 50,
|
|
completionTokens: 50,
|
|
totalTokens: 100,
|
|
});
|
|
|
|
const usage = service.getTenantTokenUsage(101);
|
|
expect(usage.totalTokens).toBe(300);
|
|
expect(usage.promptTokens).toBe(170);
|
|
expect(usage.completionTokens).toBe(130);
|
|
expect(usage.callCount).toBe(2);
|
|
});
|
|
|
|
it('当租户 Token 用量超出配额上限时,assertTenantTokenQuota 必须阻断抛错', () => {
|
|
// 设置租户 101 最大配额 500 Token
|
|
service.setTenantTokenQuota(101, 500);
|
|
|
|
service.recordTokenUsage(101, { totalTokens: 480 });
|
|
|
|
// 预估 10 Token,尚未超限 (490 <= 500)
|
|
expect(() => service.assertTenantTokenQuota(101, 10)).not.toThrow();
|
|
|
|
// 预估 30 Token,超出配额 (480 + 30 = 510 > 500)
|
|
expect(() => service.assertTenantTokenQuota(101, 30)).toThrow(CoolCommException);
|
|
});
|
|
});
|
|
});
|