forked from libp2p/js-libp2p-tcp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.spec.js
85 lines (62 loc) · 2.29 KB
/
connection.spec.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
/* eslint-env mocha */
'use strict'
const { expect } = require('aegir/utils/chai')
const TCP = require('../src')
const multiaddr = require('multiaddr')
describe('valid localAddr and remoteAddr', () => {
let tcp
const mockUpgrader = {
upgradeInbound: maConn => maConn,
upgradeOutbound: maConn => maConn
}
beforeEach(() => {
tcp = new TCP({ upgrader: mockUpgrader })
})
const ma = multiaddr('/ip4/127.0.0.1/tcp/0')
it('should resolve port 0', async () => {
// Create a Promise that resolves when a connection is handled
let handled
const handlerPromise = new Promise(resolve => { handled = resolve })
const handler = conn => handled(conn)
// Create a listener with the handler
const listener = tcp.createListener(handler)
// Listen on the multi-address
await listener.listen(ma)
const localAddrs = listener.getAddrs()
expect(localAddrs.length).to.equal(1)
// Dial to that address
const dialerConn = await tcp.dial(localAddrs[0])
// Wait for the incoming dial to be handled
const listenerConn = await handlerPromise
// Close the listener
await listener.close()
expect(dialerConn.localAddr.toString())
.to.equal(listenerConn.remoteAddr.toString())
expect(dialerConn.remoteAddr.toString())
.to.equal(listenerConn.localAddr.toString())
})
it('should handle multiple simultaneous closes', async () => {
// Create a Promise that resolves when a connection is handled
let handled
const handlerPromise = new Promise(resolve => { handled = resolve })
const handler = conn => handled(conn)
// Create a listener with the handler
const listener = tcp.createListener(handler)
// Listen on the multi-address
await listener.listen(ma)
const localAddrs = listener.getAddrs()
expect(localAddrs.length).to.equal(1)
// Dial to that address
const dialerConn = await tcp.dial(localAddrs[0])
// Wait for the incoming dial to be handled
await handlerPromise
// Close the listener with two simultaneous calls to `close`
await Promise.race([
new Promise((resolve, reject) => setTimeout(() => reject(new Error('Timed out waiting for connection close')), 500)),
await Promise.all([
dialerConn.close(),
dialerConn.close()
])
])
})
})