-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-enum.ts
More file actions
42 lines (37 loc) · 1.56 KB
/
test-enum.ts
File metadata and controls
42 lines (37 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { z } from 'zod';
const emptyToUndefined = (val: unknown) => (val === '' ? undefined : val);
const preprocessEnum = <T extends string>(
values: [T, ...T[]],
defaultValue: T
) =>
z.preprocess(
(val) => (typeof val === 'string' && val !== '' ? val.toLowerCase() : emptyToUndefined(val)),
z.enum(values).default(defaultValue)
);
const schema = z.object({
ROLE: preprocessEnum(['user', 'assistant'], 'assistant'),
EXIT: preprocessEnum(['never', 'max', 'always'], 'always'),
TURNS: z.preprocess(
(val) => (typeof val === 'string' && val !== '' ? val.toUpperCase() : emptyToUndefined(val)),
z.string().default('OFF')
),
});
const testCases = [
{ input: { ROLE: 'USER', EXIT: 'MAX', TURNS: 'on' }, expected: { ROLE: 'user', EXIT: 'max', TURNS: 'ON' } },
{ input: { ROLE: 'Assistant', EXIT: 'Always', TURNS: 'off' }, expected: { ROLE: 'assistant', EXIT: 'always', TURNS: 'OFF' } },
{ input: { ROLE: '', EXIT: '', TURNS: '' }, expected: { ROLE: 'assistant', EXIT: 'always', TURNS: 'OFF' } },
{ input: { ROLE: undefined, EXIT: undefined, TURNS: undefined }, expected: { ROLE: 'assistant', EXIT: 'always', TURNS: 'OFF' } },
];
testCases.forEach(({ input, expected }, index) => {
try {
const result = schema.parse(input);
const passed = JSON.stringify(result) === JSON.stringify(expected);
console.log(`Test Case ${index + 1}: ${passed ? 'PASS' : 'FAIL'}`);
if (!passed) {
console.error('Expected:', expected);
console.error('Received:', result);
}
} catch (e) {
console.error(`Test Case ${index + 1}: ERROR`, e);
}
});