-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathconnection-timeout-tests.js
88 lines (76 loc) · 2.54 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
86
87
88
'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: Math.floor(Math.random() * 2000) + 2000,
connectionTimeoutMillis: 2000,
user: 'not',
database: 'existing',
}
const serverWithConnectionTimeout = (port, 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(port, options.host, () => callback(closeServer))
}
suite.test('successful connection', (done) => {
serverWithConnectionTimeout(options.port, 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) => {
const opts = { ...options, port: options.port + 1 }
serverWithConnectionTimeout(opts.port, opts.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(opts)
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))
})
})