File: test.js

package info (click to toggle)
node-os-locale 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 100 kB
  • ctags: 12
  • sloc: makefile: 2; sh: 2
file content (85 lines) | stat: -rw-r--r-- 2,172 bytes parent folder | download
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
import execa from 'execa';
import test from 'ava';
import requireUncached from 'require-uncached';

const envVars = ['LC_ALL', 'LANGUAGE', 'LANG', 'LC_MESSAGES'];
const expectedFallback = 'en_US';

function unsetEnvVars(cache) {
	envVars.forEach(envVar => {
		if (process.env[envVar]) {
			cache[envVar] = process.env[envVar];
			delete process.env[envVar];
		}
	});
}

function restoreEnvVars(cache) {
	envVars.forEach(envVar => {
		if (cache[envVar]) {
			process.env[envVar] = cache[envVar];
		}
	});
}

test('async', async t => {
	const locale = await requireUncached('./')();
	console.log('Locale identifier:', locale);
	t.true(locale.length > 1);
	t.true(locale.includes('_'));
});

test('sync', t => {
	const locale = requireUncached('./').sync();
	console.log('Locale identifier:', locale);
	t.true(locale.length > 1);
	t.true(locale.includes('_'));
});

test('async without spawn', async t => {
	const beforeTest = {};

	// unset env vars and cache for restoration
	unsetEnvVars(beforeTest);

	// mock execa.stdout
	beforeTest.stdout = execa.stdout;
	execa.stdout = () => new Promise(resolve => resolve('spawn_NOTALLOWED'));

	// callback to restore env vars and undo mock
	const afterTest = () => {
		restoreEnvVars(beforeTest);
		execa.stdout = beforeTest.execaStdout;
	};

	// test async method
	const locale = await requireUncached('./')({spawn: false});
	console.log('Locale identifier:', locale);
	afterTest();
	t.is(locale, expectedFallback, 'Locale did not match expected fallback');
	t.not(locale, 'spawn_NOTALLOWED', 'Attempted to spawn subprocess');
});

test('sync without spawn', t => {
	const beforeTest = {};

	// unset env vars and cache for restoration
	unsetEnvVars(beforeTest);

	// mock execa.sync
	beforeTest.execaSync = execa.sync;
	execa.sync = () => {
		t.false('Attempted to spawn subprocess');
	};

	// test sync method
	const locale = requireUncached('./').sync({spawn: false});
	console.log('Locale identifier:', locale);
	t.is(locale, expectedFallback, 'Locale did not match expected fallback');

	// restore env vars and undo mock
	restoreEnvVars(beforeTest);
	if (beforeTest.execaSync) {
		execa.sync = beforeTest.execaSync;
	}
});