import { describe, it, beforeEach, mock } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import Gettext from '../src/gettext.js'; import type { LocaleGettext } from '../src/gettext.js'; describe('Gettext', () => { let gt: Gettext; let jsonFile: any; beforeEach(() => { gt = new Gettext({ debug: false }); jsonFile = JSON.parse(fs.readFileSync(new URL('fixtures/latin13.json', import.meta.url), 'utf8')); }); describe('#constructor', () => { let gtc; beforeEach(() => { gtc = null; }); describe('#sourceLocale option', () => { it('should accept any string as a locale', () => { gtc = new Gettext({ sourceLocale: 'en-US' }); assert.strictEqual(gtc.sourceLocale, 'en-US'); gtc = new Gettext({ sourceLocale: '01234' }); assert.strictEqual(gtc.sourceLocale, '01234'); }); it('should default to en empty string', () => { assert.strictEqual(new Gettext().sourceLocale, ''); }); it('should reject non-string values', () => { gtc = new Gettext({ sourceLocale: null as any }); assert.strictEqual(gtc.sourceLocale, ''); gtc = new Gettext({ sourceLocale: 123 as any }); assert.strictEqual(gtc.sourceLocale, ''); gtc = new Gettext({ sourceLocale: false as any }); assert.strictEqual(gtc.sourceLocale, ''); gtc = new Gettext({ sourceLocale: {} as any }); assert.strictEqual(gtc.sourceLocale, ''); gtc = new Gettext({ sourceLocale: (() => {}) as any }); assert.strictEqual(gtc.sourceLocale, ''); }); }); }); describe('#getLanguageCode', () => { it('should normalize locale string', () => { assert.strictEqual(Gettext.getLanguageCode('ab-cd_ef.utf-8'), 'ab'); assert.strictEqual(Gettext.getLanguageCode('ab-cd_ef'), 'ab'); }); }); describe('#addTranslations', () => { it('should store added translations', () => { gt.addTranslations('et-EE', 'messages', jsonFile); assert.ok(gt.catalogs['et-EE'] !== undefined && gt.catalogs['et-EE'] !== null); assert.ok(gt.catalogs['et-EE'].messages !== undefined && gt.catalogs['et-EE'].messages !== null); assert.strictEqual(gt.catalogs['et-EE'].messages.charset, 'iso-8859-13'); }); it('should store added translations on a custom domain', () => { gt.addTranslations('et-EE', 'mydomain', jsonFile); assert.ok(gt.catalogs['et-EE'].mydomain !== undefined && gt.catalogs['et-EE'].mydomain !== null); assert.strictEqual(gt.catalogs['et-EE'].mydomain.charset, 'iso-8859-13'); }); }); describe('#setLocale', () => { it('should have the empty string as default locale', () => { assert.strictEqual(gt.locale, ''); }); it('should accept whatever string is passed as locale', () => { gt.setLocale('de-AT'); assert.strictEqual(gt.locale, 'de-AT'); gt.setLocale('01234'); assert.strictEqual(gt.locale, '01234'); gt.setLocale(''); assert.strictEqual(gt.locale, ''); }); it('should reject non-string locales', () => { gt.setLocale(null as any); assert.strictEqual(gt.locale, ''); gt.setLocale(123 as any); assert.strictEqual(gt.locale, ''); gt.setLocale(false as any); assert.strictEqual(gt.locale, ''); gt.setLocale((() => {}) as any); assert.strictEqual(gt.locale, ''); gt.setLocale(NaN as any); assert.strictEqual(gt.locale, ''); (gt as any).setLocale(); assert.strictEqual(gt.locale, ''); }); }); describe('#setTextDomain', () => { it('should default to "messages"', () => { assert.strictEqual(gt.domain, 'messages'); }); it('should accept and store any string as domain name', () => { gt.setTextDomain('mydomain'); assert.strictEqual(gt.domain, 'mydomain'); gt.setTextDomain('01234'); assert.strictEqual(gt.domain, '01234'); gt.setTextDomain(''); assert.strictEqual(gt.domain, ''); }); it('should reject non-string domains', () => { gt.setTextDomain(null as any); assert.strictEqual(gt.domain, 'messages'); gt.setTextDomain(123 as any); assert.strictEqual(gt.domain, 'messages'); gt.setTextDomain(false as any); assert.strictEqual(gt.domain, 'messages'); gt.setTextDomain((() => {}) as any); assert.strictEqual(gt.domain, 'messages'); gt.setTextDomain(NaN as any); assert.strictEqual(gt.domain, 'messages'); (gt as any).setTextDomain(); assert.strictEqual(gt.domain, 'messages'); }); }); describe('Resolve translations', () => { beforeEach(() => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.setLocale('et-EE'); }); describe('#dnpgettext', () => { it('should return singular match from default context', () => { assert.strictEqual(gt.dnpgettext('messages', '', 'o2-1', 'o2-2', 1), 't2-1'); }); it('should return plural match from default context', () => { assert.strictEqual(gt.dnpgettext('messages', '', 'o2-1', 'o2-2', 2), 't2-2'); }); it('should return singular match from selected context', () => { assert.strictEqual(gt.dnpgettext('messages', 'c2', 'co2-1', 'co2-2', 1), 'ct2-1'); }); it('should return plural match from selected context', () => { assert.strictEqual(gt.dnpgettext('messages', 'c2', 'co2-1', 'co2-2', 2), 'ct2-2'); }); it('should return singular match for non existing domain', () => { assert.strictEqual(gt.dnpgettext('cccc', '', 'o2-1', 'o2-2', 1), 'o2-1'); }); }); describe('#gettext', () => { it('should return singular from default context', () => { assert.strictEqual(gt.gettext('o2-1'), 't2-1'); }); }); describe('#dgettext', () => { it('should return singular from default context', () => { assert.strictEqual(gt.dgettext('messages', 'o2-1'), 't2-1'); }); }); describe('#ngettext', () => { it('should return plural from default context', () => { assert.strictEqual(gt.ngettext('o2-1', 'o2-2', 2), 't2-2'); }); }); describe('#dngettext', () => { it('should return plural from default context', () => { assert.strictEqual(gt.dngettext('messages', 'o2-1', 'o2-2', 2), 't2-2'); }); }); describe('#pgettext', () => { it('should return singular from selected context', () => { assert.strictEqual(gt.pgettext('c2', 'co2-1'), 'ct2-1'); }); }); describe('#dpgettext', () => { it('should return singular from selected context', () => { assert.strictEqual(gt.dpgettext('messages', 'c2', 'co2-1'), 'ct2-1'); }); }); describe('#npgettext', () => { it('should return plural from selected context', () => { assert.strictEqual(gt.npgettext('c2', 'co2-1', 'co2-2', 2), 'ct2-2'); }); }); describe('#getComment', () => { it('should return comments object', () => { assert.deepStrictEqual(gt.getComment('messages', '', 'test'), { translator: 'Normal comment line 1\nNormal comment line 2', extracted: 'Editors note line 1\nEditors note line 2', reference: '/absolute/path:13\n/absolute/path:14', flag: 'line 1\nline 2', previous: 'line 3\nline 4' }); }); }); }); describe('Resolve translations with useLocale', () => { let localGt: LocaleGettext = new Gettext({ sourceLocale: 'en_US' }); beforeEach(() => { gt.addTranslations('et-EE', 'messages', jsonFile); localGt = gt.useLocale('et-EE'); }); describe('#dnpgettext', () => { it('should return singular match from default context', () => { assert.strictEqual(localGt.dnpgettext('messages', '', 'o2-1', 'o2-2', 1), 't2-1'); }); it('should return plural match from default context', () => { assert.strictEqual(localGt.dnpgettext('messages', '', 'o2-1', 'o2-2', 2), 't2-2'); }); it('should return singular match from selected context', () => { assert.strictEqual(localGt.dnpgettext('messages', 'c2', 'co2-1', 'co2-2', 1), 'ct2-1'); }); it('should return plural match from selected context', () => { assert.strictEqual(localGt.dnpgettext('messages', 'c2', 'co2-1', 'co2-2', 2), 'ct2-2'); }); it('should return singular match for non existing domain', () => { assert.strictEqual(localGt.dnpgettext('cccc', '', 'o2-1', 'o2-2', 1), 'o2-1'); }); }); describe('#gettext', () => { it('should return singular from default context', () => { assert.strictEqual(localGt.gettext('o2-1'), 't2-1'); }); }); describe('#dgettext', () => { it('should return singular from default context', () => { assert.strictEqual(localGt.dgettext('messages', 'o2-1'), 't2-1'); }); }); describe('#ngettext', () => { it('should return plural from default context', () => { assert.strictEqual(localGt.ngettext('o2-1', 'o2-2', 2), 't2-2'); }); }); describe('#dngettext', () => { it('should return plural from default context', () => { assert.strictEqual(localGt.dngettext('messages', 'o2-1', 'o2-2', 2), 't2-2'); }); }); describe('#pgettext', () => { it('should return singular from selected context', () => { assert.strictEqual(localGt.pgettext('c2', 'co2-1'), 'ct2-1'); }); }); describe('#dpgettext', () => { it('should return singular from selected context', () => { assert.strictEqual(localGt.dpgettext('messages', 'c2', 'co2-1'), 'ct2-1'); }); }); describe('#npgettext', () => { it('should return plural from selected context', () => { assert.strictEqual(localGt.npgettext('c2', 'co2-1', 'co2-2', 2), 'ct2-2'); }); }); }); describe('Unresolvable transaltions', () => { beforeEach(() => { gt.addTranslations('et-EE', 'messages', jsonFile); }); it('should pass msgid when no translation is found', () => { assert.strictEqual(gt.gettext('unknown phrase'), 'unknown phrase'); assert.strictEqual(gt.dnpgettext('unknown domain', null as any, 'hello'), 'hello'); assert.strictEqual(gt.dnpgettext('messages', 'unknown context', 'hello'), 'hello'); // 'o2-1' is translated, but no locale has been set yet assert.strictEqual(gt.dnpgettext('messages', '', 'o2-1'), 'o2-1'); }); it('should pass unresolved singular message when count is 1', () => { assert.strictEqual(gt.dnpgettext('messages', '', '0 matches', 'multiple matches', 1), '0 matches'); }); it('should pass unresolved plural message when count > 1', () => { assert.strictEqual(gt.dnpgettext('messages', '', '0 matches', 'multiple matches', 100), 'multiple matches'); }); }); describe('Object.prototype member names', () => { const names = ['constructor', 'toString', '__proto__', 'hasOwnProperty', 'valueOf', 'isPrototypeOf', '__defineGetter__']; // Built as JSON text so "__proto__" ends up an own key after JSON.parse, the way a parsed catalog carries it const entry = (msgctxt: string, msgid: string) => ({ msgctxt, msgid, msgid_plural: `${msgid} plural`, msgstr: [`${msgctxt}:${msgid}:0`, `${msgctxt}:${msgid}:1`] }); const contextJson = (msgctxt: string, msgids: string[]) => `{${msgids.map(msgid => `${JSON.stringify(msgid)}:${JSON.stringify(entry(msgctxt, msgid))}`).join(',')}}`; const buildCatalog = () => { const contexts = [`"":${contextJson('', names)}`, ...names.map(name => `${JSON.stringify(name)}:${contextJson(name, [name])}`)]; return JSON.parse(`{"charset":"utf-8","headers":{"plural-forms":"nplurals=2; plural=(n != 1);"},"translations":{${contexts.join(',')}}}`); }; it('should return the msgid without throwing when the catalog does not define it', () => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.setLocale('et-EE'); const local = gt.useLocale('et-EE'); for (const name of names) { assert.strictEqual(gt.gettext(name), name); assert.strictEqual(gt.ngettext(name, `${name}s`, 1), name); assert.strictEqual(gt.ngettext(name, `${name}s`, 5), `${name}s`); assert.strictEqual(gt.pgettext(name, name), name); assert.strictEqual(gt.pgettext('', name), name); assert.strictEqual(gt.npgettext(name, name, `${name}s`, 5), `${name}s`); assert.strictEqual(gt.dgettext(name, 'o2-1'), 'o2-1'); assert.deepStrictEqual(gt.getComment('messages', name, name), {}); assert.strictEqual(local.gettext(name), name); assert.strictEqual(local.npgettext(name, name, `${name}s`, 2), `${name}s`); } }); it('should resolve translations whose msgid and context are Object.prototype member names', () => { gt.addTranslations('et-EE', 'messages', buildCatalog()); gt.setLocale('et-EE'); const local = gt.useLocale('et-EE'); for (const name of names) { assert.strictEqual(gt.gettext(name), `:${name}:0`); assert.strictEqual(gt.ngettext(name, 'x', 1), `:${name}:0`); assert.strictEqual(gt.ngettext(name, 'x', 3), `:${name}:1`); assert.strictEqual(gt.pgettext(name, name), `${name}:${name}:0`); assert.strictEqual(gt.npgettext(name, name, 'x', 3), `${name}:${name}:1`); assert.strictEqual(local.npgettext(name, name, 'x', 3), `${name}:${name}:1`); } }); }); describe('Events', () => { let errorListener: ReturnType void>>; beforeEach(() => { errorListener = mock.fn(); gt.on('error', errorListener); }); it('should notify a registered listener of error events', () => { gt.emit('error', 'Something went wrong'); assert.strictEqual(errorListener.mock.callCount(), 1); }); it('should deregister a previously registered event listener', () => { gt.off('error', errorListener); gt.emit('error', 'Something went wrong'); assert.strictEqual(errorListener.mock.callCount(), 0); }); it('should emit an error event when adding a reserved key as locale', () => { gt.addTranslations('__proto__', 'polluted', 'pwned' as any); assert.strictEqual(errorListener.mock.callCount(), 1); }); it('should emit an error event when a locale that has no translations is set', () => { gt.setLocale('et-EE'); assert.strictEqual(errorListener.mock.callCount(), 1); }); it('should emit an error event when no locale has been set', () => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.gettext('o2-1'); assert.strictEqual(errorListener.mock.callCount(), 1); gt.setLocale('et-EE'); gt.gettext('o2-1'); assert.strictEqual(errorListener.mock.callCount(), 1); }); it('should emit an error event when a translation is missing', () => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.setLocale('et-EE'); gt.gettext('This message is not translated'); assert.strictEqual(errorListener.mock.callCount(), 1); }); it('should not emit any error events when a translation is found', () => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.setLocale('et-EE'); gt.gettext('o2-1'); assert.strictEqual(errorListener.mock.callCount(), 0); }); it('should not emit any error events when the current locale is the default locale', () => { let gtd = new Gettext({ sourceLocale: 'en-US' }); let errorListenersourceLocale = mock.fn(); gtd.on('error', errorListenersourceLocale); gtd.setLocale('en-US'); gtd.gettext('This message is not translated'); assert.strictEqual(errorListenersourceLocale.mock.callCount(), 0); }); it('should name the received type in invalid argument warnings', () => { gt.addTranslations(42 as any, 'messages', jsonFile); gt.addTranslations('et-EE', null as any, jsonFile); gt.setLocale(false as any); gt.setTextDomain(undefined as any); assert.deepStrictEqual( errorListener.mock.calls.map(call => call.arguments[0].message), [ 'Invalid argument for locale in addTranslations(): Expected a string, but received a number.', 'Invalid argument for domain in addTranslations(): Expected a string, but received a object.', 'Invalid argument for setLocale(): Expected a string, but received a boolean.', 'Invalid argument for setTextDomain(): Expected a string, but received a undefined.' ] ); }); it('should name useLocale() and the received type when useLocale() is given a non-string', () => { assert.throws(() => gt.useLocale(7 as any), { message: 'Invalid argument for useLocale(): Expected a string, but received a number.' }); }); it('should refuse reserved keywords as a domain or locale everywhere', () => { gt.addTranslations('et-EE', 'constructor', jsonFile); gt.setLocale('toString'); gt.setTextDomain('__proto__'); assert.deepStrictEqual(Object.keys(gt.catalogs), []); assert.strictEqual(gt.locale, ''); assert.strictEqual(gt.domain, 'messages'); assert.throws(() => gt.useLocale('hasOwnProperty'), { message: 'Invalid locale: "hasOwnProperty" is a reserved keyword and cannot be used as a locale.' }); assert.deepStrictEqual( errorListener.mock.calls.map(call => call.arguments[0].message), [ 'Invalid domain: "constructor" is a reserved keyword and cannot be used as a domain.', 'Invalid locale: "toString" is a reserved keyword and cannot be used as a locale.', 'Invalid domain: "__proto__" is a reserved keyword and cannot be used as a domain.' ] ); }); it('should warn about an empty or unknown locale in useLocale()', () => { gt.addTranslations('et-EE', 'messages', jsonFile); gt.useLocale('et-EE'); gt.useLocale(' '); assert.deepStrictEqual( errorListener.mock.calls.map(call => call.arguments[0].message), ['Invalid locale: The locale cannot be an empty string.', 'Locale " " not found: No translations have been added for this locale.'] ); }); it('should log warnings to the console in debug mode', t => { const consoleWarn = t.mock.method(console, 'warn', () => undefined); const debugGt = new Gettext({ debug: true }); debugGt.on('error', errorListener); debugGt.gettext('missing'); assert.deepStrictEqual( consoleWarn.mock.calls.map(call => call.arguments[0]), ['Translation not found for msgid "missing" with context "" in domain "messages".'] ); assert.strictEqual(errorListener.mock.callCount(), 1); }); }); describe('Incomplete catalog entries', () => { beforeEach(() => { gt.addTranslations('en', 'messages', { translations: { '': { bare: { msgid: 'bare', msgstr: ['Bare'] }, broken: { msgid: 'broken', msgstr: 'not an array' as any }, empty: { msgid: 'empty', msgid_plural: 'empties', msgstr: ['', ''] } } } }); gt.setLocale('en'); }); it('should return an empty comments object for an entry without comments', () => { assert.deepStrictEqual(gt.getComment('messages', '', 'bare'), {}); }); it('should fall back to the msgid when msgstr is not a list or the form is empty', () => { assert.strictEqual(gt.gettext('broken'), 'broken'); assert.strictEqual(gt.ngettext('empty', 'empties', 1), 'empty'); assert.strictEqual(gt.ngettext('empty', 'empties', 2), 'empties'); // without a plural msgid the singular one stands in for it assert.strictEqual(gt.ngettext('empty', '', 2), 'empty'); }); }); });