f4cb38b23cb1ca63c5c6e17109af45d59f66dc0d
[poolifier.git] / tests / test-utils.js
1 const { WorkerFunctions } = require('./test-types')
2
3 class TestUtils {
4 static async waitExits (pool, numberOfExitEventsToWait) {
5 let exitEvents = 0
6 return new Promise(resolve => {
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 }
21
22 static async sleepWorkerFunction (
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 )
36 })
37 }
38
39 static generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
40 if (max < 0) {
41 throw new RangeError('Invalid interval')
42 }
43 max = Math.floor(max)
44 if (min != null && min !== 0) {
45 if (max < min || min < 0) {
46 throw new RangeError('Invalid interval')
47 }
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
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.
65 *
66 * @param {number} n - The number of fibonacci numbers to generate.
67 * @returns {number} - The nth fibonacci number.
68 */
69 static fibonacci (n) {
70 if (n <= 1) return 1
71 return TestUtils.fibonacci(n - 1) + TestUtils.fibonacci(n - 2)
72 }
73
74 /**
75 * Intentionally inefficient implementation.
76 *
77 * @param {number} n - The number to calculate the factorial of.
78 * @returns {number} - The factorial of n.
79 */
80 static factorial (n) {
81 if (n === 0) {
82 return 1
83 } else {
84 return TestUtils.factorial(n - 1) * n
85 }
86 }
87
88 static executeWorkerFunction (data) {
89 switch (data.function) {
90 case WorkerFunctions.jsonIntegerSerialization:
91 return TestUtils.jsonIntegerSerialization(data.n || 100)
92 case WorkerFunctions.fibonacci:
93 return TestUtils.fibonacci(data.n || 25)
94 case WorkerFunctions.factorial:
95 return TestUtils.factorial(data.n || 100)
96 default:
97 throw new Error('Unknown worker function')
98 }
99 }
100 }
101
102 module.exports = TestUtils