1 const expect
= require('expect')
2 const { DynamicThreadPool
} = require('../../../lib/index')
5 const pool
= new DynamicThreadPool(
8 './tests/worker/thread/testWorker.js',
10 errorHandler
: e
=> console
.error(e
)
14 describe('Dynamic thread pool test suite ', () => {
15 it('Verify that the function is executed in a worker thread', async () => {
16 const result
= await pool
.execute({ test
: 'test' })
17 expect(result
).toBeDefined()
18 expect(result
).toBeFalsy()
21 it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
25 pool
.emitter
.on('FullPool', () => fullPool
++)
26 for (let i
= 0; i
< max
* 2; i
++) {
27 promises
.push(pool
.execute({ test
: 'test' }))
29 expect(pool
.workers
.length
).toBe(max
)
30 pool
.workers
.forEach(w
=> {
35 expect(fullPool
> 1).toBeTruthy()
36 await
new Promise(resolve
=> setTimeout(resolve
, 2000))
37 expect(closedThreads
).toBe(max
- min
)
40 it('Verify scale thread up and down is working', async () => {
41 expect(pool
.workers
.length
).toBe(min
)
42 for (let i
= 0; i
< max
* 10; i
++) {
43 pool
.execute({ test
: 'test' })
45 expect(pool
.workers
.length
).toBe(max
)
46 await
new Promise(resolve
=> setTimeout(resolve
, 1000))
47 expect(pool
.workers
.length
).toBe(min
)
48 for (let i
= 0; i
< max
* 10; i
++) {
49 pool
.execute({ test
: 'test' })
51 expect(pool
.workers
.length
).toBe(max
)
52 await
new Promise(resolve
=> setTimeout(resolve
, 1000))
53 expect(pool
.workers
.length
).toBe(min
)
56 it('Shutdown test', async () => {
58 pool
.workers
.forEach(w
=> {
64 expect(closedThreads
).toBe(min
)
67 it('Validations test', () => {
70 const pool1
= new DynamicThreadPool()
75 expect(error
).toBeTruthy()
76 expect(error
.message
).toBeTruthy()
79 it('Should work even without opts in input', async () => {
80 const pool1
= new DynamicThreadPool(
83 './tests/worker/thread/testWorker.js'
85 const res
= await pool1
.execute({ test
: 'test' })
86 expect(res
).toBeFalsy()
89 it('Verify scale thread up and down is working when long running task is used', async () => {
90 const longRunningPool
= new DynamicThreadPool(
93 './tests/worker/thread/longRunningWorker.js',
95 errorHandler
: e
=> console
.error(e
),
96 onlineHandler
: () => console
.log('worker is online')
99 expect(longRunningPool
.workers
.length
).toBe(min
)
100 for (let i
= 0; i
< max
* 10; i
++) {
101 longRunningPool
.execute({ test
: 'test' })
103 expect(longRunningPool
.workers
.length
).toBe(max
)
104 await
new Promise(resolve
=> setTimeout(resolve
, 1000))
105 // Here we expect the workers to be at the max size since that the task is still running
106 expect(longRunningPool
.workers
.length
).toBe(max
)