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