-
Notifications
You must be signed in to change notification settings - Fork 190
/
Copy pathchaos-rehydration-test.ts
330 lines (273 loc) · 9.57 KB
/
chaos-rehydration-test.ts
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import type { Dict, Nullable, SimpleElement } from '@glimmer/interfaces';
import type { ComponentBlueprint, Content } from '@glimmer-workspace/integration-tests';
import { castToBrowser, castToSimple, expect } from '@glimmer/debug-util';
import { isIndexable, LOCAL_LOGGER } from '@glimmer/util';
import {
blockStack,
CLOSE,
content,
equalTokens,
OPEN,
PartialRehydrationDelegate,
qunitFixture,
RehydrationDelegate,
RenderTest,
replaceHTML,
suite,
test,
} from '@glimmer-workspace/integration-tests';
abstract class AbstractChaosMonkeyTest extends RenderTest {
abstract renderClientSide(template: string | ComponentBlueprint, context: Dict): void;
getRandomForIteration(iteration: number) {
const { seed } = QUnit.config;
const str = `${iteration}\x1C${seed}`;
// from https://github.com/qunitjs/qunit/blob/2.9.3/src/core/utilities.js#L144-L158
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0;
}
let hex = (0x100000000 + hash).toString(16);
if (hex.length < 8) {
hex = '0000000' + hex;
}
const result = hex.slice(-8);
let sample = parseInt(result, 16) || -1;
// from https://github.com/qunitjs/qunit/blob/2.9.3/src/core/processing-queue.js#L134-L154
sample ^= sample << 13;
sample ^= sample >>> 17;
sample ^= sample << 5;
if (sample < 0) {
sample += 0x100000000;
}
return sample / 0x100000000;
}
wreakHavoc(iteration = 0, shouldLog = false) {
const element = castToBrowser(this.element, 'HTML');
const original = element.innerHTML;
function collectChildNodes(childNodes: Node[], node: Node): Node[] {
// do some thing with the node here
node.childNodes.forEach((child) => {
childNodes.push(child);
collectChildNodes(childNodes, child);
});
return childNodes;
}
// gather all the nodes recursively
let nodes: Node[] = collectChildNodes([], element);
// cannot remove the first opening block node and last closing block node, that is what makes it rehydrateable
nodes = nodes.slice(1, -1);
// select a random node to remove
const indexToRemove = Math.floor(this.getRandomForIteration(iteration) * nodes.length);
const nodeToRemove = this.guardPresent({ 'node to remove': nodes[indexToRemove] });
const parent = this.guardPresent({ 'parent node': nodeToRemove.parentNode });
// remove it
parent.removeChild(nodeToRemove);
let removedNodeDisplay: Nullable<string>;
switch (nodeToRemove.nodeType) {
case 8 satisfies typeof Node.COMMENT_NODE:
removedNodeDisplay = `<!--${nodeToRemove.nodeValue}-->`;
break;
case 1 satisfies typeof Node.ELEMENT_NODE:
removedNodeDisplay = castToBrowser(nodeToRemove, ['HTML', 'SVG']).outerHTML;
break;
default:
removedNodeDisplay = nodeToRemove.nodeValue;
}
if (shouldLog) {
LOCAL_LOGGER.debug(
`${removedNodeDisplay} was removed;\noriginal: ${original}\nupdated: ${element.innerHTML}`
);
}
this.assert.notEqual(
original,
element.innerHTML,
`\`${removedNodeDisplay}\` was removed from \`${original}\``
);
}
runIterations(template: string, context: Dict, expectedHTML: string, count: number) {
const element = castToBrowser(this.element, 'HTML');
const elementResetValue = element.innerHTML;
const urlParams = (QUnit as any).urlParams as Dict<string>;
if (urlParams['iteration']) {
// runs a single iteration directly, no try/catch, with logging
const iteration = parseInt(urlParams['iteration'], 10);
this.wreakHavoc(iteration, true);
this.renderClientSide(template, context);
const element = castToBrowser(this.element, 'HTML');
this.assert.strictEqual(element.innerHTML, expectedHTML);
} else {
for (let i = 0; i < count; i++) {
const seed = QUnit.config.seed ? `&seed=${QUnit.config.seed}` : '';
const rerunUrl = `&testId=${QUnit.config.current.testId}&iteration=${i}${seed}`;
try {
this.wreakHavoc(i);
this.renderClientSide(template, context);
const element = castToBrowser(this.element, 'HTML');
this.assert.strictEqual(
element.innerHTML,
expectedHTML,
`should match after iteration ${i}; rerun with these query params: '${rerunUrl}'`
);
} catch (error) {
this.assert.pushResult({
result: false,
actual: getErrorMessage(this.assert, error),
expected: undefined,
message: `Error occurred during iteration ${i}; rerun with these query params: ${rerunUrl}`,
});
throw error;
} finally {
// reset the HTML
element.innerHTML = elementResetValue;
}
}
}
}
}
function getErrorMessage(assert: Assert, error: unknown): string {
if (isIndexable(error) && 'message' in error && typeof error.message === 'string') {
return error.message;
} else {
assert.pushResult({
result: false,
expected: `an error with a 'message' property`,
actual: error,
message: `unexpectedly, error.message did not exist`,
});
return '';
}
}
class ChaosMonkeyRehydration extends AbstractChaosMonkeyTest {
static suiteName = 'chaos-rehydration';
declare protected delegate: RehydrationDelegate;
declare protected serverOutput: Nullable<string>;
renderServerSide(
template: string | ComponentBlueprint,
context: Dict,
element: SimpleElement | undefined = undefined
): void {
this.serverOutput = this.delegate.renderServerSide(
template as string,
context,
() => this.takeSnapshot(),
element
);
replaceHTML(this.element, this.serverOutput);
}
renderClientSide(template: string | ComponentBlueprint, context: Dict): void {
this.context = context;
this.renderResult = this.delegate.renderClientSide(template as string, context, this.element);
}
assertExactServerOutput(_expected: string) {
const output = expect(
this.serverOutput,
'must renderServerSide before calling assertServerOutput'
);
equalTokens(output, _expected);
}
assertServerOutput(..._expected: Content[]) {
this.assertExactServerOutput(content([OPEN, ..._expected, CLOSE]));
}
@test
'adjacent text nodes'() {
const template = '<div>a {{this.b}}{{this.c}}{{this.d}}</div>';
const context = { b: '', c: '', d: '' };
this.renderServerSide(template, context);
const b = blockStack();
this.assertServerOutput(
`<div>a ${b(1)}<!--% %-->${b(1)}${b(1)}<!--% %-->${b(1)}${b(1)}<!--% %-->${b(1)}</div>`
);
this.runIterations(template, context, '<div>a </div>', 100);
}
@test
'<p> invoking a block which emits a <div>'() {
const template = '<p>hello {{#if this.show}}<div>world!</div>{{/if}}</p>';
const context = { show: true };
this.renderServerSide(template, context);
const b = blockStack();
// assert that we are in a "browser corrected" state (note the `</p>` before the `<div>world!</div>`)
this.assertServerOutput(`<p>hello ${b(1)}</p><div>world!</div>${b(1)}<p></p>`);
this.runIterations(template, context, '<p>hello <div>world!</div></p>', 100);
}
}
class ChaosMonkeyPartialRehydration extends AbstractChaosMonkeyTest {
static suiteName = 'chaos-partial-rehydration';
declare protected delegate: PartialRehydrationDelegate;
renderClientSide(componentName: string, args: Dict): void {
this.renderResult = this.delegate.renderComponentClientSide(componentName, args, this.element);
}
@test
'adjacent text nodes'() {
const args = { b: 'b', c: 'c', d: 'd' };
this.delegate.registerTemplateOnlyComponent('RehydratingComponent', 'a {{@b}}{{@c}}{{@d}}');
this.delegate.registerTemplateOnlyComponent(
'Root',
'<div><RehydratingComponent @b={{@b}} @c={{@c}} @d={{@d}}/></div>'
);
const html = this.delegate.renderComponentServerSide('Root', args);
this.assert.strictEqual(
html,
content([
OPEN,
OPEN,
'<div>',
OPEN,
'a ',
OPEN,
'b',
CLOSE,
OPEN,
'c',
CLOSE,
OPEN,
'd',
CLOSE,
CLOSE,
'</div>',
CLOSE,
CLOSE,
]),
'server html is correct'
);
replaceHTML(qunitFixture(), html);
this.element = castToSimple(castToBrowser(qunitFixture(), 'HTML').querySelector('div')!);
this.runIterations('RehydratingComponent', args, 'a bcd', 100);
}
@test
'<p> invoking a block which emits a <div>'() {
const args = { show: true };
this.delegate.registerTemplateOnlyComponent(
'RehydratingComponent',
'<p>hello {{#if @show}}<div>world!</div>{{/if}}</p>'
);
this.delegate.registerTemplateOnlyComponent(
'Root',
'<div><RehydratingComponent @show={{@show}}/></div>'
);
const html = this.delegate.renderComponentServerSide('Root', args);
this.assert.strictEqual(
html,
content([
OPEN,
OPEN,
'<div>',
OPEN,
'<p>hello ',
OPEN,
'<div>world!</div>',
CLOSE,
'</p>',
CLOSE,
'</div>',
CLOSE,
CLOSE,
])
);
replaceHTML(qunitFixture(), html);
this.element = castToSimple(castToBrowser(qunitFixture(), 'HTML').querySelector('div')!);
this.runIterations('RehydratingComponent', args, '<p>hello <div>world!</div></p>', 100);
}
}
suite(ChaosMonkeyRehydration, RehydrationDelegate);
suite(ChaosMonkeyPartialRehydration, PartialRehydrationDelegate);