This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+46 -46
View File
@@ -1,70 +1,70 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
actionErrorMessage,
publishActionResult,
scheduleActionNoticeDismiss,
actionErrorMessage,
publishActionResult,
scheduleActionNoticeDismiss,
} from '../src/contexts/ActionFeedbackContext';
describe('action feedback error details', () => {
it('preserves the real Error message', () => {
expect(actionErrorMessage(new Error('证书校验失败'))).toBe('证书校验失败');
});
it('preserves the real Error message', () => {
expect(actionErrorMessage(new Error('证书校验失败'))).toBe('证书校验失败');
});
it('preserves a non-empty string rejection', () => {
expect(actionErrorMessage('保存被拒绝')).toBe('保存被拒绝');
});
it('preserves a non-empty string rejection', () => {
expect(actionErrorMessage('保存被拒绝')).toBe('保存被拒绝');
});
it('makes an unknown rejection observable', () => {
expect(actionErrorMessage({ code: 'E_UNKNOWN' })).toBe('未知错误');
});
it('makes an unknown rejection observable', () => {
expect(actionErrorMessage({ code: 'E_UNKNOWN' })).toBe('未知错误');
});
});
describe('action feedback result publishing', () => {
it('publishes a superseded action result without replacing the active surface', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
it('publishes a superseded action result without replacing the active surface', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
publishActionResult(false, updateCurrentActivity, publishNotice);
publishActionResult(false, updateCurrentActivity, publishNotice);
expect(updateCurrentActivity).not.toHaveBeenCalled();
expect(publishNotice).toHaveBeenCalledOnce();
});
expect(updateCurrentActivity).not.toHaveBeenCalled();
expect(publishNotice).toHaveBeenCalledOnce();
});
it('updates and publishes the current action result', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
it('updates and publishes the current action result', () => {
const updateCurrentActivity = vi.fn();
const publishNotice = vi.fn();
publishActionResult(true, updateCurrentActivity, publishNotice);
publishActionResult(true, updateCurrentActivity, publishNotice);
expect(updateCurrentActivity).toHaveBeenCalledOnce();
expect(publishNotice).toHaveBeenCalledOnce();
});
expect(updateCurrentActivity).toHaveBeenCalledOnce();
expect(publishNotice).toHaveBeenCalledOnce();
});
});
describe('action feedback auto-dismiss', () => {
afterEach(() => {
vi.useRealTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('dismisses a completed notice after its visible countdown', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
it('dismisses a completed notice after its visible countdown', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
scheduleActionNoticeDismiss(dismiss);
vi.advanceTimersByTime(4_999);
expect(dismiss).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(dismiss).toHaveBeenCalledOnce();
});
scheduleActionNoticeDismiss(dismiss);
vi.advanceTimersByTime(4_999);
expect(dismiss).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(dismiss).toHaveBeenCalledOnce();
});
it('cancels dismissal when the notice unmounts early', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
it('cancels dismissal when the notice unmounts early', () => {
vi.useFakeTimers();
const dismiss = vi.fn();
const cancel = scheduleActionNoticeDismiss(dismiss);
cancel();
vi.runAllTimers();
const cancel = scheduleActionNoticeDismiss(dismiss);
cancel();
vi.runAllTimers();
expect(dismiss).not.toHaveBeenCalled();
});
expect(dismiss).not.toHaveBeenCalled();
});
});
@@ -2,49 +2,56 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'trace-token',
save: () => undefined,
load: () => 'trace-token',
save: () => undefined,
};
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllGlobals();
});
describe('API client full TRACE export', () => {
it('downloads the exact authenticated server text and filename', async () => {
const body = 'header\nTRACE recvHex=000102aabbcc\n';
const fetchMock = vi.fn().mockResolvedValue(new Response(body, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': 'attachment; filename="server-trace.log"',
},
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
it('downloads the exact authenticated server text and filename', async () => {
const body = 'header\nTRACE recvHex=000102aabbcc\n';
const fetchMock = vi.fn().mockResolvedValue(
new Response(body, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': 'attachment; filename="server-trace.log"',
},
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.logs.exportTrace()).resolves.toEqual({
text: body,
filename: 'server-trace.log',
await expect(client.logs.exportTrace()).resolves.toEqual({
text: body,
filename: 'server-trace.log',
});
expect(fetchMock).toHaveBeenCalledExactlyOnceWith(
'/api/logs/export/trace',
expect.objectContaining({
headers: { Authorization: 'Bearer trace-token' },
}),
);
});
expect(fetchMock).toHaveBeenCalledExactlyOnceWith(
'/api/logs/export/trace',
expect.objectContaining({
headers: { Authorization: 'Bearer trace-token' },
}),
);
});
it('rejects a failed export instead of downloading an error body', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
JSON.stringify({ message: 'export unavailable' }),
{ status: 500, statusText: 'Internal Server Error' },
)));
const client = createApiClient({ tokenStore });
it('rejects a failed export instead of downloading an error body', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ message: 'export unavailable' }), {
status: 500,
statusText: 'Internal Server Error',
}),
),
);
const client = createApiClient({ tokenStore });
await expect(client.logs.exportTrace()).rejects.toMatchObject({
status: 500,
message: 'export unavailable',
await expect(client.logs.exportTrace()).rejects.toMatchObject({
status: 500,
message: 'export unavailable',
});
});
});
});
@@ -4,86 +4,104 @@ import { createApiClient } from '../src/lib/api/client';
const encoder = new TextEncoder();
describe('API client SSE authentication', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('uses an Authorization header, parses frames, and never puts the token in the URL', async () => {
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
const stream = new ReadableStream<Uint8Array>({
start(controller) { streamController = controller; },
});
const fetchMock = vi.fn().mockResolvedValue(new Response(stream, {
status: 200,
headers: { 'content-type': 'text/event-stream' },
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({
tokenStore: { load: () => 'secret-session-token', save: vi.fn() },
});
const received = new Promise<unknown>((resolve) => {
const dispose = client.stateStream({
onEvent: (event) => {
resolve(event);
dispose();
},
});
afterEach(() => {
vi.unstubAllGlobals();
});
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
streamController?.enqueue(encoder.encode('data: {"kind":"ready"}\n\n'));
it('uses an Authorization header, parses frames, and never puts the token in the URL', async () => {
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
streamController = controller;
},
});
const fetchMock = vi.fn().mockResolvedValue(
new Response(stream, {
status: 200,
headers: { 'content-type': 'text/event-stream' },
}),
);
vi.stubGlobal('fetch', fetchMock);
await expect(received).resolves.toEqual({ kind: 'ready' });
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/state/stream');
expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-session-token');
expect(init.signal?.aborted).toBe(true);
});
const client = createApiClient({
tokenStore: { load: () => 'secret-session-token', save: vi.fn() },
});
const received = new Promise<unknown>((resolve) => {
const dispose = client.stateStream({
onEvent: (event) => {
resolve(event);
dispose();
},
});
});
it('clears the session and stops reconnecting after an unauthorized response', async () => {
const save = vi.fn();
const onUnauthorized = vi.fn();
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 }));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({
tokenStore: { load: () => 'expired-token', save },
onUnauthorized,
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
streamController?.enqueue(encoder.encode('data: {"kind":"ready"}\n\n'));
await expect(received).resolves.toEqual({ kind: 'ready' });
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('/api/state/stream');
expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-session-token');
expect(init.signal?.aborted).toBe(true);
});
const statuses: string[] = [];
client.stateStream({ onEvent: vi.fn(), onStatus: (status) => statuses.push(status) });
it('clears the session and stops reconnecting after an unauthorized response', async () => {
const save = vi.fn();
const onUnauthorized = vi.fn();
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 }));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({
tokenStore: { load: () => 'expired-token', save },
onUnauthorized,
});
const statuses: string[] = [];
await vi.waitFor(() => expect(onUnauthorized).toHaveBeenCalledTimes(1));
expect(save).toHaveBeenCalledWith(null);
expect(statuses.at(-1)).toBe('closed');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
client.stateStream({ onEvent: vi.fn(), onStatus: (status) => statuses.push(status) });
it('reconnects after a completed stream without leaking the token', async () => {
vi.useFakeTimers();
try {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response('data: {"kind":"ready"}\r\n\r\n', { status: 200 }))
.mockImplementationOnce((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true });
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({
tokenStore: { load: () => 'reconnect-token', save: vi.fn() },
});
const onEvent = vi.fn();
const statuses: string[] = [];
const dispose = client.stateStream({ onEvent, onStatus: (status) => statuses.push(status) });
await vi.waitFor(() => expect(onUnauthorized).toHaveBeenCalledTimes(1));
expect(save).toHaveBeenCalledWith(null);
expect(statuses.at(-1)).toBe('closed');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
await vi.waitFor(() => expect(onEvent).toHaveBeenCalledWith({ kind: 'ready' }));
expect(statuses).toContain('reconnecting');
await vi.advanceTimersByTimeAsync(1_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls.every(([url]) => url === '/api/state/stream')).toBe(true);
dispose();
} finally {
vi.useRealTimers();
}
});
it('reconnects after a completed stream without leaking the token', async () => {
vi.useFakeTimers();
try {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response('data: {"kind":"ready"}\r\n\r\n', { status: 200 }),
)
.mockImplementationOnce(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => reject(new DOMException('Aborted', 'AbortError')),
{ once: true },
);
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({
tokenStore: { load: () => 'reconnect-token', save: vi.fn() },
});
const onEvent = vi.fn();
const statuses: string[] = [];
const dispose = client.stateStream({
onEvent,
onStatus: (status) => statuses.push(status),
});
await vi.waitFor(() => expect(onEvent).toHaveBeenCalledWith({ kind: 'ready' }));
expect(statuses).toContain('reconnecting');
await vi.advanceTimersByTimeAsync(1_000);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls.every(([url]) => url === '/api/state/stream')).toBe(true);
dispose();
} finally {
vi.useRealTimers();
}
});
});
+99 -71
View File
@@ -2,85 +2,113 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'test-token',
save: () => undefined,
load: () => 'test-token',
save: () => undefined,
};
describe('API client request deadline', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('aborts a pending request and reports a retryable timeout', async () => {
vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('Aborted', 'AbortError'));
}, { once: true });
})));
const client = createApiClient({ tokenStore });
const request = client.request('/api/processes');
const rejection = expect(request).rejects.toMatchObject({
message: '请求超时,请重试',
code: 'REQUEST_TIMEOUT',
beforeEach(() => {
vi.useFakeTimers();
});
await vi.advanceTimersByTimeAsync(30_000);
await rejection;
});
it('cancels a login probe without preventing a later retry', async () => {
const fetchMock = vi
.fn()
.mockImplementationOnce((_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('Aborted', 'AbortError'));
}, { once: true });
}),
)
.mockResolvedValueOnce(new Response(JSON.stringify({
info: { port: 0, uin: '', identityKnown: false },
}), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
const controller = new AbortController();
const cancelled = client.processes.probeLoginInfo(4242, controller.signal);
controller.abort();
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
await expect(client.processes.probeLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
});
it('settles a pending login with a retryable timeout message', async () => {
vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('Aborted', 'AbortError'));
}, { once: true });
}),
));
const client = createApiClient({ tokenStore });
it('aborts a pending request and reports a retryable timeout', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
),
);
const client = createApiClient({ tokenStore });
const login = client.login('password');
await vi.advanceTimersByTimeAsync(30_000);
const request = client.request('/api/processes');
const rejection = expect(request).rejects.toMatchObject({
message: '请求超时,请重试',
code: 'REQUEST_TIMEOUT',
});
await vi.advanceTimersByTimeAsync(30_000);
await expect(login).resolves.toEqual({
ok: false,
message: '请求超时,请重试',
await rejection;
});
it('cancels a login probe without preventing a later retry', async () => {
const fetchMock = vi
.fn()
.mockImplementationOnce(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({
info: { port: 0, uin: '', identityKnown: false },
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
const controller = new AbortController();
const cancelled = client.processes.probeLoginInfo(4242, controller.signal);
controller.abort();
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
await expect(client.processes.probeLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('settles a pending login with a retryable timeout message', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
),
);
const client = createApiClient({ tokenStore });
const login = client.login('password');
await vi.advanceTimersByTimeAsync(30_000);
await expect(login).resolves.toEqual({
ok: false,
message: '请求超时,请重试',
});
});
});
});
+59 -38
View File
@@ -2,50 +2,71 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => null as string | null,
save: vi.fn(),
load: () => null as string | null,
save: vi.fn(),
};
afterEach(() => {
vi.unstubAllGlobals();
tokenStore.save.mockReset();
vi.unstubAllGlobals();
tokenStore.save.mockReset();
});
describe('login 2FA client', () => {
it('returns needsTotp without storing a session token', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
success: false,
needsTotp: true,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
})));
it('returns needsTotp without storing a session token', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
JSON.stringify({
success: false,
needsTotp: true,
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
),
);
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!')).resolves.toEqual({ ok: false, needsTotp: true });
expect(tokenStore.save).not.toHaveBeenCalled();
});
it('sends the TOTP on the second login request and stores the session', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
success: true,
token: 'session-token',
mustChangePassword: false,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!', { totp: '287082' })).resolves.toEqual({
ok: true,
mustChangePassword: false,
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!')).resolves.toEqual({
ok: false,
needsTotp: true,
});
expect(tokenStore.save).not.toHaveBeenCalled();
});
it('sends the TOTP on the second login request and stores the session', async () => {
const fetchMock = vi.fn(
async () =>
new Response(
JSON.stringify({
success: true,
token: 'session-token',
mustChangePassword: false,
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.login('Correct-Horse-1!', { totp: '287082' })).resolves.toEqual({
ok: true,
mustChangePassword: false,
});
expect(fetchMock).toHaveBeenCalledWith(
'/api/login',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Correct-Horse-1!', totp: '287082' }),
}),
);
expect(tokenStore.save).toHaveBeenCalledWith('session-token');
});
expect(fetchMock).toHaveBeenCalledWith('/api/login', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Correct-Horse-1!', totp: '287082' }),
}));
expect(tokenStore.save).toHaveBeenCalledWith('session-token');
});
});
+21 -21
View File
@@ -2,27 +2,27 @@ import { describe, expect, it } from 'vitest';
import { migrateOverviewBlocks } from '../src/lib/dashboard-layout';
describe('migrateOverviewBlocks', () => {
it('preserves saved widget configuration while restoring the grid', () => {
const migrated = migrateOverviewBlocks([
{
id: 'account',
visible: true,
x: 8,
y: 14,
w: 4,
h: 1,
config: { uin: '123456789' },
},
]);
it('preserves saved widget configuration while restoring the grid', () => {
const migrated = migrateOverviewBlocks([
{
id: 'account',
visible: true,
x: 8,
y: 14,
w: 4,
h: 1,
config: { uin: '123456789' },
},
]);
expect(migrated.find((item) => item.id === 'account')).toEqual({
id: 'account',
visible: true,
x: 8,
y: 14,
w: 4,
h: 1,
config: { uin: '123456789' },
expect(migrated.find((item) => item.id === 'account')).toEqual({
id: 'account',
visible: true,
x: 8,
y: 14,
w: 4,
h: 1,
config: { uin: '123456789' },
});
});
});
});
+18 -18
View File
@@ -1,29 +1,29 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import {
DEVELOPER_CRASH_MESSAGE,
DeveloperCrashProbe,
developerCrashReducer,
DEVELOPER_CRASH_MESSAGE,
DeveloperCrashProbe,
developerCrashReducer,
} from '../src/components/settings/developer-tools';
import { ErrorPage } from '../src/components/pages/status-screens';
import { SETTINGS_TABS } from '../src/router';
describe('developer settings tools', () => {
it('keeps the developer page in the public settings route contract', () => {
expect(SETTINGS_TABS).toContain('developer');
});
it('keeps the developer page in the public settings route contract', () => {
expect(SETTINGS_TABS).toContain('developer');
});
it('promotes a confirmed crash into the route error screen', () => {
const requested = developerCrashReducer(false, 'confirm');
expect(() => renderToStaticMarkup(
<DeveloperCrashProbe requested={requested} />,
)).toThrowError(DEVELOPER_CRASH_MESSAGE);
it('promotes a confirmed crash into the route error screen', () => {
const requested = developerCrashReducer(false, 'confirm');
expect(() =>
renderToStaticMarkup(<DeveloperCrashProbe requested={requested} />),
).toThrowError(DEVELOPER_CRASH_MESSAGE);
const html = renderToStaticMarkup(
<ErrorPage error={new Error(DEVELOPER_CRASH_MESSAGE)} reset={() => undefined} />,
);
expect(html).toContain('页面出错了');
expect(html).toContain('重试');
expect(html).toContain(DEVELOPER_CRASH_MESSAGE);
});
const html = renderToStaticMarkup(
<ErrorPage error={new Error(DEVELOPER_CRASH_MESSAGE)} reset={() => undefined} />,
);
expect(html).toContain('页面出错了');
expect(html).toContain('重试');
expect(html).toContain(DEVELOPER_CRASH_MESSAGE);
});
});
+34 -34
View File
@@ -3,40 +3,40 @@ import { describe, expect, it } from 'vitest';
import { IconMorph, iconMorphPresets } from '../src/components/interior/icon-morph';
describe('mobile menu icon morph', () => {
it('keeps the Interior menu and close geometry unchanged', () => {
expect(iconMorphPresets['menu-close'].shapes).toEqual([
{
rotate: 0,
d: ['M 4 7 L 20 7', 'M 4 12 L 20 12', 'M 4 17 L 20 17'],
},
{
rotate: 90,
d: ['M 6.5 6.5 L 17.5 17.5', 'M 12 12 L 12 12', 'M 6.5 17.5 L 17.5 6.5'],
},
]);
});
it('keeps the Interior menu and close geometry unchanged', () => {
expect(iconMorphPresets['menu-close'].shapes).toEqual([
{
rotate: 0,
d: ['M 4 7 L 20 7', 'M 4 12 L 20 12', 'M 4 17 L 20 17'],
},
{
rotate: 90,
d: ['M 6.5 6.5 L 17.5 17.5', 'M 12 12 L 12 12', 'M 6.5 17.5 L 17.5 6.5'],
},
]);
});
it('reflects the controlled sheet state in its accessible semantics', () => {
const menu = renderToStaticMarkup(
<IconMorph
preset="menu-close"
labels={['打开菜单', '关闭菜单']}
semantics="expanded"
active={false}
/>,
);
const close = renderToStaticMarkup(
<IconMorph
preset="menu-close"
labels={['打开菜单', '关闭菜单']}
semantics="expanded"
active
/>,
);
it('reflects the controlled sheet state in its accessible semantics', () => {
const menu = renderToStaticMarkup(
<IconMorph
preset="menu-close"
labels={['打开菜单', '关闭菜单']}
semantics="expanded"
active={false}
/>,
);
const close = renderToStaticMarkup(
<IconMorph
preset="menu-close"
labels={['打开菜单', '关闭菜单']}
semantics="expanded"
active
/>,
);
expect(menu).toContain('aria-label="打开菜单"');
expect(menu).toContain('aria-expanded="false"');
expect(close).toContain('aria-label="关闭菜单"');
expect(close).toContain('aria-expanded="true"');
});
expect(menu).toContain('aria-label="打开菜单"');
expect(menu).toContain('aria-expanded="false"');
expect(close).toContain('aria-label="关闭菜单"');
expect(close).toContain('aria-expanded="true"');
});
});
+61 -61
View File
@@ -3,70 +3,70 @@ import { describe, expect, it, vi } from 'vitest';
import { LoginPage } from '../src/components/pages/login-page';
vi.mock('@/contexts/ThemeContext', () => ({
useTheme: () => ({
appearance: {
background: { type: 'none' },
reduceMotion: true,
disableMotion: true,
palette: 'default',
},
mode: 'light',
setMode: () => undefined,
}),
paletteResolved: () => false,
useTheme: () => ({
appearance: {
background: { type: 'none' },
reduceMotion: true,
disableMotion: true,
palette: 'default',
},
mode: 'light',
setMode: () => undefined,
}),
paletteResolved: () => false,
}));
describe('LoginPage 2FA step', () => {
it('keeps the password form on its own screen', () => {
const markup = renderToStaticMarkup(
<LoginPage onLogin={async () => ({ success: false, error: 'no' })} />,
);
expect(markup).toContain('输入访问令牌');
expect(markup).toContain('进入控制台');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('character 1 of 6');
expect(markup).not.toContain('验证并进入');
});
it('keeps the password form on its own screen', () => {
const markup = renderToStaticMarkup(
<LoginPage onLogin={async () => ({ success: false, error: 'no' })} />,
);
expect(markup).toContain('输入访问令牌');
expect(markup).toContain('进入控制台');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('character 1 of 6');
expect(markup).not.toContain('验证并进入');
});
it('shows a separate TOTP screen after the password factor succeeds', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).not.toContain('输入访问令牌');
expect(markup).toContain('输入 Authenticator 中的 6 位验证码');
expect(markup).not.toContain('验证并进入');
expect(markup).toContain('character 1 of 6');
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).toContain('使用恢复码');
expect(markup).toContain('返回');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('h-[2px] w-3 rounded-full');
});
it('shows a separate TOTP screen after the password factor succeeds', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).not.toContain('输入访问令牌');
expect(markup).toContain('输入 Authenticator 中的 6 位验证码');
expect(markup).not.toContain('验证并进入');
expect(markup).toContain('character 1 of 6');
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).toContain('使用恢复码');
expect(markup).toContain('返回');
expect(markup).toContain('max-w-md');
expect(markup).not.toContain('max-w-2xl');
expect(markup).not.toContain('h-[2px] w-3 rounded-full');
});
it('uses the same cell UI for a recovery code instead of a single field', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
initialUseRecovery
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).toContain('输入保存的一次性恢复码');
expect(markup).toContain('character 1 of 8');
expect(markup).toContain('character 8 of 8');
expect(markup).toContain('可以把完整恢复码粘贴到任意一格');
expect(markup).toContain('改用验证码');
expect(markup).toContain('max-w-2xl');
expect(markup).toContain('h-[2px] w-3 rounded-full');
expect(markup).not.toContain('XXXX-XXXX');
expect(markup).not.toContain('验证并进入');
expect(markup).not.toContain('输入访问令牌');
});
it('uses the same cell UI for a recovery code instead of a single field', () => {
const markup = renderToStaticMarkup(
<LoginPage
initialPassword="Correct-Horse-1!"
initialNeedsTotp
initialUseRecovery
onLogin={async () => ({ success: false, needsTotp: true })}
/>,
);
expect(markup).toContain('输入保存的一次性恢复码');
expect(markup).toContain('character 1 of 8');
expect(markup).toContain('character 8 of 8');
expect(markup).toContain('可以把完整恢复码粘贴到任意一格');
expect(markup).toContain('改用验证码');
expect(markup).toContain('max-w-2xl');
expect(markup).toContain('h-[2px] w-3 rounded-full');
expect(markup).not.toContain('XXXX-XXXX');
expect(markup).not.toContain('验证并进入');
expect(markup).not.toContain('输入访问令牌');
});
});
@@ -1,35 +1,32 @@
import { describe, expect, it } from 'vitest';
import {
messageBuilderSegmentKinds,
newSeg,
} from '../src/components/debug/message-builder';
import { messageBuilderSegmentKinds, newSeg } from '../src/components/debug/message-builder';
import { messageBuilderModeForAction } from '../src/components/debug/param-field';
describe('action message builder capabilities', () => {
it('does not offer forward nodes in ordinary message parameters', () => {
expect(messageBuilderSegmentKinds('message', [])).not.toContain('node');
});
it('does not offer forward nodes in ordinary message parameters', () => {
expect(messageBuilderSegmentKinds('message', [])).not.toContain('node');
});
it('only offers forward nodes at the root of forward actions', () => {
expect(messageBuilderSegmentKinds('forward', [])).toEqual(['node']);
});
it('only offers forward nodes at the root of forward actions', () => {
expect(messageBuilderSegmentKinds('forward', [])).toEqual(['node']);
});
it('locks nested forward content to nodes once a nested node is present', () => {
expect(messageBuilderSegmentKinds('node-content', [newSeg('node')])).toEqual(['node']);
});
it('locks nested forward content to nodes once a nested node is present', () => {
expect(messageBuilderSegmentKinds('node-content', [newSeg('node')])).toEqual(['node']);
});
it('keeps ordinary nested content free of nodes and window shakes', () => {
const kinds = messageBuilderSegmentKinds('node-content', [newSeg('text')]);
expect(kinds).not.toContain('node');
expect(kinds).not.toContain('poke');
});
it('keeps ordinary nested content free of nodes and window shakes', () => {
const kinds = messageBuilderSegmentKinds('node-content', [newSeg('text')]);
expect(kinds).not.toContain('node');
expect(kinds).not.toContain('poke');
});
it('selects the forward-only builder for every forward action', () => {
expect(messageBuilderModeForAction('send_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_group_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_private_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('upload_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('upload_foward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_msg')).toBe('message');
});
it('selects the forward-only builder for every forward action', () => {
expect(messageBuilderModeForAction('send_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_group_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_private_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('upload_forward_msg')).toBe('forward');
expect(messageBuilderModeForAction('upload_foward_msg')).toBe('forward');
expect(messageBuilderModeForAction('send_msg')).toBe('message');
});
});
@@ -1,91 +1,91 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it, vi } from 'vitest';
import {
DEFAULT_EMAIL_BODY,
DEFAULT_WEBHOOK_BODY,
NotificationChannelDialog,
DEFAULT_EMAIL_BODY,
DEFAULT_WEBHOOK_BODY,
NotificationChannelDialog,
} from '../src/components/settings/notification-channel-dialog';
vi.mock('@/contexts/ThemeContext', () => ({
useTheme: () => ({ appearance: { disableMotion: true, reduceMotion: true } }),
useTheme: () => ({ appearance: { disableMotion: true, reduceMotion: true } }),
}));
vi.mock('@/components/interior/modal', () => ({
Modal: ({
title,
description,
children,
footer,
}: {
title: string;
description?: string;
children?: unknown;
footer?: unknown;
}) => (
<div>
<h1>{title}</h1>
{description ? <p>{description}</p> : null}
{children}
<div>{footer}</div>
</div>
),
Modal: ({
title,
description,
children,
footer,
}: {
title: string;
description?: string;
children?: unknown;
footer?: unknown;
}) => (
<div>
<h1>{title}</h1>
{description ? <p>{description}</p> : null}
{children}
<div>{footer}</div>
</div>
),
}));
describe('NotificationChannelDialog', () => {
it('shows webhook fields for a new webhook channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit={false}
initial={{
id: 'channel-1',
name: '',
type: 'webhook',
url: '',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('Webhook URL');
expect(markup).toContain('请求头');
expect(markup).not.toContain('SMTP 主机');
expect(markup).toContain('向该 Webhook POST');
});
it('shows webhook fields for a new webhook channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit={false}
initial={{
id: 'channel-1',
name: '',
type: 'webhook',
url: '',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('Webhook URL');
expect(markup).toContain('请求头');
expect(markup).not.toContain('SMTP 主机');
expect(markup).toContain('向该 Webhook POST');
});
it('shows SMTP fields for an email channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit
initial={{
id: 'ops-mail',
name: '运维邮箱',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 465,
smtpSecure: true,
from: '[email protected]',
to: '[email protected]',
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('SMTP 主机');
expect(markup).toContain('smtp.qq.com');
expect(markup).toContain('发件人');
expect(markup).toContain('收件人');
expect(markup).toContain('主题模板');
expect(markup).toContain('隐式 TLS');
expect(markup).not.toContain('Webhook URL');
expect(markup).toContain('向该邮箱发送');
});
it('shows SMTP fields for an email channel', () => {
const markup = renderToStaticMarkup(
<NotificationChannelDialog
open
onOpenChange={() => undefined}
isEdit
initial={{
id: 'ops-mail',
name: '运维邮箱',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 465,
smtpSecure: true,
from: '[email protected]',
to: '[email protected]',
}}
otherIds={[]}
onSubmit={() => undefined}
/>,
);
expect(markup).toContain('SMTP 主机');
expect(markup).toContain('smtp.qq.com');
expect(markup).toContain('发件人');
expect(markup).toContain('收件人');
expect(markup).toContain('主题模板');
expect(markup).toContain('隐式 TLS');
expect(markup).not.toContain('Webhook URL');
expect(markup).toContain('向该邮箱发送');
});
});
@@ -1,107 +1,110 @@
import { describe, expect, it } from 'vitest';
import {
applyType,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
DEFAULT_WEBHOOK_BODY,
toChannel,
applyType,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
DEFAULT_WEBHOOK_BODY,
toChannel,
} from '../src/components/settings/notification-channel-dialog';
import { notificationChannelType, type NotificationChannel } from '../src/types';
function webhook(over: Partial<NotificationChannel> = {}): NotificationChannel {
return {
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
...over,
};
return {
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
...over,
};
}
describe('notificationChannelType', () => {
it('treats a missing type as webhook', () => {
expect(notificationChannelType({ type: undefined })).toBe('webhook');
expect(notificationChannelType({ type: 'email' })).toBe('email');
});
it('treats a missing type as webhook', () => {
expect(notificationChannelType({ type: undefined })).toBe('webhook');
expect(notificationChannelType({ type: 'email' })).toBe('email');
});
});
describe('applyType', () => {
it('swaps the default webhook body for the email body when switching', () => {
const next = applyType(webhook(), 'email');
expect(next.type).toBe('email');
expect(next.url).toBe('');
expect(next.bodyTemplate).toBe(DEFAULT_EMAIL_BODY);
expect(next.subjectTemplate).toBe(DEFAULT_EMAIL_SUBJECT);
expect(next.smtpPort).toBe(465);
expect(next.smtpSecure).toBe(true);
});
it('swaps the default webhook body for the email body when switching', () => {
const next = applyType(webhook(), 'email');
expect(next.type).toBe('email');
expect(next.url).toBe('');
expect(next.bodyTemplate).toBe(DEFAULT_EMAIL_BODY);
expect(next.subjectTemplate).toBe(DEFAULT_EMAIL_SUBJECT);
expect(next.smtpPort).toBe(465);
expect(next.smtpSecure).toBe(true);
});
it('keeps a custom body when switching to email', () => {
const next = applyType(webhook({ bodyTemplate: 'custom {event}' }), 'email');
expect(next.bodyTemplate).toBe('custom {event}');
});
it('keeps a custom body when switching to email', () => {
const next = applyType(webhook({ bodyTemplate: 'custom {event}' }), 'email');
expect(next.bodyTemplate).toBe('custom {event}');
});
it('drops SMTP fields when switching back to webhook', () => {
const email = applyType(webhook(), 'email');
const back = applyType({ ...email, smtpPass: 'secret' }, 'webhook');
expect(back.type).toBe('webhook');
expect(back).not.toHaveProperty('smtpPass');
expect(back).not.toHaveProperty('smtpHost');
expect(back.bodyTemplate).toBe(DEFAULT_WEBHOOK_BODY);
});
it('drops SMTP fields when switching back to webhook', () => {
const email = applyType(webhook(), 'email');
const back = applyType({ ...email, smtpPass: 'secret' }, 'webhook');
expect(back.type).toBe('webhook');
expect(back).not.toHaveProperty('smtpPass');
expect(back).not.toHaveProperty('smtpHost');
expect(back.bodyTemplate).toBe(DEFAULT_WEBHOOK_BODY);
});
});
describe('toChannel', () => {
it('emits a webhook without email fields and with trimmed headers', () => {
const ch = toChannel(webhook({ headers: { leftover: 'x' } }), [
{ name: ' Authorization ', value: ' Bearer a ' },
{ name: '', value: 'skip' },
]);
expect(ch).toEqual({
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
headers: { Authorization: 'Bearer a' },
it('emits a webhook without email fields and with trimmed headers', () => {
const ch = toChannel(webhook({ headers: { leftover: 'x' } }), [
{ name: ' Authorization ', value: ' Bearer a ' },
{ name: '', value: 'skip' },
]);
expect(ch).toEqual({
id: 'hook',
name: 'Hook',
type: 'webhook',
url: 'https://example.com/hook',
bodyTemplate: DEFAULT_WEBHOOK_BODY,
enabled: true,
headers: { Authorization: 'Bearer a' },
});
});
});
it('emits email fields and an empty url', () => {
const ch = toChannel({
id: ' mail ',
name: ' Ops ',
type: 'email',
url: 'https://ignored',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: ' smtp.qq.com ',
smtpPort: 587,
smtpSecure: false,
smtpUser: ' [email protected] ',
smtpPass: 'secret',
from: ' SnowLuma <[email protected]> ',
to: ' ops@example.com ',
subjectTemplate: ' {event} ',
}, []);
expect(ch).toEqual({
id: 'mail',
name: 'Ops',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 587,
smtpSecure: false,
smtpUser: 'bot@qq.com',
smtpPass: 'secret',
from: 'SnowLuma <[email protected]>',
to: 'ops@example.com',
subjectTemplate: '{event}',
it('emits email fields and an empty url', () => {
const ch = toChannel(
{
id: ' mail ',
name: ' Ops ',
type: 'email',
url: 'https://ignored',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: ' smtp.qq.com ',
smtpPort: 587,
smtpSecure: false,
smtpUser: ' [email protected] ',
smtpPass: 'secret',
from: ' SnowLuma <bot@qq.com> ',
to: ' [email protected] ',
subjectTemplate: ' {event} ',
},
[],
);
expect(ch).toEqual({
id: 'mail',
name: 'Ops',
type: 'email',
url: '',
bodyTemplate: DEFAULT_EMAIL_BODY,
enabled: true,
smtpHost: 'smtp.qq.com',
smtpPort: 587,
smtpSecure: false,
smtpUser: 'bot@qq.com',
smtpPass: 'secret',
from: 'SnowLuma <[email protected]>',
to: '[email protected]',
subjectTemplate: '{event}',
});
});
});
});
+27 -25
View File
@@ -2,33 +2,35 @@ import { describe, expect, it, vi } from 'vitest';
import { onboardingExecution } from '../src/lib/onboarding-actions';
describe('developer onboarding rehearsal', () => {
it('completes consent and password steps without writing persistent state', async () => {
const acceptAgreements = vi.fn(async () => ({ success: true }));
const changePassword = vi.fn(async () => ({ success: true }));
const execution = onboardingExecution(true, {
acceptAgreements,
changePassword,
it('completes consent and password steps without writing persistent state', async () => {
const acceptAgreements = vi.fn(async () => ({ success: true }));
const changePassword = vi.fn(async () => ({ success: true }));
const execution = onboardingExecution(true, {
acceptAgreements,
changePassword,
});
expect(execution.passwordMode).toBe('rehearsal');
await expect(execution.actions.acceptAgreements()).resolves.toEqual({ success: true });
await expect(execution.actions.changePassword('old', 'new')).resolves.toEqual({
success: true,
});
expect(acceptAgreements).not.toHaveBeenCalled();
expect(changePassword).not.toHaveBeenCalled();
});
expect(execution.passwordMode).toBe('rehearsal');
await expect(execution.actions.acceptAgreements()).resolves.toEqual({ success: true });
await expect(execution.actions.changePassword('old', 'new')).resolves.toEqual({ success: true });
expect(acceptAgreements).not.toHaveBeenCalled();
expect(changePassword).not.toHaveBeenCalled();
});
it('keeps real onboarding wired to persistent actions', async () => {
const acceptAgreements = vi.fn(async () => ({ success: true }));
const changePassword = vi.fn(async () => ({ success: true }));
const execution = onboardingExecution(false, {
acceptAgreements,
changePassword,
});
it('keeps real onboarding wired to persistent actions', async () => {
const acceptAgreements = vi.fn(async () => ({ success: true }));
const changePassword = vi.fn(async () => ({ success: true }));
const execution = onboardingExecution(false, {
acceptAgreements,
changePassword,
expect(execution.passwordMode).toBe('change');
await execution.actions.acceptAgreements();
await execution.actions.changePassword('old', 'new');
expect(acceptAgreements).toHaveBeenCalledOnce();
expect(changePassword).toHaveBeenCalledWith('old', 'new');
});
expect(execution.passwordMode).toBe('change');
await execution.actions.acceptAgreements();
await execution.actions.changePassword('old', 'new');
expect(acceptAgreements).toHaveBeenCalledOnce();
expect(changePassword).toHaveBeenCalledWith('old', 'new');
});
});
@@ -1,44 +1,58 @@
import { describe, expect, it } from 'vitest';
import {
browserPath,
DEVELOPER_ONBOARDING_RETURN_KEY,
developerOnboardingReturnPath,
isDeveloperOnboardingLocation,
browserPath,
DEVELOPER_ONBOARDING_RETURN_KEY,
developerOnboardingReturnPath,
isDeveloperOnboardingLocation,
} from '../src/lib/onboarding-navigation';
describe('developer onboarding navigation', () => {
it('recognizes only the dedicated developer replay URL', () => {
expect(isDeveloperOnboardingLocation({
pathname: '/onboarding',
search: '?mode=developer',
})).toBe(true);
expect(isDeveloperOnboardingLocation({ pathname: '/onboarding', search: '' })).toBe(false);
expect(isDeveloperOnboardingLocation({
pathname: '/settings',
search: '?mode=developer',
})).toBe(false);
});
it('recognizes only the dedicated developer replay URL', () => {
expect(
isDeveloperOnboardingLocation({
pathname: '/onboarding',
search: '?mode=developer',
}),
).toBe(true);
expect(isDeveloperOnboardingLocation({ pathname: '/onboarding', search: '' })).toBe(false);
expect(
isDeveloperOnboardingLocation({
pathname: '/settings',
search: '?mode=developer',
}),
).toBe(false);
});
it('preserves the complete local return path', () => {
expect(browserPath({
pathname: '/settings',
search: '?tab=developer',
hash: '#tools',
})).toBe('/settings?tab=developer#tools');
});
it('preserves the complete local return path', () => {
expect(
browserPath({
pathname: '/settings',
search: '?tab=developer',
hash: '#tools',
}),
).toBe('/settings?tab=developer#tools');
});
it('accepts only local non-onboarding return paths from history state', () => {
expect(developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '/settings?tab=developer',
})).toBe('/settings?tab=developer');
expect(developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: 'https://example.com',
})).toBeNull();
expect(developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '//example.com',
})).toBeNull();
expect(developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '/onboarding?mode=developer',
})).toBeNull();
});
it('accepts only local non-onboarding return paths from history state', () => {
expect(
developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '/settings?tab=developer',
}),
).toBe('/settings?tab=developer');
expect(
developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: 'https://example.com',
}),
).toBeNull();
expect(
developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '//example.com',
}),
).toBeNull();
expect(
developerOnboardingReturnPath({
[DEVELOPER_ONBOARDING_RETURN_KEY]: '/onboarding?mode=developer',
}),
).toBeNull();
});
});
+58 -52
View File
@@ -2,67 +2,73 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { WizardSteps } from '../src/components/interior/wizard-steps';
import {
advanceOnboardingStep,
buildRequiredOnboardingStepIds,
advanceOnboardingStep,
buildRequiredOnboardingStepIds,
} from '../src/components/pages/onboarding-steps';
describe('buildRequiredOnboardingStepIds', () => {
it('keeps legal consent before password setup when both are required', () => {
expect(buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
})).toEqual(['agreements', 'password']);
});
it('omits steps already satisfied by backend environment-aware policy', () => {
expect(buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: false,
})).toEqual([]);
expect(buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: true,
})).toEqual(['password']);
});
it('completes consent and password in order before releasing onboarding', () => {
const steps = buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
it('keeps legal consent before password setup when both are required', () => {
expect(
buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
}),
).toEqual(['agreements', 'password']);
});
expect(advanceOnboardingStep(steps, 'agreements')).toEqual({
nextIndex: 1,
complete: false,
it('omits steps already satisfied by backend environment-aware policy', () => {
expect(
buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: false,
}),
).toEqual([]);
expect(
buildRequiredOnboardingStepIds({
needsConsent: false,
mustChangePassword: true,
}),
).toEqual(['password']);
});
expect(advanceOnboardingStep(steps, 'password')).toEqual({
nextIndex: null,
complete: true,
it('completes consent and password in order before releasing onboarding', () => {
const steps = buildRequiredOnboardingStepIds({
needsConsent: true,
mustChangePassword: true,
});
expect(advanceOnboardingStep(steps, 'agreements')).toEqual({
nextIndex: 1,
complete: false,
});
expect(advanceOnboardingStep(steps, 'password')).toEqual({
nextIndex: null,
complete: true,
});
});
});
});
describe('WizardSteps onboarding policy', () => {
it('only renders a skip action for a step configured as skippable', () => {
const skippable = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'optional', label: '可选步骤', content: <p>可选内容</p>, canSkip: true },
{ id: 'required', label: '必要步骤', content: <p>必要内容</p> },
]}
skipLabel="跳过"
/>,
);
const required = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'required', label: '必要步骤', content: <p>必要内容</p>, canSkip: false },
]}
skipLabel="跳过"
/>,
);
it('only renders a skip action for a step configured as skippable', () => {
const skippable = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'optional', label: '可选步骤', content: <p>可选内容</p>, canSkip: true },
{ id: 'required', label: '必要步骤', content: <p>必要内容</p> },
]}
skipLabel="跳过"
/>,
);
const required = renderToStaticMarkup(
<WizardSteps
steps={[
{ id: 'required', label: '必要步骤', content: <p>必要内容</p>, canSkip: false },
]}
skipLabel="跳过"
/>,
);
expect(skippable).toContain('跳过');
expect(required).not.toContain('跳过');
});
expect(skippable).toContain('跳过');
expect(required).not.toContain('跳过');
});
});
@@ -3,44 +3,44 @@ import { accessTokenFeedback } from '../src/lib/access-token-feedback';
import { NETWORK_TABS, generateAccessToken } from '../src/components/config/defaults';
describe('OneBot access token editor policy', () => {
it('creates inbound endpoints on loopback with generated tokens', () => {
const http = NETWORK_TABS.httpServers.defaultEntry(1);
const ws = NETWORK_TABS.wsServers.defaultEntry(1);
it('creates inbound endpoints on loopback with generated tokens', () => {
const http = NETWORK_TABS.httpServers.defaultEntry(1);
const ws = NETWORK_TABS.wsServers.defaultEntry(1);
expect(http.host).toBe('127.0.0.1');
expect(ws.host).toBe('127.0.0.1');
expect(http.accessToken).not.toBe(ws.accessToken);
expect(accessTokenFeedback(http.accessToken ?? '', [], false).valid).toBe(true);
expect(accessTokenFeedback(ws.accessToken ?? '', [], false).valid).toBe(true);
});
it('generates a fresh strong token on demand', () => {
const first = generateAccessToken();
const second = generateAccessToken();
expect(first).not.toBe(second);
expect(accessTokenFeedback(first, ['SnowLuma', 'OneBot'], false).valid).toBe(true);
});
it('gives one actionable message for short and guessable values', () => {
expect(accessTokenFeedback('short', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
expect(http.host).toBe('127.0.0.1');
expect(ws.host).toBe('127.0.0.1');
expect(http.accessToken).not.toBe(ws.accessToken);
expect(accessTokenFeedback(http.accessToken ?? '', [], false).valid).toBe(true);
expect(accessTokenFeedback(ws.accessToken ?? '', [], false).valid).toBe(true);
});
expect(accessTokenFeedback('SnowLumaSnowLuma', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
});
});
it('only permits an empty inbound token in a trusted bind or local-page context', () => {
expect(accessTokenFeedback('', [], false)).toEqual({
valid: false,
tone: 'error',
message: '未绑定本机地址时,远程访问必须填写令牌;请生成令牌或将主机改为 127.0.0.1。',
it('generates a fresh strong token on demand', () => {
const first = generateAccessToken();
const second = generateAccessToken();
expect(first).not.toBe(second);
expect(accessTokenFeedback(first, ['SnowLuma', 'OneBot'], false).valid).toBe(true);
});
it('gives one actionable message for short and guessable values', () => {
expect(accessTokenFeedback('short', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
});
expect(accessTokenFeedback('SnowLumaSnowLuma', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
});
});
it('only permits an empty inbound token in a trusted bind or local-page context', () => {
expect(accessTokenFeedback('', [], false)).toEqual({
valid: false,
tone: 'error',
message: '未绑定本机地址时,远程访问必须填写令牌;请生成令牌或将主机改为 127.0.0.1。',
});
expect(accessTokenFeedback('', [], true)).toMatchObject({ valid: true, tone: 'warning' });
});
expect(accessTokenFeedback('', [], true)).toMatchObject({ valid: true, tone: 'warning' });
});
});
+10 -8
View File
@@ -2,13 +2,15 @@ import { describe, expect, it } from 'vitest';
import { normalizeOneBotConfig } from '../src/lib/onebot-config';
describe('normalizeOneBotConfig history sync', () => {
it('defaults older payloads to disabled', () => {
expect(normalizeOneBotConfig({}).historySync).toEqual({ enabled: false });
});
it('defaults older payloads to disabled', () => {
expect(normalizeOneBotConfig({}).historySync).toEqual({ enabled: false });
});
it('preserves an explicit per-account opt-in', () => {
expect(normalizeOneBotConfig({
historySync: { enabled: true },
}).historySync).toEqual({ enabled: true });
});
it('preserves an explicit per-account opt-in', () => {
expect(
normalizeOneBotConfig({
historySync: { enabled: true },
}).historySync,
).toEqual({ enabled: true });
});
});
+24 -24
View File
@@ -3,29 +3,29 @@ import { describe, expect, it } from 'vitest';
import { OtpInput } from '../src/components/interior/otp-input';
describe('OtpInput official error/hint contract', () => {
it('shows the hint while error is false', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error={false}
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).not.toContain('验证码不正确,改错的那一位即可。');
});
it('shows the hint while error is false', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error={false}
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('可以把完整验证码粘贴到任意一格。');
expect(markup).not.toContain('验证码不正确,改错的那一位即可。');
});
it('swaps to the error message when error is true', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('验证码不正确,改错的那一位即可。');
expect(markup).toContain('aria-invalid="true"');
});
it('swaps to the error message when error is true', () => {
const markup = renderToStaticMarkup(
<OtpInput
label="验证码"
hint="可以把完整验证码粘贴到任意一格。"
error
errorMessage="验证码不正确,改错的那一位即可。"
/>,
);
expect(markup).toContain('验证码不正确,改错的那一位即可。');
expect(markup).toContain('aria-invalid="true"');
});
});
+102 -97
View File
@@ -2,121 +2,126 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { FloatingLabelInput } from '../src/components/interior/floating-label';
import { InlineValidation } from '../src/components/interior/inline-validation';
import {
PasswordStrength,
type PasswordRule,
} from '../src/components/interior/password-strength';
import { PasswordStrength, type PasswordRule } from '../src/components/interior/password-strength';
import { passwordRequirementHint } from '../src/components/pages/change-password-form';
const RULES: readonly PasswordRule[] = [
{ id: 'length', label: '长度不少于 10 位', test: (value) => value.length >= 10 },
{ id: 'upper', label: '包含大写字母', test: (value) => /[A-Z]/.test(value) },
{ id: 'length', label: '长度不少于 10 位', test: (value) => value.length >= 10 },
{ id: 'upper', label: '包含大写字母', test: (value) => /[A-Z]/.test(value) },
];
describe('password input guidance', () => {
it('renders an accessible floating password label', () => {
const markup = renderToStaticMarkup(
<FloatingLabelInput
id="password"
label="新密码"
type="password"
value=""
required
onChange={() => {}}
/>,
);
it('renders an accessible floating password label', () => {
const markup = renderToStaticMarkup(
<FloatingLabelInput
id="password"
label="新密码"
type="password"
value=""
required
onChange={() => {}}
/>,
);
expect(markup).toContain('id="password"');
expect(markup).toContain('for="password"');
expect(markup).toContain('新密码');
expect(markup).toContain('aria-required="true"');
});
expect(markup).toContain('id="password"');
expect(markup).toContain('for="password"');
expect(markup).toContain('新密码');
expect(markup).toContain('aria-required="true"');
});
it('keeps the strength details out of the tree while hidden', () => {
const markup = renderToStaticMarkup(
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible={false} />,
);
it('keeps the strength details out of the tree while hidden', () => {
const markup = renderToStaticMarkup(
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible={false} />,
);
expect(markup).not.toContain('role="meter"');
expect(markup).not.toContain('长度不少于 10 位');
});
expect(markup).not.toContain('role="meter"');
expect(markup).not.toContain('长度不少于 10 位');
});
it('shows the evaluated strength details while visible', () => {
const markup = renderToStaticMarkup(
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible />,
);
it('shows the evaluated strength details while visible', () => {
const markup = renderToStaticMarkup(
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible />,
);
expect(markup).toContain('role="meter"');
expect(markup).toContain('aria-valuenow="2"');
expect(markup).toContain('长度不少于 10 位');
expect(markup).toContain('包含大写字母');
});
expect(markup).toContain('role="meter"');
expect(markup).toContain('aria-valuenow="2"');
expect(markup).toContain('长度不少于 10 位');
expect(markup).toContain('包含大写字母');
});
it('renders inline validation with its hint and status channel', () => {
const markup = renderToStaticMarkup(
<InlineValidation
id="confirm-password"
label="确认新密码"
value=""
onChange={() => {}}
validate={(value) => value ? null : '请再次输入新密码'}
hint="需要与新密码完全一致"
/>,
);
it('renders inline validation with its hint and status channel', () => {
const markup = renderToStaticMarkup(
<InlineValidation
id="confirm-password"
label="确认新密码"
value=""
onChange={() => {}}
validate={(value) => (value ? null : '请再次输入新密码')}
hint="需要与新密码完全一致"
/>,
);
expect(markup).toContain('确认新密码');
expect(markup).toContain('需要与新密码完全一致');
expect(markup).toContain('role="status"');
});
expect(markup).toContain('确认新密码');
expect(markup).toContain('需要与新密码完全一致');
expect(markup).toContain('role="status"');
});
});
describe('passwordRequirementHint', () => {
const rules = [
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'upper', label: '包含大写字母', ok: true },
];
const rules = [
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'upper', label: '包含大写字母', ok: true },
];
it('hides unmet-rule copy while the animated list is open', () => {
expect(passwordRequirementHint({
focused: true,
value: 'short',
checked: true,
valid: false,
rules,
checkError: '',
})).toBeNull();
});
it('hides unmet-rule copy while the animated list is open', () => {
expect(
passwordRequirementHint({
focused: true,
value: 'short',
checked: true,
valid: false,
rules,
checkError: '',
}),
).toBeNull();
});
it('lists unmet rules after the new-password field loses focus', () => {
expect(passwordRequirementHint({
focused: false,
value: 'short',
checked: true,
valid: false,
rules,
checkError: '',
})).toBe('仍需满足:长度不少于 10 位');
});
it('lists unmet rules after the new-password field loses focus', () => {
expect(
passwordRequirementHint({
focused: false,
value: 'short',
checked: true,
valid: false,
rules,
checkError: '',
}),
).toBe('仍需满足:长度不少于 10 位');
});
it('does not invent unmet rules while strength is still being checked', () => {
expect(passwordRequirementHint({
focused: false,
value: 'short',
checked: false,
valid: false,
rules,
checkError: '',
})).toBeNull();
});
it('does not invent unmet rules while strength is still being checked', () => {
expect(
passwordRequirementHint({
focused: false,
value: 'short',
checked: false,
valid: false,
rules,
checkError: '',
}),
).toBeNull();
});
it('surfaces a failed strength check after blur', () => {
expect(passwordRequirementHint({
focused: false,
value: 'short',
checked: false,
valid: false,
rules,
checkError: '网络错误',
})).toBe('密码强度校验失败:网络错误');
});
it('surfaces a failed strength check after blur', () => {
expect(
passwordRequirementHint({
focused: false,
value: 'short',
checked: false,
valid: false,
rules,
checkError: '网络错误',
}),
).toBe('密码强度校验失败:网络错误');
});
});
@@ -2,72 +2,99 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'test-token',
save: () => undefined,
load: () => 'test-token',
save: () => undefined,
};
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllGlobals();
});
describe('password strength API client', () => {
it('returns the server-owned rule evaluation', async () => {
const rules = [
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
];
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
rules,
valid: true,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
it('returns the server-owned rule evaluation', async () => {
const rules = [
{ id: 'length', label: '长度不少于 10 位', ok: true },
{ id: 'no-space', label: '不包含空格', ok: true },
];
const fetchMock = vi.fn(
async () =>
new Response(
JSON.stringify({
rules,
valid: true,
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('Strong-password')).resolves.toEqual({
rules,
valid: true,
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('Strong-password')).resolves.toEqual({
rules,
valid: true,
});
expect(fetchMock).toHaveBeenCalledWith(
'/api/auth/check-strength',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Strong-password' }),
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
signal: expect.any(AbortSignal),
}),
);
});
expect(fetchMock).toHaveBeenCalledWith('/api/auth/check-strength', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ password: 'Strong-password' }),
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
signal: expect.any(AbortSignal),
}));
});
it('rejects malformed responses instead of silently disabling the form', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
valid: false,
}), {
status: 200,
headers: { 'content-type': 'application/json' },
})));
it('rejects malformed responses instead of silently disabling the form', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
JSON.stringify({
valid: false,
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
),
),
);
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
status: 502,
message: '密码强度接口返回了无效响应',
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
status: 502,
message: '密码强度接口返回了无效响应',
});
});
});
it('propagates request failures for observable inline validation', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
message: 'strength service unavailable',
}), {
status: 503,
headers: { 'content-type': 'application/json' },
})));
it('propagates request failures for observable inline validation', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
JSON.stringify({
message: 'strength service unavailable',
}),
{
status: 503,
headers: { 'content-type': 'application/json' },
},
),
),
);
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
status: 503,
message: 'strength service unavailable',
const client = createApiClient({ tokenStore });
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
status: 503,
message: 'strength service unavailable',
});
});
});
});
+50 -53
View File
@@ -1,67 +1,64 @@
import { describe, expect, it, vi } from 'vitest';
import {
selectServerLogLevel,
TRACE_CONFIRMATION_WARNINGS,
} from '../src/lib/server-log-level';
import { selectServerLogLevel, TRACE_CONFIRMATION_WARNINGS } from '../src/lib/server-log-level';
describe('selectServerLogLevel', () => {
it('keeps every required warning in the TRACE confirmation', () => {
expect(TRACE_CONFIRMATION_WARNINGS).toEqual([
'TRACE 会产生非常大量的数据。',
'TRACE 可能包含未经脱敏的隐私数据和凭据。',
'TRACE 不适合长时间开启。',
'TRACE 仅用于小规模问题复现和 bug 反馈。',
]);
});
it('requires confirmation before entering TRACE from a normal level', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
selectServerLogLevel({
currentLevel: 'info',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
it('keeps every required warning in the TRACE confirmation', () => {
expect(TRACE_CONFIRMATION_WARNINGS).toEqual([
'TRACE 会产生非常大量的数据。',
'TRACE 可能包含未经脱敏的隐私数据和凭据。',
'TRACE 不适合长时间开启。',
'TRACE 仅用于小规模问题复现和 bug 反馈。',
]);
});
expect(requestTraceConfirmation).toHaveBeenCalledOnce();
expect(applyLevel).not.toHaveBeenCalled();
});
it('requires confirmation before entering TRACE from a normal level', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
it('applies ordinary level transitions immediately', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
selectServerLogLevel({
currentLevel: 'info',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
});
selectServerLogLevel({
currentLevel: 'trace',
nextLevel: 'info',
applyLevel,
requestTraceConfirmation,
expect(requestTraceConfirmation).toHaveBeenCalledOnce();
expect(applyLevel).not.toHaveBeenCalled();
});
expect(applyLevel).toHaveBeenCalledExactlyOnceWith('info');
expect(requestTraceConfirmation).not.toHaveBeenCalled();
});
it('applies ordinary level transitions immediately', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
it('requires confirmation each time TRACE is re-entered', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
selectServerLogLevel({
currentLevel: 'trace',
nextLevel: 'info',
applyLevel,
requestTraceConfirmation,
});
selectServerLogLevel({
currentLevel: 'debug',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
});
selectServerLogLevel({
currentLevel: 'info',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
expect(applyLevel).toHaveBeenCalledExactlyOnceWith('info');
expect(requestTraceConfirmation).not.toHaveBeenCalled();
});
expect(requestTraceConfirmation).toHaveBeenCalledTimes(2);
expect(applyLevel).not.toHaveBeenCalled();
});
it('requires confirmation each time TRACE is re-entered', () => {
const applyLevel = vi.fn();
const requestTraceConfirmation = vi.fn();
selectServerLogLevel({
currentLevel: 'debug',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
});
selectServerLogLevel({
currentLevel: 'info',
nextLevel: 'trace',
applyLevel,
requestTraceConfirmation,
});
expect(requestTraceConfirmation).toHaveBeenCalledTimes(2);
expect(applyLevel).not.toHaveBeenCalled();
});
});
+21 -21
View File
@@ -3,28 +3,28 @@ import { describe, expect, it } from 'vitest';
import { SkeletonSwap } from '../src/components/interior/skeleton-swap';
describe('SkeletonSwap', () => {
it('reserves the requested space without painting a skeleton immediately', () => {
const html = renderToStaticMarkup(
<SkeletonSwap ready={false} reserve={84} lines={4} label="测试内容">
<div>尚未就绪</div>
</SkeletonSwap>,
);
it('reserves the requested space without painting a skeleton immediately', () => {
const html = renderToStaticMarkup(
<SkeletonSwap ready={false} reserve={84} lines={4} label="测试内容">
<div>尚未就绪</div>
</SkeletonSwap>,
);
expect(html).toContain('aria-busy="true"');
expect(html).toContain('height:84px');
expect(html).toContain('尚未就绪');
expect(html).not.toContain('aria-hidden="true"');
});
expect(html).toContain('aria-busy="true"');
expect(html).toContain('height:84px');
expect(html).toContain('尚未就绪');
expect(html).not.toContain('aria-hidden="true"');
});
it('exposes ready content without a loading announcement', () => {
const html = renderToStaticMarkup(
<SkeletonSwap ready label="测试内容">
<div>内容已加载</div>
</SkeletonSwap>,
);
it('exposes ready content without a loading announcement', () => {
const html = renderToStaticMarkup(
<SkeletonSwap ready label="测试内容">
<div>内容已加载</div>
</SkeletonSwap>,
);
expect(html).toContain('aria-busy="false"');
expect(html).toContain('内容已加载');
expect(html).toContain('测试内容 loaded');
});
expect(html).toContain('aria-busy="false"');
expect(html).toContain('内容已加载');
expect(html).toContain('测试内容 loaded');
});
});
+114 -93
View File
@@ -2,109 +2,130 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'test-token',
save: () => undefined,
load: () => 'test-token',
save: () => undefined,
};
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllGlobals();
});
describe('storage API client', () => {
it('reads the authenticated storage overview', async () => {
const payload = {
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
envOverrides: [],
},
snapshot: {
logs: {
state: 'healthy',
totalBytes: 0,
maxTotalBytes: 1024 * 1024 * 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 0, fileCount: 0, activeItemCount: 0 },
accounts: [],
totals: { logsBytes: 0, temporaryBytes: 0, accountDataBytes: 0, managedBytes: 0 },
},
lastCleanup: null,
};
const fetchMock = vi.fn(async () => new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
it('reads the authenticated storage overview', async () => {
const payload = {
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
envOverrides: [],
},
snapshot: {
logs: {
state: 'healthy',
totalBytes: 0,
maxTotalBytes: 1024 * 1024 * 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 0, fileCount: 0, activeItemCount: 0 },
accounts: [],
totals: { logsBytes: 0, temporaryBytes: 0, accountDataBytes: 0, managedBytes: 0 },
},
lastCleanup: null,
};
const fetchMock = vi.fn(
async () =>
new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.storage.get()).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', expect.objectContaining({
headers: { Authorization: 'Bearer test-token' },
signal: expect.any(AbortSignal),
}));
});
const client = createApiClient({ tokenStore });
await expect(client.storage.get()).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith(
'/api/system/storage',
expect.objectContaining({
headers: { Authorization: 'Bearer test-token' },
signal: expect.any(AbortSignal),
}),
);
});
it('posts a partial log-settings patch', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
success: true,
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
envOverrides: [],
},
status: { state: 'healthy' },
snapshot: {},
}), { status: 200, headers: { 'content-type': 'application/json' } }));
vi.stubGlobal('fetch', fetchMock);
it('posts a partial log-settings patch', async () => {
const fetchMock = vi.fn(
async () =>
new Response(
JSON.stringify({
success: true,
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
envOverrides: [],
},
status: { state: 'healthy' },
snapshot: {},
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await client.storage.saveSettings({ logRetainDays: 0 });
const client = createApiClient({ tokenStore });
await client.storage.saveSettings({ logRetainDays: 0 });
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ logRetainDays: 0 }),
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
signal: expect.any(AbortSignal),
}));
});
expect(fetchMock).toHaveBeenCalledWith(
'/api/system/storage/settings',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ logRetainDays: 0 }),
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
signal: expect.any(AbortSignal),
}),
);
});
it('returns a structured partial cleanup result from an HTTP 500 response', async () => {
const payload = {
success: false,
message: '部分文件清理失败,请检查失败明细',
scope: 'temporary',
cleanup: {
deletedFiles: 1,
freedBytes: 5,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
snapshot: {},
lastCleanup: {
at: '2026-07-24T04:00:00.000Z',
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
};
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), {
status: 500,
headers: { 'content-type': 'application/json' },
})));
it('returns a structured partial cleanup result from an HTTP 500 response', async () => {
const payload = {
success: false,
message: '部分文件清理失败,请检查失败明细',
scope: 'temporary',
cleanup: {
deletedFiles: 1,
freedBytes: 5,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
snapshot: {},
lastCleanup: {
at: '2026-07-24T04:00:00.000Z',
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
};
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(JSON.stringify(payload), {
status: 500,
headers: { 'content-type': 'application/json' },
}),
),
);
const client = createApiClient({ tokenStore });
await expect(client.storage.cleanup({ scope: 'temporary' })).resolves.toEqual(payload);
});
const client = createApiClient({ tokenStore });
await expect(client.storage.cleanup({ scope: 'temporary' })).resolves.toEqual(payload);
});
});
@@ -1,50 +1,58 @@
import { describe, expect, it } from 'vitest';
import {
buildLogSettingsPatch,
formatBytes,
isAllAccountsConfirmation,
logStoragePresentation,
buildLogSettingsPatch,
formatBytes,
isAllAccountsConfirmation,
logStoragePresentation,
} from '../src/lib/storage-presentation';
describe('storage presentation helpers', () => {
it('omits environment-locked and unchanged fields from a settings patch', () => {
expect(buildLogSettingsPatch(
{ logMaxTotalMb: 2048, logRetainDays: 0, logPerUin: true },
{ logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
['logMaxTotalMb'],
)).toEqual({
logRetainDays: 0,
logPerUin: true,
it('omits environment-locked and unchanged fields from a settings patch', () => {
expect(
buildLogSettingsPatch(
{ logMaxTotalMb: 2048, logRetainDays: 0, logPerUin: true },
{ logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
['logMaxTotalMb'],
),
).toEqual({
logRetainDays: 0,
logPerUin: true,
});
});
});
it('prioritizes degraded state over capacity percentage and warns at 80 percent', () => {
expect(logStoragePresentation({
state: 'degraded',
totalBytes: 10,
maxTotalBytes: 100,
})).toMatchObject({ label: '磁盘写入已暂停', tone: 'danger', percent: 10 });
expect(logStoragePresentation({
state: 'healthy',
totalBytes: 80,
maxTotalBytes: 100,
})).toMatchObject({ label: '接近上限', tone: 'warning', percent: 80 });
expect(logStoragePresentation({
state: 'healthy',
totalBytes: 20,
maxTotalBytes: 100,
})).toMatchObject({ label: '正常', tone: 'success', percent: 20 });
});
it('prioritizes degraded state over capacity percentage and warns at 80 percent', () => {
expect(
logStoragePresentation({
state: 'degraded',
totalBytes: 10,
maxTotalBytes: 100,
}),
).toMatchObject({ label: '磁盘写入已暂停', tone: 'danger', percent: 10 });
expect(
logStoragePresentation({
state: 'healthy',
totalBytes: 80,
maxTotalBytes: 100,
}),
).toMatchObject({ label: '接近上限', tone: 'warning', percent: 80 });
expect(
logStoragePresentation({
state: 'healthy',
totalBytes: 20,
maxTotalBytes: 100,
}),
).toMatchObject({ label: '正常', tone: 'success', percent: 20 });
});
it('formats byte counts without exposing implementation units', () => {
expect(formatBytes(0)).toBe('0 B');
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(1024 * 1024)).toBe('1 MB');
});
it('formats byte counts without exposing implementation units', () => {
expect(formatBytes(0)).toBe('0 B');
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(1024 * 1024)).toBe('1 MB');
});
it('requires the exact all-account confirmation phrase', () => {
expect(isAllAccountsConfirmation('清理全部账号')).toBe(true);
expect(isAllAccountsConfirmation(' 清理全部账号 ')).toBe(false);
expect(isAllAccountsConfirmation('确认')).toBe(false);
});
it('requires the exact all-account confirmation phrase', () => {
expect(isAllAccountsConfirmation('清理全部账号')).toBe(true);
expect(isAllAccountsConfirmation(' 清理全部账号 ')).toBe(false);
expect(isAllAccountsConfirmation('确认')).toBe(false);
});
});
@@ -2,11 +2,11 @@ import { describe, expect, it } from 'vitest';
import { parseSecondFactor } from '../src/lib/totp-second-factor';
describe('parseSecondFactor', () => {
it('treats a 6-digit code as TOTP, ignoring spaces', () => {
expect(parseSecondFactor('287 082')).toEqual({ totp: '287082' });
});
it('treats a 6-digit code as TOTP, ignoring spaces', () => {
expect(parseSecondFactor('287 082')).toEqual({ totp: '287082' });
});
it('treats a recovery code as a recovery code', () => {
expect(parseSecondFactor('AB3D-K7MQ')).toEqual({ recoveryCode: 'AB3D-K7MQ' });
});
it('treats a recovery code as a recovery code', () => {
expect(parseSecondFactor('AB3D-K7MQ')).toEqual({ recoveryCode: 'AB3D-K7MQ' });
});
});
+41 -41
View File
@@ -1,51 +1,51 @@
import { describe, expect, it } from 'vitest';
import {
allowEmptyInboundAccessToken,
isLoopbackHostname,
shouldWarnAboutInsecureRemoteAccess,
allowEmptyInboundAccessToken,
isLoopbackHostname,
shouldWarnAboutInsecureRemoteAccess,
} from '../src/lib/transport-security';
describe('WebUI transport security notice', () => {
it.each([
'localhost',
'dashboard.localhost',
'127.0.0.1',
'127.42.1.9',
'[::1]',
'0:0:0:0:0:0:0:1',
'::ffff:127.0.0.1',
])('recognizes %s as a loopback browser hostname', (hostname) => {
expect(isLoopbackHostname(hostname)).toBe(true);
});
it.each([
'localhost',
'dashboard.localhost',
'127.0.0.1',
'127.42.1.9',
'[::1]',
'0:0:0:0:0:0:0:1',
'::ffff:127.0.0.1',
])('recognizes %s as a loopback browser hostname', (hostname) => {
expect(isLoopbackHostname(hostname)).toBe(true);
});
it.each([
'0.0.0.0',
'192.168.1.20',
'10.0.0.8',
'snowluma.example.com',
'::ffff:192.168.1.20',
])('does not treat %s as loopback', (hostname) => {
expect(isLoopbackHostname(hostname)).toBe(false);
});
it.each(['0.0.0.0', '192.168.1.20', '10.0.0.8', 'snowluma.example.com', '::ffff:192.168.1.20'])(
'does not treat %s as loopback',
(hostname) => {
expect(isLoopbackHostname(hostname)).toBe(false);
},
);
it('allows an empty inbound token when the bind host is loopback, even from a remote WebUI', () => {
expect(allowEmptyInboundAccessToken('192.168.1.20', '127.0.0.1')).toBe(true);
expect(allowEmptyInboundAccessToken('panel.example.com', 'localhost')).toBe(true);
expect(allowEmptyInboundAccessToken('192.168.1.20', '0.0.0.0')).toBe(false);
expect(allowEmptyInboundAccessToken('192.168.1.20', '')).toBe(false);
});
it('allows an empty inbound token when the bind host is loopback, even from a remote WebUI', () => {
expect(allowEmptyInboundAccessToken('192.168.1.20', '127.0.0.1')).toBe(true);
expect(allowEmptyInboundAccessToken('panel.example.com', 'localhost')).toBe(true);
expect(allowEmptyInboundAccessToken('192.168.1.20', '0.0.0.0')).toBe(false);
expect(allowEmptyInboundAccessToken('192.168.1.20', '')).toBe(false);
});
it('still allows an empty inbound token when the WebUI itself is opened on loopback', () => {
expect(allowEmptyInboundAccessToken('127.0.0.1', '0.0.0.0')).toBe(true);
expect(allowEmptyInboundAccessToken('localhost', undefined)).toBe(true);
});
it('still allows an empty inbound token when the WebUI itself is opened on loopback', () => {
expect(allowEmptyInboundAccessToken('127.0.0.1', '0.0.0.0')).toBe(true);
expect(allowEmptyInboundAccessToken('localhost', undefined)).toBe(true);
});
it('warns only when a non-loopback page is accessed without HTTPS', () => {
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '192.168.1.20' }))
.toBe(true);
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'https:', hostname: '192.168.1.20' }))
.toBe(false);
expect(shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '127.0.0.1' }))
.toBe(false);
});
it('warns only when a non-loopback page is accessed without HTTPS', () => {
expect(
shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '192.168.1.20' }),
).toBe(true);
expect(
shouldWarnAboutInsecureRemoteAccess({ protocol: 'https:', hostname: '192.168.1.20' }),
).toBe(false);
expect(
shouldWarnAboutInsecureRemoteAccess({ protocol: 'http:', hostname: '127.0.0.1' }),
).toBe(false);
});
});