Repository navigation
Expand file tree
/
Copy pathvalidation-message.test.ts
More file actions
282 lines (257 loc) · 12.3 KB
/
Copy pathvalidation-message.test.ts
File metadata and controls
282 lines (257 loc) · 12.3 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import {
BUILTIN_VALIDATION_MESSAGES,
VALIDATION_MESSAGE_FALLBACK_LOCALE,
interpolateValidationMessage,
renderValidationMessage,
validationMessageTranslationKey,
} from './validation-message';
/**
* #3957 — the write path's built-in messages were hardcoded English templates
* with the API field name concatenated in, so a `zh-CN` user reading a rejected
* import row got `penalty_amount must be ≥ 0`. These tests pin the catalog's
* contract: every locale is complete, `en` output is unchanged from the
* pre-#3957 strings, and a deployment can override any message.
*/
describe('validation message catalog — completeness', () => {
const en = BUILTIN_VALIDATION_MESSAGES[VALIDATION_MESSAGE_FALLBACK_LOCALE];
it('ships the four platform locales', () => {
expect(Object.keys(BUILTIN_VALIDATION_MESSAGES).sort()).toEqual(
['en', 'es-ES', 'ja-JP', 'zh-CN'],
);
});
/**
* `en` is the last-resort fallback, so a key missing from ANOTHER locale
* degrades to English — but a key missing from `en` degrades to
* `<label> (<messageKey>)`. Every locale carrying every key is what keeps a
* localized deployment from silently falling back mid-sentence.
*/
it('every locale defines every message key', () => {
const expected = Object.keys(en).sort();
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
expect(Object.keys(catalog).sort(), `locale ${locale}`).toEqual(expected);
}
});
it('every template names the field via {{label}}, never a bare API name', () => {
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
for (const [key, template] of Object.entries(catalog)) {
expect(template, `${locale}.${key}`).toContain('{{label}}');
expect(template, `${locale}.${key}`).not.toContain('{{field}}');
}
}
});
/**
* The bounds must reach the reader. A template that dropped `{{min}}` would
* produce "必须大于或等于" with no number — worse than the English it replaced.
*/
it('the bounded codes interpolate their bound in every locale', () => {
const required: Record<string, string[]> = {
min_value: ['{{min}}'],
max_value: ['{{max}}'],
max_scale: ['{{scale}}', '{{actual}}'],
// `max_precision` (#19992): both sentences carry the bound and the count;
// the `_scaled` one also names the decimal places the count was taken at.
max_precision: ['{{precision}}', '{{actual}}'],
max_precision_scaled: ['{{precision}}', '{{scale}}', '{{actual}}'],
min_length: ['{{minLength}}', '{{actual}}'],
max_length: ['{{maxLength}}', '{{actual}}'],
invalid_option: ['{{allowed}}'],
invalid_option_value: ['{{value}}', '{{allowed}}'],
invalid_transition: ['{{from}}', '{{to}}'],
// `value_domain` (#14168): the code-named default names the domain by
// its machine word and echoes the offending value; each finer variant
// spells the standard out in prose and must still echo the value.
value_domain: ['{{valueDomain}}', '{{value}}'],
value_domain_iana_time_zone: ['{{value}}'],
value_domain_iso_4217_currency: ['{{value}}'],
value_domain_iso_3166_alpha2: ['{{value}}'],
// `invalid_date`'s range sentences (#20846) name the kind's years in
// every locale — from parameters, so the refusing door's range decides them.
invalid_date_range: ['{{firstYear}}', '{{lastYear}}'],
invalid_datetime_range: ['{{firstYear}}', '{{lastYear}}'],
};
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
for (const [key, placeholders] of Object.entries(required)) {
for (const p of placeholders) {
expect(catalog[key], `${locale}.${key}`).toContain(p);
}
}
}
});
});
describe('renderValidationMessage — English output is unchanged, the field label in place of the API name', () => {
// Byte-for-byte the pre-#3957 strings, with the field's label where the API
// name used to be interpolated.
const cases: Array<[string, Record<string, unknown> | undefined, string]> = [
['required', undefined, 'Amount is required'],
['min_value', { min: 0 }, 'Amount must be ≥ 0'],
['max_value', { max: 99999999.99 }, 'Amount must be ≤ 99999999.99'],
['max_length', { maxLength: 512, actual: 3000 }, 'Amount must be ≤ 512 characters (got 3000)'],
['min_length', { minLength: 3, actual: 1 }, 'Amount must be ≥ 3 characters (got 1)'],
['invalid_email', undefined, 'Amount must be a valid email address'],
['invalid_url', undefined, 'Amount must be a valid URL (scheme://...)'],
['invalid_phone', undefined, 'Amount must be a valid phone number'],
['invalid_number', undefined, 'Amount must be a number'],
['invalid_boolean', undefined, 'Amount must be true or false'],
['invalid_date', undefined, 'Amount must be a valid date (ISO-8601)'],
['invalid_datetime', undefined, 'Amount must be a valid datetime (ISO-8601)'],
['invalid_time', undefined, 'Amount must be a valid time (HH:MM or HH:MM:SS)'],
['invalid_date_range', { firstYear: '0001', lastYear: '9999' }, 'Amount must be a date in the years 0001 to 9999'],
[
'invalid_datetime_range',
{ firstYear: '1000', lastYear: '9999' },
'Amount must be a datetime whose UTC year falls in the years 1000 to 9999',
],
['invalid_option', { allowed: 'a, b' }, 'Amount must be one of: a, b'],
['invalid_option_value', { value: 'z', allowed: 'a, b' }, 'Amount: "z" is not one of: a, b'],
['invalid_type_array', undefined, 'Amount must be an array of values'],
];
for (const [messageKey, params, expected] of cases) {
it(`renders ${messageKey}`, () => {
expect(renderValidationMessage({ messageKey, label: 'Amount', params })).toBe(expected);
});
}
});
describe('renderValidationMessage — locale selection', () => {
it('renders zh-CN with the localized label', () => {
expect(
renderValidationMessage(
{ messageKey: 'min_value', label: '处罚金额', field: 'penalty_amount', params: { min: 0 } },
{ locale: 'zh-CN' },
),
).toBe('处罚金额必须大于或等于 0');
});
it('renders ja-JP and es-ES', () => {
expect(
renderValidationMessage({ messageKey: 'required', label: '氏名' }, { locale: 'ja-JP' }),
).toBe('氏名は必須です');
expect(
renderValidationMessage({ messageKey: 'required', label: 'Nombre' }, { locale: 'es-ES' }),
).toBe('Nombre es obligatorio');
});
// BCP-47 matching, same ladder as bundle lookup: a client sending `zh` or
// `ZH-cn` must not silently drop to English.
it.each(['zh', 'zh-cn', 'ZH-CN', 'zh-Hans-CN'])('matches %s to zh-CN', (locale) => {
expect(
renderValidationMessage({ messageKey: 'invalid_number', label: '数量' }, { locale }),
).toBe('数量必须是数字');
});
it('falls back to en for an unsupported locale', () => {
expect(
renderValidationMessage({ messageKey: 'invalid_number', label: 'Qty' }, { locale: 'fr-FR' }),
).toBe('Qty must be a number');
});
it('defaults to en when no locale is supplied', () => {
expect(renderValidationMessage({ messageKey: 'required', label: 'Qty' })).toBe('Qty is required');
});
});
describe('renderValidationMessage — deployment overrides', () => {
const key = validationMessageTranslationKey('min_value');
it('uses a translation when the i18n service resolves the key', () => {
const translate = (k: string) => (k === key ? '{{label}}不得小于 {{min}} 元' : k);
expect(
renderValidationMessage(
{ messageKey: 'min_value', label: '处罚金额', params: { min: 0 } },
{ locale: 'zh-CN', translate },
),
).toBe('处罚金额不得小于 0 元');
});
/**
* `II18nService.t` echoes the key back on a miss — that echo must not become
* the user-facing message.
*/
it('ignores the key-echo miss and uses the built-in', () => {
const translate = (k: string) => k;
expect(
renderValidationMessage(
{ messageKey: 'min_value', label: '处罚金额', params: { min: 0 } },
{ locale: 'zh-CN', translate },
),
).toBe('处罚金额必须大于或等于 0');
});
it('accepts an already-interpolated override without double-substituting', () => {
const translate = () => '处罚金额不得小于 0 元';
expect(
renderValidationMessage(
{ messageKey: 'min_value', label: '处罚金额', params: { min: 0 } },
{ locale: 'zh-CN', translate },
),
).toBe('处罚金额不得小于 0 元');
});
// A broken i18n plugin must degrade to the built-in catalog, never turn a
// 400 into a 500.
it('survives a throwing translator', () => {
const translate = () => { throw new Error('i18n exploded'); };
expect(
renderValidationMessage({ messageKey: 'required', label: '数量' }, { locale: 'zh-CN', translate }),
).toBe('数量不能为空');
});
});
describe('interpolateValidationMessage', () => {
it('leaves an unresolved placeholder verbatim', () => {
// Visible breakage beats a silent "must be ≥ ." — the missing param is
// named right there in the message.
expect(interpolateValidationMessage('{{label}} must be ≥ {{min}}', { label: 'Qty' }))
.toBe('Qty must be ≥ {{min}}');
});
it('interpolates falsy values rather than skipping them', () => {
expect(interpolateValidationMessage('{{label}} must be ≥ {{min}}', { label: 'Qty', min: 0 }))
.toBe('Qty must be ≥ 0');
});
it('renders a label-only fallback for an unknown message key', () => {
expect(renderValidationMessage({ messageKey: 'no_such_key', label: 'Qty' }))
.toBe('Qty (no_such_key)');
});
});
/**
* #20846 — a value the kind's rule reads, in a year outside the kind's
* supported years, is refused `invalid_date` with a sentence that names the
* years. The catalog never spells them: a template that carried a number would
* be a second copy of the range the doors judge by, and would go on naming the
* old years the day the range moved.
*/
describe('invalid_date_range / invalid_datetime_range — the years are parameters, never literals', () => {
it('no locale spells a year in the range sentences', () => {
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
for (const key of ['invalid_date_range', 'invalid_datetime_range']) {
expect(catalog[key], `${locale}.${key}`).toBeDefined();
const withoutPlaceholders = catalog[key].replace(/\{\{\w+\}\}/g, '');
expect(withoutPlaceholders, `${locale}.${key}`).not.toMatch(/\d/);
}
}
});
it('renders the years it is handed, in the caller\'s locale', () => {
expect(
renderValidationMessage(
{ messageKey: 'invalid_datetime_range', label: '发生时间', params: { firstYear: '1000', lastYear: '9999' } },
{ locale: 'zh-CN' },
),
).toBe('发生时间必须是 UTC 年份在 1000 年至 9999 年之间的日期时间');
});
});
/**
* #27236 — `invalid_number`'s currency sentence: a `currency` field written as
* an object, the retired `{ value, currency }` shape (ADR-0104 D1). Every
* locale teaches the same three facts, and none names a currency code: the
* field's `currencyConfig` or the tenant default decides the currency, never
* the sentence (#27119 Q2 = X).
*/
describe('invalid_number_currency_object — the shape lesson, with no currency code of its own', () => {
it('every locale names the retired shape, currencyConfig, both modes and ADR-0104', () => {
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
const template = catalog.invalid_number_currency_object;
expect(template, locale).toBeDefined();
for (const word of ['{ value, currency }', 'currencyConfig', 'defaultCurrency', 'fixed', 'dynamic', 'ADR-0104']) {
expect(template, `${locale}: ${word}`).toContain(word);
}
}
});
it('no locale spells a currency code', () => {
for (const [locale, catalog] of Object.entries(BUILTIN_VALIDATION_MESSAGES)) {
const prose = catalog.invalid_number_currency_object.replace('ADR-0104', '');
expect(prose, locale).not.toMatch(/(?<![A-Za-z])[A-Z]{3}(?![A-Za-z])/);
expect(prose, locale).not.toMatch(/[$¥€£]/);
}
});
});