summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/tests/utils/TelemetryTestUtils.sys.mjs
blob: 9e608c1c5e154761cb575452a39111160ee1b228 (plain)
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

import { Assert } from "resource://testing-common/Assert.sys.mjs";

export var TelemetryTestUtils = {
  /* Scalars */

  /**
   * A helper that asserts the value of a scalar.
   *
   * @param {Object} scalars The snapshot of the scalars.
   * @param {String} scalarName The name of the scalar to check.
   * @param {Boolean|Number|String} value The expected value for the scalar.
   * @param {String} msg The message to print when checking the value.
   */
  assertScalar(scalars, scalarName, value, msg) {
    Assert.equal(scalars[scalarName], value, msg);
  },

  /**
   * A helper that asserts a scalar is not set.
   *
   * @param {Object} scalars The snapshot of the scalars.
   * @param {String} scalarName The name of the scalar to check.
   */
  assertScalarUnset(scalars, scalarName) {
    Assert.ok(!(scalarName in scalars), scalarName + " must not be reported.");
  },

  /**
   * Asserts if the snapshotted keyed scalars contain the expected
   * data.
   *
   * @param {Object} scalars The snapshot of the keyed scalars.
   * @param {String} scalarName The name of the keyed scalar to check.
   * @param {String} key The key that must be within the keyed scalar.
   * @param {String|Boolean|Number} expectedValue The expected value for the
   *        provided key in the scalar.
   */
  assertKeyedScalar(scalars, scalarName, key, expectedValue) {
    Assert.ok(scalarName in scalars, scalarName + " must be recorded.");
    Assert.ok(
      key in scalars[scalarName],
      scalarName + " must contain the '" + key + "' key."
    );
    Assert.equal(
      scalars[scalarName][key],
      expectedValue,
      scalarName + "['" + key + "'] must contain the expected value"
    );
  },

  /**
   * Returns a snapshot of scalars from the specified process.
   *
   * @param {String} aProcessName Name of the process. Could be parent or
   *   something else.
   * @param {boolean} [aKeyed] Set to true if keyed scalars rather than normal
   *   scalars should be snapshotted.
   * @param {boolean} [aClear] Set to true to clear the scalars once the snapshot
   *   has been obtained.
   * @param {Number} aChannel The channel dataset type from nsITelemetry.
   * @returns {Object} The snapshotted scalars from the parent process.
   */
  getProcessScalars(
    aProcessName,
    aKeyed = false,
    aClear = false,
    aChannel = Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS
  ) {
    const extended = aChannel == Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS;
    const currentExtended = Services.telemetry.canRecordExtended;
    Services.telemetry.canRecordExtended = extended;
    const scalars = aKeyed
      ? Services.telemetry.getSnapshotForKeyedScalars("main", aClear)[
          aProcessName
        ]
      : Services.telemetry.getSnapshotForScalars("main", aClear)[aProcessName];
    Services.telemetry.canRecordExtended = currentExtended;
    return scalars || {};
  },

  /* Events */

  /**
   * Asserts that the number of events, after filtering, is equal to numEvents.
   *
   * @param {Number} numEvents The number of events to assert.
   * @param {Object} filter As per assertEvents.
   * @param {Object} options As per assertEvents.
   */
  assertNumberOfEvents(numEvents, filter, options) {
    // Create an array of empty objects of length numEvents
    TelemetryTestUtils.assertEvents(
      Array.from({ length: numEvents }, () => ({})),
      filter,
      options
    );
  },

  /**
   * Returns the events in a snapshot, after optional filtering.
   *
   * @param {Object} filter An object of strings or RegExps for first filtering
   *                 the event snapshot. Of the form {category, method, object}.
   *                 Absent filters filter nothing.
   * @param {Object} options An object containing any of
   *                     - process {string} the process to examine. Default parent.
   */
  getEvents(filter = {}, { process = "parent" } = {}) {
    // Step 0: Snapshot and clear.
    let snapshots = Services.telemetry.snapshotEvents(
      Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS,
      false
    );

    if (!(process in snapshots)) {
      return [];
    }

    let snapshot = snapshots[process];

    // Step 1: Filter.
    // Shared code with the below function
    let {
      category: filterCategory,
      method: filterMethod,
      object: filterObject,
    } = filter;
    let matches = (expected, actual) => {
      if (expected === undefined) {
        return true;
      } else if (expected && expected.test) {
        // Possibly a RegExp.
        return expected.test(actual);
      } else if (typeof expected === "function") {
        return expected(actual);
      }
      return expected === actual;
    };

    return snapshot
      .map(([, /* timestamp */ category, method, object, value, extra]) => {
        // We don't care about the `timestamp` value.
        // Tests that examine that value should use `snapshotEvents` directly.
        return [category, method, object, value, extra];
      })
      .filter(([category, method, object]) => {
        return (
          matches(filterCategory, category) &&
          matches(filterMethod, method) &&
          matches(filterObject, object)
        );
      })
      .map(([category, method, object, value, extra]) => {
        return { category, method, object, value, extra };
      });
  },

  /**
   * Asserts that, after optional filtering, the current events snapshot
   * matches expectedEvents.
   *
   * @param {Array} expectedEvents An array of event structures of the form
   *                [category, method, object, value, extra]
   *                or the same as an object with fields named as above.
   *                The array can be empty to assert that there are no events
   *                that match the filter.
   *                Each field can be absent/undefined (to match
   *                everything), a string or null (to match that value), a
   *                RegExp to match what it can match, or a function which
   *                matches by returning true when called with the field.
   *                `extra` is slightly different. If present it must be an
   *                object whose fields are treated the same way as the others.
   * @param {Object} filter An object of strings or RegExps for first filtering
   *                 the event snapshot. Of the form {category, method, object}.
   *                 Absent filters filter nothing.
   * @param {Object} options An object containing any of
   *                     - clear {bool} clear events. Default true.
   *                     - process {string} the process to examine. Default parent.
   */
  assertEvents(
    expectedEvents,
    filter = {},
    { clear = true, process = "parent" } = {}
  ) {
    // Step 0: Snapshot and clear.
    let snapshots = Services.telemetry.snapshotEvents(
      Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS,
      clear
    );
    if (expectedEvents.length === 0 && !(process in snapshots)) {
      // Job's done!
      return;
    }
    Assert.ok(
      process in snapshots,
      `${process} must be in snapshot. Has [${Object.keys(snapshots)}].`
    );
    let snapshot = snapshots[process];

    // Step 1: Filter.
    // Shared code with the above function
    let {
      category: filterCategory,
      method: filterMethod,
      object: filterObject,
    } = filter;
    let matches = (expected, actual) => {
      if (expected === undefined) {
        return true;
      } else if (expected && expected.test) {
        // Possibly a RegExp.
        return expected.test(actual);
      } else if (typeof expected === "function") {
        return expected(actual);
      }
      return expected === actual;
    };

    let filtered = snapshot
      .map(([, /* timestamp */ category, method, object, value, extra]) => {
        // We don't care about the `timestamp` value.
        // Tests that examine that value should use `snapshotEvents` directly.
        return [category, method, object, value, extra];
      })
      .filter(([category, method, object]) => {
        return (
          matches(filterCategory, category) &&
          matches(filterMethod, method) &&
          matches(filterObject, object)
        );
      });

    // Step 2: Match.
    Assert.equal(
      filtered.length,
      expectedEvents.length,
      `After filtering we must have the expected number of events. Filtered events: ${JSON.stringify(
        filtered
      )}`
    );
    if (expectedEvents.length === 0) {
      // Job's done!
      return;
    }

    // Transform object-type expected events to array-type to match snapshot.
    if (!Array.isArray(expectedEvents[0])) {
      expectedEvents = expectedEvents.map(
        ({ category, method, object, value, extra }) => [
          category,
          method,
          object,
          value,
          extra,
        ]
      );
    }

    const FIELD_NAMES = ["category", "method", "object", "value", "extra"];
    const EXTRA_INDEX = 4;
    for (let i = 0; i < expectedEvents.length; ++i) {
      let expected = expectedEvents[i];
      let actual = filtered[i];

      // Match everything up to `extra`
      for (let j = 0; j < EXTRA_INDEX; ++j) {
        if (expected[j] === undefined) {
          // Don't spam the assert log with unspecified fields.
          continue;
        }
        Assert.report(
          !matches(expected[j], actual[j]),
          actual[j],
          expected[j],
          `${FIELD_NAMES[j]} in event ${actual[0]}#${actual[1]}#${actual[2]} must match.`,
          "matches"
        );
      }

      // Match extra
      if (
        expected.length > EXTRA_INDEX &&
        expected[EXTRA_INDEX] !== undefined
      ) {
        Assert.ok(
          actual.length > EXTRA_INDEX,
          `Actual event ${actual[0]}#${actual[1]}#${actual[2]} expected to have extra.`
        );
        let expectedExtra = expected[EXTRA_INDEX];
        let actualExtra = actual[EXTRA_INDEX];
        for (let [key, value] of Object.entries(expectedExtra)) {
          Assert.ok(
            key in actualExtra,
            `Expected key ${key} must be in actual extra. Actual keys: [${Object.keys(
              actualExtra
            )}].`
          );
          Assert.report(
            !matches(value, actualExtra[key]),
            actualExtra[key],
            value,
            `extra[${key}] must match in event ${actual[0]}#${actual[1]}#${actual[2]}.`,
            "matches"
          );
        }
      }
    }
  },

  /* Histograms */

  /**
   * Clear and get the named histogram.
   *
   * @param {String} name The name of the histogram
   * @returns {Object} The obtained histogram.
   */
  getAndClearHistogram(name) {
    let histogram = Services.telemetry.getHistogramById(name);
    histogram.clear();
    return histogram;
  },

  /**
   * Clear and get the named keyed histogram.
   *
   * @param {String} name The name of the keyed histogram
   * @returns {Object} The obtained keyed histogram.
   */
  getAndClearKeyedHistogram(name) {
    let histogram = Services.telemetry.getKeyedHistogramById(name);
    histogram.clear();
    return histogram;
  },

  /**
   * Assert that the histogram index is the right value. It expects that
   * other indexes are all zero.
   *
   * @param {Object} histogram The histogram to check.
   * @param {Number} index The index to check against the expected value.
   * @param {Number} expected The expected value of the index.
   */
  assertHistogram(histogram, index, expected) {
    const snapshot = histogram.snapshot();
    let found = false;
    for (let [i, val] of Object.entries(snapshot.values)) {
      if (i == index) {
        found = true;
        Assert.equal(
          val,
          expected,
          `expected counts should match for ${histogram.name()} at index ${i}`
        );
      } else {
        Assert.equal(
          val,
          0,
          `unexpected counts should be zero for ${histogram.name()} at index ${i}`
        );
      }
    }
    Assert.ok(
      found,
      `Should have found an entry for ${histogram.name()} at index ${index}`
    );
  },

  /**
   * Assert that a key within a keyed histogram contains the required sum.
   *
   * @param {Object} histogram The keyed histogram to check.
   * @param {String} key The key to check.
   * @param {Number} [expected] The expected sum for the key.
   */
  assertKeyedHistogramSum(histogram, key, expected) {
    const snapshot = histogram.snapshot();
    if (expected === undefined) {
      Assert.ok(
        !(key in snapshot),
        `The histogram ${histogram.name()} must not contain ${key}.`
      );
      return;
    }
    Assert.ok(
      key in snapshot,
      `The histogram ${histogram.name()} must contain ${key}.`
    );
    Assert.equal(
      snapshot[key].sum,
      expected,
      `The key ${key} must contain the expected sum in ${histogram.name()}.`
    );
  },

  /**
   * Assert that the value of a key within a keyed histogram is the right value.
   * It expects that other values are all zero.
   *
   * @param {Object} histogram The keyed histogram to check.
   * @param {String} key The key to check.
   * @param {Number} index The index to check against the expected value.
   * @param {Number} [expected] The expected values for the key.
   */
  assertKeyedHistogramValue(histogram, key, index, expected) {
    const snapshot = histogram.snapshot();
    if (!(key in snapshot)) {
      Assert.ok(false, `The histogram ${histogram.name()} must contain ${key}`);
      return;
    }
    for (let [i, val] of Object.entries(snapshot[key].values)) {
      if (i == index) {
        Assert.equal(
          val,
          expected,
          `expected counts should match for ${histogram.name()} at index ${i}`
        );
      } else {
        Assert.equal(
          val,
          0,
          `unexpected counts should be zero for ${histogram.name()} at index ${i}`
        );
      }
    }
  },
};