Merge pull request #29 from pioardi/dependabot/npm_and_yarn/standard-14.3.4
[poolifier.git] / tests / fixed.test.js
CommitLineData
506c2a14 1const expect = require('expect')
2const FixedThreadPool = require('../lib/fixed')
3const numThreads = 10
4const pool = new FixedThreadPool(numThreads,
106744f7 5 './tests/workers/testWorker.js',
506c2a14 6 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
106744f7 7const emptyPool = new FixedThreadPool(1, './tests/workers/emptyWorker.js')
8const echoPool = new FixedThreadPool(1, './tests/workers/echoWorker.js')
9const errorPool = new FixedThreadPool(1, './tests/workers/errorWorker.js', { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
506c2a14 10
11describe('Fixed thread pool test suite ', () => {
12 it('Choose worker round robin test', async () => {
13 const results = new Set()
14 for (let i = 0; i < numThreads; i++) {
15 results.add(pool._chooseWorker().threadId)
16 }
17 expect(results.size).toBe(numThreads)
18 })
19
20 it('Verify that the function is executed in a worker thread', async () => {
21 const result = await pool.execute({ test: 'test' })
22 expect(result).toBeDefined()
23 expect(result).toBeFalsy()
24 })
25
106744f7 26 it('Verify that is possible to invoke the execute method without input', async () => {
27 const result = await pool.execute()
28 expect(result).toBeDefined()
29 expect(result).toBeFalsy()
30 })
31
32 it('Verify that is possible to have a worker that return undefined', async () => {
33 const result = await emptyPool.execute()
34 expect(result).toBeFalsy()
35 })
36
37 it('Verify that data are sent to the worker correctly', async () => {
38 const data = { f: 10 }
39 const result = await echoPool.execute(data)
40 expect(result).toBeTruthy()
41 expect(result.f).toBe(data.f)
42 })
43
44 it('Verify that error handling is working properly', async () => {
45 const data = { f: 10 }
46 let inError
47 try {
48 await errorPool.execute(data)
49 } catch (e) {
50 inError = e
51 }
52 expect(inError).toBeTruthy()
53 expect(inError instanceof Error).toBeTruthy()
54 expect(inError.message).toBeTruthy()
55 })
56
506c2a14 57 it('Shutdown test', async () => {
58 let closedThreads = 0
59 pool.workers.forEach(w => {
60 w.on('exit', () => {
61 closedThreads++
62 })
63 })
1f9a5a44 64 await pool.destroy()
506c2a14 65 expect(closedThreads).toBe(numThreads)
66 })
67
68 it('Validations test', () => {
69 let error
70 try {
71 const pool1 = new FixedThreadPool()
72 console.log(pool1)
73 } catch (e) {
74 error = e
75 }
76 expect(error).toBeTruthy()
77 expect(error.message).toBeTruthy()
78 })
79
80 it('Should work even without opts in input', async () => {
106744f7 81 const pool1 = new FixedThreadPool(1, './tests/workers/testWorker.js')
506c2a14 82 const res = await pool1.execute({ test: 'test' })
83 expect(res).toBeFalsy()
84 })
85})