2018-02-07 05:56:55 +00:00
|
|
|
/* eslint-env mocha */
|
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const chai = require('chai')
|
|
|
|
const dirtyChai = require('dirty-chai')
|
|
|
|
const expect = chai.expect
|
|
|
|
chai.use(dirtyChai)
|
|
|
|
const TCP = require('../src')
|
|
|
|
const multiaddr = require('multiaddr')
|
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
describe('valid localAddr and remoteAddr', () => {
|
2018-02-07 05:56:55 +00:00
|
|
|
let tcp
|
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
const mockUpgrader = {
|
|
|
|
upgradeInbound: maConn => maConn,
|
|
|
|
upgradeOutbound: maConn => maConn
|
|
|
|
}
|
|
|
|
|
2018-02-07 05:56:55 +00:00
|
|
|
beforeEach(() => {
|
2019-09-16 16:19:47 +01:00
|
|
|
tcp = new TCP({ upgrader: mockUpgrader })
|
2018-02-07 05:56:55 +00:00
|
|
|
})
|
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
const ma = multiaddr('/ip4/127.0.0.1/tcp/0')
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
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 })
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
const handler = conn => handled(conn)
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
// Create a listener with the handler
|
|
|
|
const listener = tcp.createListener(handler)
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
// Listen on the multi-address
|
|
|
|
await listener.listen(ma)
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
const localAddrs = listener.getAddrs()
|
|
|
|
expect(localAddrs.length).to.equal(1)
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
// Dial to that address
|
|
|
|
const dialerConn = await tcp.dial(localAddrs[0])
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
// Wait for the incoming dial to be handled
|
|
|
|
const listenerConn = await handlerPromise
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
// Close the listener
|
|
|
|
await listener.close()
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
expect(dialerConn.localAddr.toString())
|
|
|
|
.to.equal(listenerConn.remoteAddr.toString())
|
2018-02-07 05:56:55 +00:00
|
|
|
|
2019-09-16 16:19:47 +01:00
|
|
|
expect(dialerConn.remoteAddr.toString())
|
|
|
|
.to.equal(listenerConn.localAddr.toString())
|
2018-02-07 05:56:55 +00:00
|
|
|
})
|
|
|
|
})
|