31a33c627eec12c671872e3e2acf8c89d6bfe34c
[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 jsonIntegerSerialization (n) {
40 for (let i = 0; i < n; i++) {
41 const o = {
42 a: i
43 }
44 JSON.stringify(o)
45 }
46 }
47
48 /**
49 * Intentionally inefficient implementation.
50 *
51 * @param {number} n - The number of fibonacci numbers to generate.
52 * @returns {number} - The nth fibonacci number.
53 */
54 static fibonacci (n) {
55 if (n <= 1) return 1
56 return TestUtils.fibonacci(n - 1) + TestUtils.fibonacci(n - 2)
57 }
58
59 /**
60 * Intentionally inefficient implementation.
61 *
62 * @param {number} n - The number to calculate the factorial of.
63 * @returns {number} - The factorial of n.
64 */
65 static factorial (n) {
66 if (n === 0) {
67 return 1
68 } else {
69 return TestUtils.factorial(n - 1) * n
70 }
71 }
72
73 static executeWorkerFunction (data) {
74 switch (data.function) {
75 case WorkerFunctions.jsonIntegerSerialization:
76 return TestUtils.jsonIntegerSerialization(data.n || 100)
77 case WorkerFunctions.fibonacci:
78 return TestUtils.fibonacci(data.n || 25)
79 case WorkerFunctions.factorial:
80 return TestUtils.factorial(data.n || 100)
81 default:
82 throw new Error('Unknown worker function')
83 }
84 }
85 }
86
87 module.exports = TestUtils