Commit | Line | Data |
---|---|---|
2d2e32c2 | 1 | const { WorkerFunctions } = require('./test-types') |
6db75ad9 | 2 | |
85a3f8a7 APA |
3 | class TestUtils { |
4 | static async waitExits (pool, numberOfExitEventsToWait) { | |
5 | let exitEvents = 0 | |
d94bee6f | 6 | return new Promise(resolve => { |
85a3f8a7 APA |
7 | pool.workers.forEach(w => { |
8 | w.on('exit', () => { | |
9 | exitEvents++ | |
10 | if (exitEvents === numberOfExitEventsToWait) { | |
11 | resolve(exitEvents) | |
12 | } | |
13 | }) | |
14 | }) | |
15 | }) | |
16 | } | |
17 | ||
18 | static async sleep (ms) { | |
19 | return new Promise(resolve => setTimeout(resolve, ms)) | |
20 | } | |
bdacc2d2 | 21 | |
6db75ad9 | 22 | static async sleepWorkerFunction ( |
15d56315 JB |
23 | data, |
24 | ms, | |
25 | rejection = false, | |
26 | rejectionMessage = '' | |
27 | ) { | |
28 | return new Promise((resolve, reject) => { | |
29 | setTimeout( | |
30 | () => | |
31 | rejection === true | |
32 | ? reject(new Error(rejectionMessage)) | |
33 | : resolve(data), | |
34 | ms | |
35 | ) | |
bdacc2d2 JB |
36 | }) |
37 | } | |
38 | ||
9bc18a6d | 39 | static generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) { |
f931db5c JB |
40 | max = Math.floor(max) |
41 | if (min) { | |
42 | min = Math.ceil(min) | |
43 | return Math.floor(Math.random() * (max - min + 1)) + min | |
44 | } | |
45 | return Math.floor(Math.random() * (max + 1)) | |
46 | } | |
47 | ||
bdacc2d2 JB |
48 | static jsonIntegerSerialization (n) { |
49 | for (let i = 0; i < n; i++) { | |
50 | const o = { | |
51 | a: i | |
52 | } | |
53 | JSON.stringify(o) | |
54 | } | |
55 | } | |
56 | ||
57 | /** | |
58 | * Intentionally inefficient implementation. | |
59 | * | |
7d82d90e JB |
60 | * @param {number} n - The number of fibonacci numbers to generate. |
61 | * @returns {number} - The nth fibonacci number. | |
bdacc2d2 JB |
62 | */ |
63 | static fibonacci (n) { | |
64 | if (n <= 1) return 1 | |
65 | return TestUtils.fibonacci(n - 1) + TestUtils.fibonacci(n - 2) | |
66 | } | |
67 | ||
68 | /** | |
69 | * Intentionally inefficient implementation. | |
70 | * | |
7d82d90e JB |
71 | * @param {number} n - The number to calculate the factorial of. |
72 | * @returns {number} - The factorial of n. | |
bdacc2d2 JB |
73 | */ |
74 | static factorial (n) { | |
75 | if (n === 0) { | |
76 | return 1 | |
77 | } else { | |
78 | return TestUtils.factorial(n - 1) * n | |
79 | } | |
80 | } | |
6db75ad9 JB |
81 | |
82 | static executeWorkerFunction (data) { | |
83 | switch (data.function) { | |
84 | case WorkerFunctions.jsonIntegerSerialization: | |
85 | return TestUtils.jsonIntegerSerialization(data.n || 100) | |
86 | case WorkerFunctions.fibonacci: | |
87 | return TestUtils.fibonacci(data.n || 25) | |
88 | case WorkerFunctions.factorial: | |
89 | return TestUtils.factorial(data.n || 100) | |
90 | default: | |
91 | throw new Error('Unknown worker function') | |
92 | } | |
93 | } | |
85a3f8a7 APA |
94 | } |
95 | ||
96 | module.exports = TestUtils |