-
Notifications
You must be signed in to change notification settings - Fork 287
/
Copy pathtest-adapter.js
348 lines (302 loc) · 8.91 KB
/
test-adapter.js
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* eslint-disable no-console */
import QUnit from 'qunit';
import { next } from '@ember/runloop';
import BasicAdapter from 'ember-inspector/services/adapters/basic';
import { settled } from '@ember/test-helpers';
let adapter = null;
let resourcesEnabled = false;
let resources = [];
let responders = [];
export function setupTestAdapter(hooks) {
// Some default responders that are part of the normal application boot cycle
hooks.beforeEach(function () {
respondWith('check-version', false, { isDefault: true });
respondWith(
'general:applicationBooted',
{
type: 'general:applicationBooted',
applicationId: 'my-app',
applicationName: 'My App',
booted: true,
},
{ isDefault: true }
);
respondWith(
'app-picker-loaded',
{
type: 'apps-loaded',
applicationId: null,
applicationName: null,
apps: [
{
applicationId: 'my-app',
applicationName: 'My App',
},
],
},
{ isDefault: true }
);
respondWith('app-selected', false, { isDefault: true });
respondWith(
'deprecation:getCount',
({ applicationId, applicationName }) => ({
type: 'deprecation:count',
applicationId,
applicationName,
count: 0,
}),
{ isDefault: true }
);
});
// Ensure all expectations are met and reset the global states
hooks.afterEach(function (assert) {
for (let { file, line, actual, expected, reject } of resources) {
if (!isNaN(expected) && actual !== expected) {
assert.strictEqual(
actual,
expected,
`Expceting resouce ${file}:${line} to be opened ${expected} time(s)`
);
reject(
`Expceting resouce ${file}:${line} to be opened ${expected} time(s), was opened ${actual} time(s)`
);
}
}
for (let { type, isDefault, actual, expected, reject } of responders) {
if (!isDefault && !isNaN(expected) && actual !== expected) {
assert.strictEqual(
actual,
expected,
`The correct amount of ${type} messages are sent`
);
reject(`Expecting ${expected} ${type} messages, got ${actual}`);
}
}
adapter = null;
resourcesEnabled = false;
resources.length = 0;
responders.length = 0;
});
}
/**
* Allow `openResouce` to be called on the adapter.
*
* @method enableOpenResource
*/
export function enableOpenResource() {
resourcesEnabled = true;
}
/**
* Expect `openResouce` to be called on the adapter with a specific filename and
* line number. Must call `enableOpenResource` first.
*
* @method expectOpenResource
* @param {String} file The filename.
* @param {number} line The line number.
* @param {Object} options
* - {number | false} count How many calls to allow. `false` for unlimited.
* Defaults to 1.
* @return {Promise} Resolves when all the expected calls are made, or
* rejects at the end of the current test if not called
* enough times.
*/
export function expectOpenResource(file, line, options = {}) {
if (!resourcesEnabled) {
throw new Error('call enableOpenResource first');
}
return new Promise((resolve, reject) => {
let { count } = { count: 1, ...options };
resources.push({
file,
line,
actual: 0,
expected: count === false ? NaN : count,
resolve,
reject,
});
});
}
/**
* Send a message to the adapter.
*
* @method expectOpenResource
* @param {Object} message The message.
* @return {Promise} Resolves when the message is delivered.
*/
export async function sendMessage(message) {
if (adapter === null) {
throw new Error('Cannot call sendMessage outside of a test');
}
const msg = await new Promise((resolve, reject) => {
next(async () => {
let normalized = {
applicationId: 'my-app',
applicationName: 'My App',
...message,
from: 'inspectedWindow',
};
try {
adapter._messageReceived(normalized);
} catch (e) {
return reject(e);
}
resolve(normalized);
});
});
await settled();
return msg;
}
/**
* Expect a message from the adapter of the given type, and respond to the message
* with the given payload.
*
* @method respondWith
* @param {String} type The incoming message type.
* @param { false | Object | Function } payload The payload.
* - Pass `false` to acknoledge the message but don't send a response.
* - Pass an object to send a response (`message` parameter of `sendMessage`).
* - Pass a callback to dynamically respond with one of the above, or `undefined`,
* in which case the incoming messages is considered unhandled and the remaining
* responders will be tried instead. The callback is given the incoming message
* as an argument.
* @param {Object} options
* - {number | false} count How many calls to allow. `false` for unlimited.
* Defaults to 1.
* @return {Promise} Resolves when all the expected calls are made, or
* rejects at the end of the current test if not called
* enough times.
*/
export function respondWith(type, payload, options = {}) {
return new Promise((resolve, reject) => {
let { count, isDefault } = { count: 1, isDefault: false, ...options };
let callback = typeof payload === 'function' ? payload : () => payload;
responders.push({
type,
isDefault,
callback,
actual: 0,
expected: count === false ? NaN : count,
resolve,
reject,
});
});
}
/**
* Disable the default responder for the given type.
*
* @method disableDefaultResponseFor
*/
export function disableDefaultResponseFor(type) {
for (let [i, responder] of responders.entries()) {
if (responder.type === type && responder.isDefault) {
if (responder.actual > 0) {
throw new Error(
`Cannot remove default responder for ${type}: a response has already been sent!`
);
}
responders.splice(i, 1);
return;
}
}
throw new Error(
`Cannot remove default responder for ${type}: no such responder!`
);
}
export default class TestAdapter extends BasicAdapter {
constructor() {
super(...arguments);
adapter = this;
}
get name() {
return 'test';
}
get canOpenResource() {
return resourcesEnabled;
}
openResource(file, line) {
if (!resourcesEnabled) {
throw new Error('openResource called unexpectedly');
}
console.debug('Opening resource', { file, line });
if (!file) {
QUnit.assert.ok(
file,
`resource has valid "file" field: ${JSON.stringify(file)}`
);
return;
}
if (!line) {
QUnit.assert.ok(
file,
`resource has valid "line" field: ${JSON.stringify(line)}`
);
return;
}
for (let resource of resources) {
let { actual, expected, resolve } = resource;
if (actual === expected) {
continue;
}
if (file === resource.file && line === resource.line) {
console.debug('Opened resource', { file, line });
resource.actual = ++actual;
resolve();
return;
}
}
console.error('Unknown resource', { file, line });
QUnit.assert.deepEqual({ file, line }, {}, 'Unknown resource');
}
sendMessage(message) {
console.debug('Sending message (devtools -> inspectedWindow)', message);
if (!message.type) {
QUnit.assert.ok(
false,
`message has valid "type" field: ${JSON.stringify(message)}`
);
return;
}
if (message.from !== 'devtools') {
QUnit.assert.strictEqual(
message.from,
'devtools',
`message has valid "from" field: ${JSON.stringify(message)}`
);
return;
}
for (let responder of responders) {
let { type, callback, actual, expected, resolve } = responder;
if (actual === expected) {
continue;
}
if (type === message.type) {
let response = callback(message);
if (response !== undefined) {
responder.actual = ++actual;
}
let didRespond;
if (response) {
console.debug(
'Received response (inspectedWindow -> devtools)',
response
);
didRespond = sendMessage(response);
} else if (response === false) {
console.debug(
'Ignoreing message (devtools -> inspectedWindow)',
message
);
didRespond = Promise.resolve();
}
if (didRespond) {
if (actual === expected) {
didRespond.then(resolve);
}
return;
}
}
}
console.error('Unexpected message', message);
QUnit.assert.deepEqual(message, {}, 'Unexpected message');
}
}