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
|
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const { Async } = ChromeUtils.importESModule(
"resource://services-common/async.sys.mjs"
);
const { sinon } = ChromeUtils.importESModule(
"resource://testing-common/Sinon.sys.mjs"
);
function makeArray(length) {
// Start at 1 so that we can just divide by yieldEvery to get the expected
// call count. (we exp)
return Array.from({ length }, (v, i) => i + 1);
}
// Adjust if we ever change the default.
const DEFAULT_YIELD_EVERY = 50;
add_task(async function testYields() {
let spy = sinon.spy(Async, "promiseYield");
try {
await Async.yieldingForEach(makeArray(DEFAULT_YIELD_EVERY * 2), element => {
// The yield will happen *after* this function is ran.
Assert.equal(
spy.callCount,
Math.floor((element - 1) / DEFAULT_YIELD_EVERY)
);
});
} finally {
spy.restore();
}
});
add_task(async function testExistingYieldState() {
const yieldState = Async.yieldState(DEFAULT_YIELD_EVERY);
for (let i = 0; i < 15; i++) {
Assert.equal(yieldState.shouldYield(), false);
}
let spy = sinon.spy(Async, "promiseYield");
try {
await Async.yieldingForEach(
makeArray(DEFAULT_YIELD_EVERY * 2),
element => {
Assert.equal(
spy.callCount,
Math.floor((element + 15 - 1) / DEFAULT_YIELD_EVERY)
);
},
yieldState
);
} finally {
spy.restore();
}
});
add_task(async function testEarlyReturn() {
let lastElement = 0;
await Async.yieldingForEach(makeArray(DEFAULT_YIELD_EVERY), element => {
lastElement = element;
return element === 10;
});
Assert.equal(lastElement, 10);
});
add_task(async function testEaryReturnAsync() {
let lastElement = 0;
await Async.yieldingForEach(makeArray(DEFAULT_YIELD_EVERY), async element => {
lastElement = element;
return element === 10;
});
Assert.equal(lastElement, 10);
});
add_task(async function testEarlyReturnPromise() {
let lastElement = 0;
await Async.yieldingForEach(makeArray(DEFAULT_YIELD_EVERY), element => {
lastElement = element;
return new Promise(resolve => resolve(element === 10));
});
Assert.equal(lastElement, 10);
});
|