@whotracksme/reporting 6.3.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,12 @@ import UrlAnalyzer from '../src/url-analyzer.js';
16
16
  import SessionStorageWrapper from '../src/session-storage.js';
17
17
  import Patterns from '../src/patterns.js';
18
18
 
19
+ function waitForPendingMicrotasks() {
20
+ return new Promise((resolve) => {
21
+ setTimeout(resolve, 0);
22
+ });
23
+ }
24
+
19
25
  class ListenerMock {
20
26
  constructor() {
21
27
  this._listeners = new Set();
@@ -118,50 +124,76 @@ class ChromeApiMock {
118
124
  // eslint-disable-next-line no-undef
119
125
  const runSelfChecks = __karma__.config.ENABLE_SELF_CHECKS;
120
126
 
121
- const history = [];
122
- for (let step = 0; step < recordedEvents.length; step += 1) {
123
- const { startedAt, api, event, args } = recordedEvents[step];
124
-
125
- // (optional) build a log of the intermediate states
126
- const stateBeforeAction = verbose
127
- ? uut.describe(startedAt)
128
- : '<unavailable: set VERBOSE_REPLAY to enable>';
129
- history.push({
130
- stateBeforeAction,
131
- step,
132
- ...recordedEvents[step],
133
- });
134
- if (history.length > 100) {
135
- history.shift();
127
+ let step;
128
+ let stopObserving = false;
129
+ const emittedPageEvents = [];
130
+ uut.addObserver((event) => {
131
+ if (stopObserving) {
132
+ console.warn(
133
+ 'page event seen after replay completed:',
134
+ JSON.stringify(event),
135
+ );
136
+ return;
136
137
  }
137
138
  if (verbose) {
138
- console.log(`--- Executing step: ${step} ---`);
139
- console.log(JSON.stringify(history.at(-1), null, 2));
139
+ console.log(
140
+ `page event triggered (step=${step}):`,
141
+ JSON.stringify(event),
142
+ );
140
143
  }
144
+ emittedPageEvents.push({ step, pageEvent: event });
145
+ });
146
+
147
+ try {
148
+ const history = [];
149
+ for (step = 0; step < recordedEvents.length; step += 1) {
150
+ const { startedAt, api, event, args } = recordedEvents[step];
151
+
152
+ // (optional) build a log of the intermediate states
153
+ const stateBeforeAction = verbose
154
+ ? uut.describe(startedAt)
155
+ : '<unavailable: set VERBOSE_REPLAY to enable>';
156
+ history.push({
157
+ stateBeforeAction,
158
+ step,
159
+ ...recordedEvents[step],
160
+ });
161
+ if (history.length > 100) {
162
+ history.shift();
163
+ }
164
+ if (verbose) {
165
+ console.log(`--- Executing step: ${step} ---`);
166
+ console.log(JSON.stringify(history.at(-1), null, 2));
167
+ }
168
+
169
+ // execute the next step (modifies the state)
170
+ this[api][event].dispatch(...args);
171
+
172
+ // (optional) run self-checks
173
+ // Warning: this is async, so it may change the observation!
174
+ if (runSelfChecks) {
175
+ const check = await uut.selfChecks();
176
+ const { status, overview, log } = check.report();
141
177
 
142
- // execute the next step (modifies the state)
143
- this[api][event].dispatch(...args);
144
-
145
- // (optional) run self-checks
146
- // Warning: this is async, so it may change the observation!
147
- if (runSelfChecks) {
148
- const check = await uut.selfChecks();
149
- const { status, overview, log } = check.report();
150
-
151
- if (status === 'FAILED') {
152
- const ppOverview = JSON.stringify(overview, null, 2);
153
- console.error(
154
- `*** self checks failed after step=${step}:\n`,
155
- ppOverview,
156
- '\n--- begin details ---:\n',
157
- JSON.stringify(log, null, 2),
158
- '\n--- end details ---',
159
- );
160
- throw new Error(
161
- `self checks failed after step=${step} (for details, see logs)`,
162
- );
178
+ if (status === 'FAILED') {
179
+ const ppOverview = JSON.stringify(overview, null, 2);
180
+ console.error(
181
+ `*** self checks failed after step=${step}:\n`,
182
+ ppOverview,
183
+ '\n--- begin details ---:\n',
184
+ JSON.stringify(log, null, 2),
185
+ '\n--- end details ---',
186
+ );
187
+ throw new Error(
188
+ `self checks failed after step=${step} (for details, see logs)`,
189
+ );
190
+ }
163
191
  }
164
192
  }
193
+ await waitForPendingMicrotasks();
194
+ return emittedPageEvents;
195
+ } finally {
196
+ stopObserving = true;
165
197
  }
166
198
  }
167
199
  }
@@ -226,7 +258,6 @@ describe('#Pages', function () {
226
258
  try {
227
259
  expect(notes, '<notes>').to.be.a('string');
228
260
  expect(expectations, '<expectations>').to.be.an('object');
229
- expect(expectations).to.contain.any.key('expectedTabs', 'activeTab');
230
261
  expect(initialState, '<events.initialState>').to.be.an('object');
231
262
  expect(recorded, '<events.recorded>').to.be.an('array');
232
263
  } catch (e) {
@@ -234,18 +265,72 @@ describe('#Pages', function () {
234
265
  throw e;
235
266
  }
236
267
 
237
- await chromeApiMock.replay(uut, initialState, recorded);
268
+ const allEmittedPageEvents = await chromeApiMock.replay(
269
+ uut,
270
+ initialState,
271
+ recorded,
272
+ );
238
273
  const state = uut.describe();
239
274
  try {
240
- const { expectedTabs, activeTab } = expectations;
275
+ const { expectedTabs, activeTab, pageEvents, ...unexpectedFields } =
276
+ expectations;
277
+ expect(unexpectedFields).to.eql({});
278
+
279
+ const pp = (x) => JSON.stringify(x, null, 2);
280
+
281
+ // Compares open tabs at the end of the scenario.
282
+ //
283
+ // Notes:
284
+ // * The given mapping from tabId to description is complete in that
285
+ // sense that all keys (tabIds) must match.
286
+ // * However, it is a partial match, since you can leave out keys
287
+ // in the page description. It will only enforce that all given
288
+ // fields exist and match exactly; but it will ignore extra keys.
289
+ //
290
+ // Example 1: two open tabs (with tab 2 and 3)
291
+ //
292
+ // "expectedTabs": {
293
+ // "2": {
294
+ // "status": "complete",
295
+ // "title": "Test page",
296
+ // "url": "https://www.example.test/",
297
+ // "windowId": 1,
298
+ // "isActive": false,
299
+ // "pageLoadMethod": "history-navigation",
300
+ // "search": {
301
+ // "category": "gh",
302
+ // "query": "testing",
303
+ // "depth": 0
304
+ // }
305
+ // },
306
+ // "3": {
307
+ // "status": "complete",
308
+ // }
309
+ // }
241
310
  if (expectedTabs) {
242
- expect(state?.openTabs).to.have.keys(Object.keys(expectedTabs));
243
- for (const [tabId, data] of Object.entries(expectedTabs)) {
244
- expect(state.openTabs[tabId]).to.deep.include(data);
311
+ const expectedTabIds = Object.keys(expectedTabs);
312
+ if (expectedTabIds.length !== 0) {
313
+ expect(state.openTabs).to.have.all.keys(expectedTabIds);
314
+ for (const [tabId, data] of Object.entries(expectedTabs)) {
315
+ expect(state.openTabs[tabId]).to.deep.include(data);
316
+ }
317
+ } else {
318
+ expect(Object.keys(state.openTabs)).to.eql([]);
245
319
  }
246
320
  }
247
321
 
248
- const pp = (x) => JSON.stringify(x, null, 2);
322
+ // Compares the active tabs at the end of the scenario.
323
+ //
324
+ // Example 1: tabId=3 is active
325
+ //
326
+ // "activeTab": {
327
+ // "tabId": 3
328
+ // }
329
+ //
330
+ // Example 2: No active tab
331
+ //
332
+ // "active": "none"
333
+ //
249
334
  if (activeTab === 'none') {
250
335
  if (state.activeTab !== undefined) {
251
336
  expect.fail(
@@ -268,6 +353,181 @@ describe('#Pages', function () {
268
353
  );
269
354
  }
270
355
  }
356
+
357
+ // Emitted page events:
358
+ //
359
+ // Notes:
360
+ // * If the ordering of "mustContain" is relevant, use "mustContainSequence"
361
+ // It is like "mustContain", but does not rewind after finding a match.
362
+ // * To remove noise in the output:
363
+ // "ignoredTypes": ["lazy-init", "page-updated", "activity-updated"]
364
+ // * Or focus on specific types with "focusType"
365
+ //
366
+ // "pageEvents": {
367
+ // // filters:
368
+ // "ignoredTypes": ["some-noisy-type"], // optional
369
+ // "focusType": ["important-type", "another-important-one"], // optional
370
+ //
371
+ // // expectations:
372
+ // "mustContain": [
373
+ // { // match exactly this message (needs to have exactly these tree fields)
374
+ // "type": "A",
375
+ // "x": "foo",
376
+ // "y": "bar"
377
+ // },
378
+ // { // match exactly this message, but it can be before "A"
379
+ // "type": "B",
380
+ // "...": "ignore", // if there are more fields, it will still match
381
+ // }
382
+ // ],
383
+ // "mustContainSequence": [
384
+ // // these must be all present and in the following order
385
+ // { "type": "first" },
386
+ // { "type": "second" },
387
+ // { "type": "third" }
388
+ // ]
389
+ // "mustNotContain": [
390
+ // {
391
+ // "type": "unexpected.signal",
392
+ // "...": "ignore"
393
+ // },
394
+ // {
395
+ // "x": "bad-value"
396
+ // "...": "ignore"
397
+ // }
398
+ // ],
399
+ // "counts": {
400
+ // "first": 1, // there was exactly one message of type "first"
401
+ // "second": 1,
402
+ // "third": 1,
403
+ // }
404
+ // }
405
+ if (pageEvents) {
406
+ const matches = (expectedPageEvent) => {
407
+ let shrink;
408
+ if (expectedPageEvent['...'] === 'ignore') {
409
+ expectedPageEvent = { ...expectedPageEvent };
410
+ delete expectedPageEvent['...'];
411
+ const focusedKeys = Object.keys(expectedPageEvent);
412
+
413
+ shrink = (fullPageEvent) => {
414
+ const obj = {};
415
+ focusedKeys.forEach((key) => (obj[key] = fullPageEvent[key]));
416
+ return obj;
417
+ };
418
+ } else {
419
+ shrink = (fullPageEvent) => fullPageEvent;
420
+ }
421
+
422
+ return ({ pageEvent }) => {
423
+ const actual = shrink(pageEvent);
424
+ try {
425
+ expect(actual).to.eql(expectedPageEvent);
426
+ return true;
427
+ } catch (e) {
428
+ return false;
429
+ }
430
+ };
431
+ };
432
+
433
+ const {
434
+ // Optional filters. To filter events before, or simplify to remove
435
+ // noise and make error messages for failed tests more readable.
436
+ focusedTypes = [],
437
+ ignoredTypes = [],
438
+
439
+ // checks:
440
+ mustContain,
441
+ mustContainSequence,
442
+ mustNotContain,
443
+ counts,
444
+ } = pageEvents;
445
+ let emittedPageEvents = [...allEmittedPageEvents];
446
+ if (focusedTypes.length > 0) {
447
+ const isFocused = ({ pageEvent }) =>
448
+ focusedTypes.includes(pageEvent.type);
449
+ emittedPageEvents = emittedPageEvents.filter(isFocused);
450
+ } else if (ignoredTypes.length > 0) {
451
+ const isIgnored = ({ pageEvent }) =>
452
+ ignoredTypes.includes(pageEvent.type);
453
+ emittedPageEvents = emittedPageEvents.filter((x) => !isIgnored(x));
454
+ }
455
+ if (mustContain) {
456
+ expect(mustContain, '<expectations.mustContain>').to.be.an('array');
457
+ for (const check of mustContain) {
458
+ if (!emittedPageEvents.some(matches(check))) {
459
+ expect.fail(
460
+ `Failed to find matching page event.\n\n` +
461
+ `List of all events:\n${pp(allEmittedPageEvents)}\n\n` +
462
+ `----------------------------------------------------------------------\n\n` +
463
+ `List of events after filter/focus:\n${pp(
464
+ emittedPageEvents,
465
+ )}\n\n` +
466
+ `Expected to find a signal that satisfies: ${pp(check)}\n` +
467
+ `Hint: if you want to ignore missing fields, use { "...": "ignore" }`,
468
+ );
469
+ }
470
+ }
471
+ }
472
+ if (mustContainSequence) {
473
+ expect(
474
+ mustContainSequence,
475
+ '<expectations.mustContainSequence>',
476
+ ).to.be.an('array');
477
+ let remainingEvents = [...emittedPageEvents];
478
+ for (const check of mustContainSequence) {
479
+ const isMatch = matches(check);
480
+ for (;;) {
481
+ const event = remainingEvents.shift();
482
+ if (!event) {
483
+ expect.fail(
484
+ `Failed to find matching sequence.\n\n` +
485
+ `List of events after filter/focus:\n` +
486
+ `${pp(emittedPageEvents)}\n\n` +
487
+ `Expected to find a signal that satisfies: ${pp(
488
+ check,
489
+ )}\n` +
490
+ `Hint: if you want to ignore missing fields, use { "...": "ignore" }`,
491
+ );
492
+ }
493
+ if (isMatch(event)) {
494
+ break;
495
+ }
496
+ }
497
+ }
498
+ }
499
+ if (mustNotContain) {
500
+ expect(mustNotContain, '<expectations.mustNotContain>').to.be.an(
501
+ 'array',
502
+ );
503
+ for (const check of mustNotContain) {
504
+ const unexpectedEvent = emittedPageEvents.find(matches(check));
505
+ if (unexpectedEvent) {
506
+ const event = pp(unexpectedEvent);
507
+ expect.fail(
508
+ `Found unexpected page event:${event}\n\nIt matches: ${pp(
509
+ check,
510
+ )}`,
511
+ );
512
+ }
513
+ }
514
+ }
515
+ if (counts) {
516
+ expect(counts, '<expectations.counts>').to.be.an('object');
517
+ for (const [eventType, expectedCount] of Object.entries(counts)) {
518
+ const events = allEmittedPageEvents.filter(
519
+ (x) => x.pageEvent.type === eventType,
520
+ );
521
+ if (events.length !== expectedCount) {
522
+ expect.fail(
523
+ `List of all matching page events that have been found:\n` +
524
+ JSON.stringify(events, null, 2) +
525
+ `\n\nExpected ${expectedCount} of type ${eventType}, but found ${events.length}.`,
526
+ );
527
+ }
528
+ }
529
+ }
530
+ }
271
531
  } catch (e) {
272
532
  e.results = state;
273
533
  throw e;
@@ -552,18 +812,22 @@ describe('#Pages', function () {
552
812
  console.log(`test ${name}: PASSED`);
553
813
  } catch (e) {
554
814
  testsFailed.push({ name, error: e });
555
- e.message = `Test fixture <${name}> failed: ${e}`;
815
+ e.message = `Test fixture <${name}> failed: ${e}\n\nTest fixture <${name}>`;
556
816
  console.error(e);
557
817
  if (e.results) {
558
818
  console.log(`This was the scenario (${name}):\n
559
- ----------------------------------------------------------------------
560
- ${JSON.stringify(fixture.scenario.expectations, null, 2)}
561
- ----------------------------------------------------------------------
819
+ ---------------------- begin scenario notes --------------------------
820
+ ${fixture.scenario?.notes || '<missing>'}
821
+ ----------------------- end scenario notes --------------------------
822
+
823
+ -------------------- begin scenario expectations ---------------------
824
+ ${JSON.stringify(fixture.scenario?.expectations || '<missing>', null, 2)}
825
+ --------------------- end scenario expectations ----------------------
562
826
 
563
827
  But this was the actual state:\n
564
- ----------------------------------------------------------------------
828
+ --------------------- begin actual state -----------------------------
565
829
  ${JSON.stringify(e.results, null, 2)}
566
- ----------------------------------------------------------------------
830
+ ---------------------- end actual state ------------------------------
567
831
  `);
568
832
  }
569
833
  }
@@ -1,62 +0,0 @@
1
- {
2
- "search-go": {
3
- "doublefetch": {
4
- "headers": {
5
- "Cookie": "CONSENT=YES+cb-m.20220301-1-p0.de+FX+1;"
6
- },
7
- "followRedirects": true
8
- },
9
- "input": {
10
- "#main div[data-text-ad=\"1\"]": {
11
- "all": {
12
- "u": {
13
- "select": "a div[role=\"link\"]",
14
- "attr": "aria-label"
15
- },
16
- "t": {
17
- "select": "a div[role=\"heading\"] > span",
18
- "attr": "textContent"
19
- }
20
- }
21
- }
22
- },
23
- "output": {
24
- "hwlite.query0": {
25
- "fields": [
26
- {
27
- "key": "q"
28
- },
29
- {
30
- "key": "qurl"
31
- },
32
- {
33
- "key": "ctry"
34
- }
35
- ],
36
- "deduplicateBy": "q"
37
- },
38
- "hwlite.ads_A": {
39
- "fields": [
40
- {
41
- "key": "r",
42
- "source": "#main div[data-text-ad=\"1\"]",
43
- "requiredKeys": [
44
- "t",
45
- "u"
46
- ]
47
- },
48
- {
49
- "key": "q"
50
- },
51
- {
52
- "key": "qurl"
53
- },
54
- {
55
- "key": "ctry"
56
- }
57
- ],
58
- "deduplicateBy": "q"
59
- }
60
- }
61
- }
62
- }