1 | 'use strict'
|
2 |
|
3 | const expect = require('expect.js')
|
4 | const EventEmitter = require('events').EventEmitter
|
5 | const describe = require('mocha').describe
|
6 | const it = require('mocha').it
|
7 | const Pool = require('../')
|
8 |
|
9 | describe('events', function () {
|
10 | it('emits connect before callback', function (done) {
|
11 | const pool = new Pool()
|
12 | let emittedClient = false
|
13 | pool.on('connect', function (client) {
|
14 | emittedClient = client
|
15 | })
|
16 |
|
17 | pool.connect(function (err, client, release) {
|
18 | if (err) return done(err)
|
19 | release()
|
20 | pool.end()
|
21 | expect(client).to.be(emittedClient)
|
22 | done()
|
23 | })
|
24 | })
|
25 |
|
26 | it('emits "connect" only with a successful connection', function () {
|
27 | const pool = new Pool({
|
28 |
|
29 | Client: mockClient({
|
30 | connect: function (cb) {
|
31 | process.nextTick(() => {
|
32 | cb(new Error('bad news'))
|
33 | })
|
34 | }
|
35 | })
|
36 | })
|
37 | pool.on('connect', function () {
|
38 | throw new Error('should never get here')
|
39 | })
|
40 | return pool.connect().catch(e => expect(e.message).to.equal('bad news'))
|
41 | })
|
42 |
|
43 | it('emits acquire every time a client is acquired', function (done) {
|
44 | const pool = new Pool()
|
45 | let acquireCount = 0
|
46 | pool.on('acquire', function (client) {
|
47 | expect(client).to.be.ok()
|
48 | acquireCount++
|
49 | })
|
50 | for (let i = 0; i < 10; i++) {
|
51 | pool.connect(function (err, client, release) {
|
52 | if (err) return done(err)
|
53 | release()
|
54 | })
|
55 | pool.query('SELECT now()')
|
56 | }
|
57 | setTimeout(function () {
|
58 | expect(acquireCount).to.be(20)
|
59 | pool.end(done)
|
60 | }, 100)
|
61 | })
|
62 |
|
63 | it('emits error and client if an idle client in the pool hits an error', function (done) {
|
64 | const pool = new Pool()
|
65 | pool.connect(function (err, client) {
|
66 | expect(err).to.equal(undefined)
|
67 | client.release()
|
68 | setImmediate(function () {
|
69 | client.emit('error', new Error('problem'))
|
70 | })
|
71 | pool.once('error', function (err, errClient) {
|
72 | expect(err.message).to.equal('problem')
|
73 | expect(errClient).to.equal(client)
|
74 | done()
|
75 | })
|
76 | })
|
77 | })
|
78 | })
|
79 |
|
80 | function mockClient (methods) {
|
81 | return function () {
|
82 | const client = new EventEmitter()
|
83 | Object.assign(client, methods)
|
84 | return client
|
85 | }
|
86 | }
|