Files
CyberGril/web/tests/domain.test.ts
T

31 lines
5.5 KiB
TypeScript

import { newId } from '../src/domain/id';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { publicView, eventById } from '../src/domain/privacy';
import { validateCreation } from '../src/domain/model';
import { freshState, sampleDays } from '../src/demo/fixtures';
import { loadState, parseState, persistState } from '../src/adapters/storage';
import { DemoAdapter, TurnGate } from '../src/adapters/demo';
const identity = { id: 'same-person', name: '小满', birth: '2000-01-01', hour: '亥时', relation: '朋友' as const, nickname: '', boundary: '' };
const seed = () => sampleDays(freshState(identity));
afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });
describe('approved business rules', () => {
it('fails closed on private/unknown references throughout public data', () => { const s = seed(); s.memories.push({ id: 'unknown', title: '未知引用', text: '不能展示', group: '我们一起的', source: 'x', lifeIds: ['missing'] }); const view = publicView(s); const text = JSON.stringify(view); for (const secret of ['秘密散步', '私密地点', '隐私测试内容', '未知引用'])
expect(text).not.toContain(secret); expect(eventById(s, 'secret')).toBeUndefined(); expect(view.events).toHaveLength(4); expect(view.memories.some(m => m.id === 'habit')).toBe(true); expect(view.messages.some(m => m.id === 'c1')).toBe(true); });
it('unknown sharing status is hidden', () => { const s = seed(); delete (s.events[0] as Partial<typeof s.events[number]>).shared; expect(publicView(s).events.some(e => e.id === 'book')).toBe(false); expect(publicView(s).memories.some(m => m.id === 'habit')).toBe(false); });
it('requires real name, adult birth and explicit relationship', () => { expect(validateCreation(' ', '2000-01-01', '朋友')).toContain('名字'); expect(validateCreation('小满', '2000-01-01', '')).toContain('关系'); expect(validateCreation('小满', '2020-01-01', '朋友')).toContain('18'); expect(validateCreation('小满', '2000-01-01', '朋友')).toBe(''); });
});
describe('local persistence and restore boundary', () => {
it('reopens the same creation and preserves drafts when save fails', () => { const data = new Map<string, string>(); vi.stubGlobal('localStorage', { getItem: (k: string) => data.get(k) || null, setItem: (k: string, v: string) => data.set(k, v) }); const s = seed(); persistState(s); expect(loadState().state?.identity).toEqual(identity); expect(() => persistState({ ...s, settings: { ...s.settings, city: '上海' } }, true)).toThrow(); expect(loadState().state?.settings.city).toBe('杭州'); });
it('corrupt storage produces a visible boundary instead of new creation', () => { vi.stubGlobal('localStorage', { getItem: () => '{invalid' }); expect(loadState().state).toBeNull(); expect(loadState().error).not.toBe(''); });
it('rejects another companion, malformed records and oversized files', () => { const s = seed(); expect(() => parseState(JSON.stringify({ ...s, identity: { ...identity, id: 'other' } }), identity)).toThrow('另一位'); expect(() => parseState(JSON.stringify({ ...s, messages: [{ text: 'invalid' }] }), identity)).toThrow(); expect(() => parseState(' '.repeat(5000001))).toThrow('太大'); });
it('untrusted text stays text, arbitrary keys are dropped, pending turns cancelled on restore', () => { const s = seed(); s.messages.push({ id: 'script', role: 'companion', text: '<img src=x onerror=alert(1)>', lifeIds: [], status: 'pending' }); const parsed = parseState(JSON.stringify({ ...s, script: 'evil' }), identity); expect(parsed.messages.at(-1)?.text).toContain('<img'); expect(parsed.messages.at(-1)?.status).toBe('cancelled'); expect(parsed).not.toHaveProperty('script'); });
it('keeps when she told you only on shared records', () => { const s = seed(); s.events[3] = { ...s.events[3], told: '13:20 告诉你' }; const parsed = parseState(JSON.stringify(s), identity); expect(parsed.events.find(e => e.id === 'book')?.told).toBe('19:46 告诉你'); expect(parsed.events.find(e => e.id === 'secret')).not.toHaveProperty('told'); });
});
describe('turn/epoch cancellation', () => {
it('rejects old results after new turn, cancel, exit, and resync', () => { const g = new TurnGate(); const a = g.begin('a'); const e = { t: 'chat.delta' as const, epoch: 1, turn_id: 'a', delta: '旧' }; expect(g.accepts(e)).toBe(true); g.begin('b'); expect(a.aborted).toBe(true); expect(g.accepts(e)).toBe(false); g.cancel(); expect(g.accepts({ ...e, turn_id: 'b' })).toBe(false); g.begin('b'); g.resync(); g.begin('c'); expect(g.accepts({ ...e, turn_id: 'c' })).toBe(false); });
it('aborts simulator without reviving a late reply', async () => { vi.useFakeTimers(); const c = new AbortController(), emit = vi.fn(); const p = new DemoAdapter().send('hello', 'a', 1, c.signal, emit).catch(e => e.name); c.abort(); await vi.runAllTimersAsync(); expect(await p).toBe('AbortError'); expect(emit).not.toHaveBeenCalled(); });
it('simulated send failure is retryable without fabricating a reply', async () => { vi.useFakeTimers(); const emit = vi.fn(); const p = new DemoAdapter().send('hello', 'a', 1, new AbortController().signal, emit, true).catch(e => e.message); await vi.runAllTimersAsync(); expect(await p).toContain('没发出去'); expect(emit).not.toHaveBeenCalled(); });
});
it('creates valid local ids without secure-context randomUUID',()=>{vi.stubGlobal('crypto',{getRandomValues:(a:Uint8Array)=>{a.fill(7);return a;}});expect(newId()).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);});