test(common): cover hex/log-summary/request-context; fix Utf8Validator dead code (#84, #85)

Reimplements PR #86 independently (author abandoned it after change-requests),
with the review feedback applied — the original tests asserted behavior the
code never had.

#84 — add @snowluma/common unit tests:
- hex: toHex/toHexUpper/hexPreview boundary + fromHex round-trip & odd-length throw
- log-summary: summarizeParams (top-level primitive is String()'d WITHOUT quotes;
  fields quoted; nested collapsed; total cap) and renderParamsVerbose (redaction,
  long-string marker is the Unicode ellipsis '…<N B>' not ASCII '...', circular guard)
- request-context: nextRequestId monotonic; runWithRequestId sync/async + nested scopes
- root scripts test:common/test:all/coverage; coverage/ gitignored

#85 — Utf8Validator: the second surrogate check was unreachable (within the
0x80–0xBF continuation-byte guard, 'b & 0x20' is true iff 'b >= 0xA0'); merge to
one check. No behavior change.

common suite green (26 tests).
This commit is contained in:
DrSmoothl committed 2026-06-22 22:53:21 +08:00
1 parent b918450483
commit 2b3d1c67c2
6 files changed
+132 -4

No files matched your search

+3
View File
@@ -15,3 +15,6 @@ logs/
# macOS metadata
.DS_Store
# test coverage output
coverage/
+3
View File
@@ -16,6 +16,9 @@
"dev:web": "pnpm --filter webui dev",
"test": "pnpm --filter @snowluma/core test",
"test:watch": "pnpm --filter @snowluma/core test:watch",
"test:common": "pnpm --filter @snowluma/common test",
"test:all": "pnpm -r --if-present test",
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
"typecheck": "pnpm -r --if-present typecheck",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
describe('hex', () => {
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
expect(toHex(b)).toBe('000fa0ff');
expect(toHexUpper(b)).toBe('000FA0FF');
expect(toHex(Uint8Array.of())).toBe('');
});
it('hexPreview appends "..." only past maxBytes', () => {
const b = Uint8Array.from([1, 2, 3, 4, 5]);
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
});
it('fromHex round-trips toHex and rejects odd-length input', () => {
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
expect(fromHex(toHex(b)).equals(b)).toBe(true);
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
expect(() => fromHex('abc')).toThrow();
});
});
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest';
import { renderParamsVerbose, summarizeParams } from '../src/log-summary';
describe('summarizeParams', () => {
it('renders null/undefined as {}', () => {
expect(summarizeParams(null)).toBe('{}');
expect(summarizeParams(undefined)).toBe('{}');
});
it('renders a top-level non-object via String() WITHOUT quotes', () => {
// The reported change-request: a top-level primitive is NOT JSON-quoted.
expect(summarizeParams('hello')).toBe('hello');
expect(summarizeParams(123)).toBe('123');
});
it('collapses a top-level array to [len=N]', () => {
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
});
it('quotes string fields, collapses nested values, truncates long strings', () => {
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
.toBe('a=1 b="x" c={...} e=[len=2]');
expect(summarizeParams({ s: 'x'.repeat(50) }))
.toBe(`s="${'x'.repeat(40)}..."`);
});
it('caps total output and appends "..." on overflow', () => {
const big: Record<string, number> = {};
for (let i = 0; i < 60; i++) big['key' + i] = i;
const out = summarizeParams(big);
expect(out.startsWith('key0=0')).toBe(true);
expect(out.endsWith('...')).toBe(true);
});
});
describe('renderParamsVerbose', () => {
it('redacts token / password / secret keys at any depth', () => {
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
expect(out).toContain('token:"***"');
expect(out).toContain('password:"***"');
expect(out).toContain('secret:"***"');
expect(out).toContain('ok:"v"');
});
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
expect(out).toContain('…<500B>');
expect(out).not.toContain('...<500B>');
});
it('guards against circular references', () => {
const o: Record<string, unknown> = { a: 1 };
o.self = o;
expect(renderParamsVerbose(o)).toContain('"[circular]"');
});
it('renders nested structure with primitives intact', () => {
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
});
});
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest';
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
describe('request-context', () => {
it('nextRequestId increments monotonically and stays a positive integer', () => {
const a = nextRequestId();
const b = nextRequestId();
expect(a).toBeGreaterThan(0);
expect(b).toBe(a + 1);
});
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
expect(currentRequestId()).toBeUndefined();
runWithRequestId(42, () => {
expect(currentRequestId()).toBe(42);
runWithRequestId(99, () => {
expect(currentRequestId()).toBe(99);
});
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
});
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
await runWithRequestId(7, async () => {
await Promise.resolve();
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
});
});
it('returns the callback result', () => {
expect(runWithRequestId(1, () => 'value')).toBe('value');
});
});
+5 -4
View File
@@ -82,10 +82,11 @@ class Utf8Validator {
}
} else {
if (b < this.minNext || b > 0xBF) return false;
if (this.state === 2 && this.codepoint === 0xD && (b & 0x20)) {
return false;
}
if (this.codepoint === 0xD && this.state === 2 && b >= 0xA0) {
// Reject UTF-16 surrogates (U+D800–U+DFFF), encoded as 0xED 0xA0–0xBF ….
// Here b is already constrained to 0x80–0xBF by the guard above, and in
// that range `b & 0x20` is true iff `b >= 0xA0` — so a single check
// covers it (the former second `if` was unreachable dead code).
if (this.state === 2 && this.codepoint === 0xD && b >= 0xA0) {
return false;
}
this.codepoint = (this.codepoint << 6) | (b & 0x3F);