| 1 | const expect = require('expect') |
| 2 | const { DynamicThreadPool } = require('../lib/dynamic') |
| 3 | const min = 1 |
| 4 | const max = 3 |
| 5 | const pool = new DynamicThreadPool(min, max, './tests/workers/testWorker.js', { |
| 6 | errorHandler: e => console.error(e), |
| 7 | onlineHandler: () => console.log('worker is online') |
| 8 | }) |
| 9 | |
| 10 | describe('Dynamic thread pool test suite ', () => { |
| 11 | it('Verify that the function is executed in a worker thread', async () => { |
| 12 | const result = await pool.execute({ test: 'test' }) |
| 13 | expect(result).toBeDefined() |
| 14 | expect(result).toBeFalsy() |
| 15 | }) |
| 16 | |
| 17 | it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => { |
| 18 | const promises = [] |
| 19 | let closedThreads = 0 |
| 20 | let fullPool = 0 |
| 21 | pool.emitter.on('FullPool', () => fullPool++) |
| 22 | for (let i = 0; i < max * 2; i++) { |
| 23 | promises.push(pool.execute({ test: 'test' })) |
| 24 | } |
| 25 | expect(pool.workers.length).toBe(max) |
| 26 | pool.workers.forEach(w => { |
| 27 | w.on('exit', () => { |
| 28 | closedThreads++ |
| 29 | }) |
| 30 | }) |
| 31 | expect(fullPool > 1).toBeTruthy() |
| 32 | await new Promise(resolve => setTimeout(resolve, 2000)) |
| 33 | expect(closedThreads).toBe(max - min) |
| 34 | }) |
| 35 | |
| 36 | it('Verify scale thread up and down is working', async () => { |
| 37 | expect(pool.workers.length).toBe(min) |
| 38 | for (let i = 0; i < max * 10; i++) { |
| 39 | pool.execute({ test: 'test' }) |
| 40 | } |
| 41 | expect(pool.workers.length).toBe(max) |
| 42 | await new Promise(resolve => setTimeout(resolve, 1000)) |
| 43 | expect(pool.workers.length).toBe(min) |
| 44 | for (let i = 0; i < max * 10; i++) { |
| 45 | pool.execute({ test: 'test' }) |
| 46 | } |
| 47 | expect(pool.workers.length).toBe(max) |
| 48 | await new Promise(resolve => setTimeout(resolve, 1000)) |
| 49 | expect(pool.workers.length).toBe(min) |
| 50 | }) |
| 51 | it('Shutdown test', async () => { |
| 52 | let closedThreads = 0 |
| 53 | pool.workers.forEach(w => { |
| 54 | w.on('exit', () => { |
| 55 | closedThreads++ |
| 56 | }) |
| 57 | }) |
| 58 | await pool.destroy() |
| 59 | expect(closedThreads).toBe(min) |
| 60 | }) |
| 61 | |
| 62 | it('Validations test', () => { |
| 63 | let error |
| 64 | try { |
| 65 | const pool1 = new DynamicThreadPool() |
| 66 | console.log(pool1) |
| 67 | } catch (e) { |
| 68 | error = e |
| 69 | } |
| 70 | expect(error).toBeTruthy() |
| 71 | expect(error.message).toBeTruthy() |
| 72 | }) |
| 73 | |
| 74 | it('Should work even without opts in input', async () => { |
| 75 | const pool1 = new DynamicThreadPool(1, 1, './tests/workers/testWorker.js') |
| 76 | const res = await pool1.execute({ test: 'test' }) |
| 77 | expect(res).toBeFalsy() |
| 78 | }) |
| 79 | }) |