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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
|
import {
ASRouterTargeting,
CachedTargetingGetter,
getSortedMessages,
QueryCache,
} from "lib/ASRouterTargeting.jsm";
import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
import { ASRouterPreferences } from "lib/ASRouterPreferences.jsm";
import { GlobalOverrider } from "test/unit/utils";
// Note that tests for the ASRouterTargeting environment can be found in
// test/functional/mochitest/browser_asrouter_targeting.js
describe("#CachedTargetingGetter", () => {
const sixHours = 6 * 60 * 60 * 1000;
let sandbox;
let clock;
let frecentStub;
let topsitesCache;
let globals;
let doesAppNeedPinStub;
let getAddonsByTypesStub;
beforeEach(() => {
sandbox = sinon.createSandbox();
clock = sinon.useFakeTimers();
frecentStub = sandbox.stub(
global.NewTabUtils.activityStreamProvider,
"getTopFrecentSites"
);
topsitesCache = new CachedTargetingGetter("getTopFrecentSites");
globals = new GlobalOverrider();
globals.set(
"TargetingContext",
class {
static combineContexts(...args) {
return sinon.stub();
}
evalWithDefault(expr) {
return sinon.stub();
}
}
);
doesAppNeedPinStub = sandbox.stub().resolves();
getAddonsByTypesStub = sandbox.stub().resolves();
});
afterEach(() => {
sandbox.restore();
clock.restore();
globals.restore();
});
it("should cache allow for optional getter argument", async () => {
let pinCachedGetter = new CachedTargetingGetter(
"doesAppNeedPin",
true,
undefined,
{ doesAppNeedPin: doesAppNeedPinStub }
);
// Need to tick forward because Date.now() is stubbed
clock.tick(sixHours);
await pinCachedGetter.get();
await pinCachedGetter.get();
await pinCachedGetter.get();
// Called once; cached request
assert.calledOnce(doesAppNeedPinStub);
// Called with option argument
assert.calledWith(doesAppNeedPinStub, true);
// Expire and call again
clock.tick(sixHours);
await pinCachedGetter.get();
// Call goes through
assert.calledTwice(doesAppNeedPinStub);
let themesCachedGetter = new CachedTargetingGetter(
"getAddonsByTypes",
["foo"],
undefined,
{ getAddonsByTypes: getAddonsByTypesStub }
);
// Need to tick forward because Date.now() is stubbed
clock.tick(sixHours);
await themesCachedGetter.get();
await themesCachedGetter.get();
await themesCachedGetter.get();
// Called once; cached request
assert.calledOnce(getAddonsByTypesStub);
// Called with option argument
assert.calledWith(getAddonsByTypesStub, ["foo"]);
// Expire and call again
clock.tick(sixHours);
await themesCachedGetter.get();
// Call goes through
assert.calledTwice(getAddonsByTypesStub);
});
it("should only make a request every 6 hours", async () => {
frecentStub.resolves();
clock.tick(sixHours);
await topsitesCache.get();
await topsitesCache.get();
assert.calledOnce(
global.NewTabUtils.activityStreamProvider.getTopFrecentSites
);
clock.tick(sixHours);
await topsitesCache.get();
assert.calledTwice(
global.NewTabUtils.activityStreamProvider.getTopFrecentSites
);
});
it("throws when failing getter", async () => {
frecentStub.rejects(new Error("fake error"));
clock.tick(sixHours);
// assert.throws expect a function as the first parameter, try/catch is a
// workaround
let rejected = false;
try {
await topsitesCache.get();
} catch (e) {
rejected = true;
}
assert(rejected);
});
describe("sortMessagesByPriority", () => {
it("should sort messages in descending priority order", async () => {
const [m1, m2, m3 = { id: "m3" }] =
await OnboardingMessageProvider.getUntranslatedMessages();
const checkMessageTargetingStub = sandbox
.stub(ASRouterTargeting, "checkMessageTargeting")
.resolves(false);
sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
await ASRouterTargeting.findMatchingMessage({
messages: [
{ ...m1, priority: 0 },
{ ...m2, priority: 1 },
{ ...m3, priority: 2 },
],
trigger: "testing",
});
assert.equal(checkMessageTargetingStub.callCount, 3);
const [arg_m1] = checkMessageTargetingStub.firstCall.args;
assert.equal(arg_m1.id, m3.id);
const [arg_m2] = checkMessageTargetingStub.secondCall.args;
assert.equal(arg_m2.id, m2.id);
const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
assert.equal(arg_m3.id, m1.id);
});
it("should sort messages with no priority last", async () => {
const [m1, m2, m3 = { id: "m3" }] =
await OnboardingMessageProvider.getUntranslatedMessages();
const checkMessageTargetingStub = sandbox
.stub(ASRouterTargeting, "checkMessageTargeting")
.resolves(false);
sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
await ASRouterTargeting.findMatchingMessage({
messages: [
{ ...m1, priority: 0 },
{ ...m2, priority: undefined },
{ ...m3, priority: 2 },
],
trigger: "testing",
});
assert.equal(checkMessageTargetingStub.callCount, 3);
const [arg_m1] = checkMessageTargetingStub.firstCall.args;
assert.equal(arg_m1.id, m3.id);
const [arg_m2] = checkMessageTargetingStub.secondCall.args;
assert.equal(arg_m2.id, m1.id);
const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
assert.equal(arg_m3.id, m2.id);
});
it("should keep the order of messages with same priority unchanged", async () => {
const [m1, m2, m3 = { id: "m3" }] =
await OnboardingMessageProvider.getUntranslatedMessages();
const checkMessageTargetingStub = sandbox
.stub(ASRouterTargeting, "checkMessageTargeting")
.resolves(false);
sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
await ASRouterTargeting.findMatchingMessage({
messages: [
{ ...m1, priority: 2, targeting: undefined, rank: 1 },
{ ...m2, priority: undefined, targeting: undefined, rank: 1 },
{ ...m3, priority: 2, targeting: undefined, rank: 1 },
],
trigger: "testing",
});
assert.equal(checkMessageTargetingStub.callCount, 3);
const [arg_m1] = checkMessageTargetingStub.firstCall.args;
assert.equal(arg_m1.id, m1.id);
const [arg_m2] = checkMessageTargetingStub.secondCall.args;
assert.equal(arg_m2.id, m3.id);
const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
assert.equal(arg_m3.id, m2.id);
});
});
});
describe("#isTriggerMatch", () => {
let trigger;
let message;
beforeEach(() => {
trigger = { id: "openURL" };
message = { id: "openURL" };
});
it("should return false if trigger and candidate ids are different", () => {
trigger.id = "trigger";
message.id = "message";
assert.isFalse(ASRouterTargeting.isTriggerMatch(trigger, message));
assert.isTrue(
ASRouterTargeting.isTriggerMatch({ id: "foo" }, { id: "foo" })
);
});
it("should return true if the message we check doesn't have trigger params or patterns", () => {
// No params or patterns defined
assert.isTrue(ASRouterTargeting.isTriggerMatch(trigger, message));
});
it("should return false if the trigger does not have params defined", () => {
message.params = {};
// trigger.param is undefined
assert.isFalse(ASRouterTargeting.isTriggerMatch(trigger, message));
});
it("should return true if message params includes trigger host", () => {
message.params = ["mozilla.org"];
trigger.param = { host: "mozilla.org" };
assert.isTrue(ASRouterTargeting.isTriggerMatch(trigger, message));
});
it("should return true if message params includes trigger param.type", () => {
message.params = ["ContentBlockingMilestone"];
trigger.param = { type: "ContentBlockingMilestone" };
assert.isTrue(Boolean(ASRouterTargeting.isTriggerMatch(trigger, message)));
});
it("should return true if message params match trigger mask", () => {
// STATE_BLOCKED_FINGERPRINTING_CONTENT
message.params = [0x00000040];
trigger.param = { type: 538091584 };
assert.isTrue(Boolean(ASRouterTargeting.isTriggerMatch(trigger, message)));
});
});
describe("#CacheListAttachedOAuthClients", () => {
const fourHours = 4 * 60 * 60 * 1000;
let sandbox;
let clock;
let fakeFxAccount;
let authClientsCache;
let globals;
beforeEach(() => {
globals = new GlobalOverrider();
sandbox = sinon.createSandbox();
clock = sinon.useFakeTimers();
fakeFxAccount = {
listAttachedOAuthClients: () => {},
};
globals.set("fxAccounts", fakeFxAccount);
authClientsCache = QueryCache.queries.ListAttachedOAuthClients;
sandbox
.stub(global.fxAccounts, "listAttachedOAuthClients")
.returns(Promise.resolve({}));
});
afterEach(() => {
authClientsCache.expire();
sandbox.restore();
clock.restore();
});
it("should only make additional request every 4 hours", async () => {
clock.tick(fourHours);
await authClientsCache.get();
assert.calledOnce(global.fxAccounts.listAttachedOAuthClients);
clock.tick(fourHours);
await authClientsCache.get();
assert.calledTwice(global.fxAccounts.listAttachedOAuthClients);
});
it("should not make additional request before 4 hours", async () => {
clock.tick(fourHours);
await authClientsCache.get();
assert.calledOnce(global.fxAccounts.listAttachedOAuthClients);
await authClientsCache.get();
assert.calledOnce(global.fxAccounts.listAttachedOAuthClients);
});
});
describe("ASRouterTargeting", () => {
let evalStub;
let sandbox;
let clock;
let globals;
let fakeTargetingContext;
beforeEach(() => {
sandbox = sinon.createSandbox();
sandbox.replace(ASRouterTargeting, "Environment", {});
clock = sinon.useFakeTimers();
fakeTargetingContext = {
combineContexts: sandbox.stub(),
evalWithDefault: sandbox.stub().resolves(),
setTelemetrySource: sandbox.stub(),
};
globals = new GlobalOverrider();
globals.set(
"TargetingContext",
class {
static combineContexts(...args) {
return fakeTargetingContext.combineContexts.apply(sandbox, args);
}
setTelemetrySource(id) {
fakeTargetingContext.setTelemetrySource(id);
}
evalWithDefault(expr) {
return fakeTargetingContext.evalWithDefault(expr);
}
}
);
evalStub = fakeTargetingContext.evalWithDefault;
});
afterEach(() => {
clock.restore();
sandbox.restore();
globals.restore();
});
it("should provide message.id as source", async () => {
await ASRouterTargeting.checkMessageTargeting(
{
id: "message",
targeting: "true",
},
fakeTargetingContext,
sandbox.stub(),
false
);
assert.calledOnce(fakeTargetingContext.evalWithDefault);
assert.calledWithExactly(fakeTargetingContext.evalWithDefault, "true");
assert.calledWithExactly(
fakeTargetingContext.setTelemetrySource,
"message"
);
});
it("should cache evaluation result", async () => {
evalStub.resolves(true);
let targetingContext = new global.TargetingContext();
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl1" },
targetingContext,
sandbox.stub(),
true
);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl2" },
targetingContext,
sandbox.stub(),
true
);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl1" },
targetingContext,
sandbox.stub(),
true
);
assert.calledTwice(evalStub);
});
it("should not cache evaluation result", async () => {
evalStub.resolves(true);
let targetingContext = new global.TargetingContext();
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
false
);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
false
);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
false
);
assert.calledThrice(evalStub);
});
it("should expire cache entries", async () => {
evalStub.resolves(true);
let targetingContext = new global.TargetingContext();
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
true
);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
true
);
clock.tick(5 * 60 * 1000 + 1);
await ASRouterTargeting.checkMessageTargeting(
{ targeting: "jexl" },
targetingContext,
sandbox.stub(),
true
);
assert.calledTwice(evalStub);
});
describe("#findMatchingMessage", () => {
let matchStub;
let messages = [
{ id: "FOO", targeting: "match" },
{ id: "BAR", targeting: "match" },
{ id: "BAZ" },
];
beforeEach(() => {
matchStub = sandbox
.stub(ASRouterTargeting, "_isMessageMatch")
.callsFake(message => message.targeting === "match");
});
it("should return an array of matches if returnAll is true", async () => {
assert.deepEqual(
await ASRouterTargeting.findMatchingMessage({
messages,
returnAll: true,
}),
[
{ id: "FOO", targeting: "match" },
{ id: "BAR", targeting: "match" },
]
);
});
it("should return an empty array if no matches were found and returnAll is true", async () => {
matchStub.returns(false);
assert.deepEqual(
await ASRouterTargeting.findMatchingMessage({
messages,
returnAll: true,
}),
[]
);
});
it("should return the first match if returnAll is false", async () => {
assert.deepEqual(
await ASRouterTargeting.findMatchingMessage({
messages,
}),
messages[0]
);
});
it("should return null if if no matches were found and returnAll is false", async () => {
matchStub.returns(false);
assert.deepEqual(
await ASRouterTargeting.findMatchingMessage({
messages,
}),
null
);
});
});
});
/**
* Messages should be sorted in the following order:
* 1. Rank
* 2. Priority
* 3. If the message has targeting
* 4. Order or randomization, depending on input
*/
describe("getSortedMessages", () => {
let globals = new GlobalOverrider();
let sandbox;
beforeEach(() => {
globals.set({ ASRouterPreferences });
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
globals.restore();
});
/**
* assertSortsCorrectly - Tests to see if an array, when sorted with getSortedMessages,
* returns the items in the expected order.
*
* @param {Message[]} expectedOrderArray - The array of messages in its expected order
* @param {{}} options - The options param for getSortedMessages
* @returns
*/
function assertSortsCorrectly(expectedOrderArray, options) {
const input = [...expectedOrderArray].reverse();
const result = getSortedMessages(input, options);
const indexes = result.map(message => expectedOrderArray.indexOf(message));
return assert.equal(
indexes.join(","),
[...expectedOrderArray.keys()].join(","),
"Messsages are out of order"
);
}
it("should sort messages by priority, then by targeting", () => {
assertSortsCorrectly([
{ priority: 100, targeting: "isFoo" },
{ priority: 100 },
{ priority: 99 },
{ priority: 1, targeting: "isFoo" },
{ priority: 1 },
{},
]);
});
it("should sort messages by priority, then targeting, then order if ordered param is true", () => {
assertSortsCorrectly(
[
{ priority: 100, order: 4 },
{ priority: 100, order: 5 },
{ priority: 1, order: 3, targeting: "isFoo" },
{ priority: 1, order: 0 },
{ priority: 1, order: 1 },
{ priority: 1, order: 2 },
{ order: 0 },
],
{ ordered: true }
);
});
});
|