-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathconnection-timeout-tests.js
85 lines (73 loc) · 2.4 KB
/
connection-timeout-tests.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict'
const net = require('net')
const buffers = require('../../test-buffers')
const helper = require('./test-helper')
const suite = new helper.Suite()
const options = {
host: 'localhost',
port: 54321,
connectionTimeoutMillis: 2000,
user: 'not',
database: 'existing'
}
const serverWithConnectionTimeout = (timeout, callback) => {
const sockets = new Set()
const server = net.createServer(socket => {
sockets.add(socket)
socket.once('end', () => sockets.delete(socket))
socket.on('data', data => {
// deny request for SSL
if (data.length === 8) {
socket.write(Buffer.from('N', 'utf8'))
// consider all authentication requests as good
} else if (!data[0]) {
socket.write(buffers.authenticationOk())
// send ReadyForQuery `timeout` ms after authentication
setTimeout(() => socket.write(buffers.readyForQuery()), timeout).unref()
// respond with our canned response
} else {
socket.write(buffers.readyForQuery())
}
})
})
let closing = false
const closeServer = done => {
if (closing) return
closing = true
server.close(done)
for (const socket of sockets) {
socket.destroy()
}
}
server.listen(options.port, options.host, () => callback(closeServer))
}
suite.test('successful connection', done => {
serverWithConnectionTimeout(0, closeServer => {
const timeoutId = setTimeout(() => {
throw new Error('Client should have connected successfully but it did not.')
}, 3000)
const client = new helper.Client(options)
client.connect()
.then(() => client.end())
.then(() => closeServer(done))
.catch(err => closeServer(() => done(err)))
.then(() => clearTimeout(timeoutId))
})
})
suite.test('expired connection timeout', done => {
serverWithConnectionTimeout(options.connectionTimeoutMillis * 2, closeServer => {
const timeoutId = setTimeout(() => {
throw new Error('Client should have emitted an error but it did not.')
}, 3000)
const client = new helper.Client(options)
client.connect()
.then(() => client.end())
.then(() => closeServer(() => done(new Error('Connection timeout should have expired but it did not.'))))
.catch(err => {
assert(err instanceof Error)
assert(/timeout expired\s*/.test(err.message))
closeServer(done)
})
.then(() => clearTimeout(timeoutId))
})
})