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