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
|
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {inspect} from 'node:util';
import chroma from 'chroma-js';
import {getColors} from '#colors';
import {quickLoadContentDependencies} from '#content-dependencies';
import {quickEvaluate} from '#content-function';
import * as html from '#html';
import {internalDefaultStringsFile, processLanguageFile} from '#language';
import {empty, showAggregate} from '#sugar';
import {generateURLs, thumb, urlSpec} from '#urls';
import mock from './generic-mock.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function testContentFunctions(t, message, fn) {
const urls = generateURLs(urlSpec);
t.test(message, async t => {
let loadedContentDependencies;
const language = await processLanguageFile(internalDefaultStringsFile);
const mocks = [];
const evaluate = ({
from = 'localized.home',
contentDependencies = {},
extraDependencies = {},
...opts
}) => {
if (!loadedContentDependencies) {
throw new Error(`Await .load() before performing tests`);
}
const {to} = urls.from(from);
return cleanCatchAggregate(() => {
return quickEvaluate({
...opts,
contentDependencies: {
...contentDependencies,
...loadedContentDependencies,
},
extraDependencies: {
html,
language,
thumb,
to,
urls,
cachebust: 413,
pagePath: ['home'],
appendIndexHTML: false,
getColors: c => getColors(c, {chroma}),
wikiData: {
wikiInfo: {},
},
...extraDependencies,
},
});
});
};
evaluate.load = async (opts) => {
if (loadedContentDependencies) {
throw new Error(`Already loaded!`);
}
loadedContentDependencies = await asyncCleanCatchAggregate(() =>
quickLoadContentDependencies({
logging: false,
...opts,
}));
};
evaluate.snapshot = (...args) => {
if (!loadedContentDependencies) {
throw new Error(`Await .load() before performing tests`);
}
const [description, opts] =
(typeof args[0] === 'string'
? args
: ['output', ...args]);
let result = evaluate(opts);
if (opts.multiple) {
result = result.map(item => item.toString()).join('\n');
} else {
result = result.toString();
}
t.matchSnapshot(result, description);
};
evaluate.stubTemplate = name =>
// Creates a particularly permissable template, allowing any slot values
// to be stored and just outputting the contents of those slots as-are.
_stubTemplate(name, false);
evaluate.stubContentFunction = name =>
// Like stubTemplate, but instead of a template directly, returns
// an object describing a content function - suitable for passing
// into evaluate.mock.
_stubTemplate(name, true);
const _stubTemplate = (name, mockContentFunction) => {
const inspectNicely = (value, opts = {}) =>
inspect(value, {
...opts,
colors: false,
sort: true,
});
const makeTemplate = formatContentFn =>
new (class extends html.Template {
#slotValues = {};
constructor() {
super({
content: () => this.#getContent(formatContentFn),
});
}
setSlots(slotNamesToValues) {
Object.assign(this.#slotValues, slotNamesToValues);
}
setSlot(slotName, slotValue) {
this.#slotValues[slotName] = slotValue;
}
#getContent(formatContentFn) {
const toInspect =
Object.fromEntries(
Object.entries(this.#slotValues)
.filter(([key, value]) => value !== null));
const inspected =
inspectNicely(toInspect, {
breakLength: Infinity,
compact: true,
depth: Infinity,
});
return formatContentFn(inspected); `${name}: ${inspected}`;
}
});
if (mockContentFunction) {
return {
data: (...args) => ({args}),
generate: (data) =>
makeTemplate(slots => {
const argsLines =
(empty(data.args)
? []
: inspectNicely(data.args, {depth: Infinity})
.split('\n'));
return (`[mocked: ${name}` +
(empty(data.args)
? ``
: argsLines.length === 1
? `\n args: ${argsLines[0]}`
: `\n args: ${argsLines[0]}\n` +
argsLines.slice(1).join('\n').replace(/^/gm, ' ')) +
(!empty(data.args)
? `\n `
: ` - `) +
(slots
? `slots: ${slots}]`
: `slots: none]`));
}),
};
} else {
return makeTemplate(slots => `${name}: ${slots}`);
}
};
evaluate.mock = (...opts) => {
const {value, close} = mock(...opts);
mocks.push({close});
return value;
};
evaluate.mock.transformContent = {
transformContent: {
extraDependencies: ['html'],
data: content => ({content}),
slots: {mode: {type: 'string'}},
generate: ({content}) => content,
},
};
await fn(t, evaluate);
if (!empty(mocks)) {
cleanCatchAggregate(() => {
const errors = [];
for (const {close} of mocks) {
try {
close();
} catch (error) {
errors.push(error);
}
}
if (!empty(errors)) {
throw new AggregateError(errors, `Errors closing mocks`);
}
});
}
});
}
function printAggregate(error) {
if (error instanceof AggregateError) {
const message = showAggregate(error, {
showTraces: true,
print: false,
pathToFileURL: f => path.relative(path.join(__dirname, '../..'), fileURLToPath(f)),
});
for (const line of message.split('\n')) {
console.error(line);
}
}
}
function cleanCatchAggregate(fn) {
try {
return fn();
} catch (error) {
printAggregate(error);
throw error;
}
}
async function asyncCleanCatchAggregate(fn) {
try {
return await fn();
} catch (error) {
printAggregate(error);
throw error;
}
}
|