nim-libp2p-experimental/tests/testswitch.nim

81 lines
2.4 KiB
Nim
Raw Normal View History

2019-09-04 22:00:39 +00:00
import unittest, tables
2019-08-31 17:58:49 +00:00
import chronos
2019-09-06 07:13:47 +00:00
import ../libp2p/switch,
../libp2p/multistream,
../libp2p/protocols/identify,
../libp2p/connection,
../libp2p/transports/[transport, tcptransport],
../libp2p/multiaddress,
../libp2p/peerinfo,
../libp2p/crypto/crypto,
../libp2p/peer,
../libp2p/protocols/protocol,
../libp2p/muxers/muxer,
2019-09-04 22:00:39 +00:00
../libp2p/muxers/mplex/mplex,
../libp2p/muxers/mplex/types
2019-08-31 17:58:49 +00:00
const TestCodec = "/test/proto/1.0.0"
type
TestProto = ref object of LPProtocol
method init(p: TestProto) {.gcsafe.} =
proc handle(conn: Connection, proto: string) {.async, gcsafe.} =
let msg = cast[string](await conn.readLp())
2019-09-06 07:13:47 +00:00
echo msg
2019-08-31 17:58:49 +00:00
check "Hello!" == msg
await conn.writeLp("Hello!")
2019-08-31 18:52:56 +00:00
p.codec = TestCodec
2019-08-31 17:58:49 +00:00
p.handler = handle
suite "Switch":
test "e2e use switch":
2019-09-04 22:00:39 +00:00
proc createSwitch(ma: MultiAddress): (Switch, PeerInfo) =
let seckey = PrivateKey.random(RSA)
var peerInfo: PeerInfo
peerInfo.peerId = PeerID.init(seckey)
peerInfo.addrs.add(ma)
let identify = newIdentify(peerInfo)
proc createMplex(conn: Connection): Muxer =
result = newMplex(conn)
let mplexProvider = newMuxerProvider(createMplex, MplexCodec)
let transports = @[Transport(newTransport(TcpTransport))]
let muxers = [(MplexCodec, mplexProvider)].toTable()
let switch = newSwitch(peerInfo, transports, identify, muxers)
result = (switch, peerInfo)
2019-08-31 17:58:49 +00:00
proc testSwitch(): Future[bool] {.async, gcsafe.} =
let ma1: MultiAddress = Multiaddress.init("/ip4/127.0.0.1/tcp/53370")
2019-09-06 07:13:47 +00:00
let ma2: MultiAddress = Multiaddress.init("/ip4/127.0.0.1/tcp/53371")
2019-08-31 17:58:49 +00:00
var peerInfo1, peerInfo2: PeerInfo
var switch1, switch2: Switch
(switch1, peerInfo1) = createSwitch(ma1)
2019-09-05 15:19:39 +00:00
2019-09-04 22:00:39 +00:00
let testProto = new TestProto
2019-09-05 15:19:39 +00:00
testProto.init()
2019-09-04 22:00:39 +00:00
testProto.codec = TestCodec
2019-08-31 17:58:49 +00:00
switch1.mount(testProto)
await switch1.start()
(switch2, peerInfo2) = createSwitch(ma2)
2019-09-05 15:19:39 +00:00
await switch2.start()
2019-08-31 17:58:49 +00:00
let conn = await switch2.dial(peerInfo1, TestCodec)
2019-09-06 07:13:47 +00:00
echo "DIALED???"
echo conn.repr
2019-08-31 17:58:49 +00:00
await conn.writeLp("Hello!")
2019-09-06 07:13:47 +00:00
echo "WROTE FROM TEST"
echo conn.repr
2019-08-31 17:58:49 +00:00
let msg = cast[string](await conn.readLp())
2019-09-06 07:13:47 +00:00
echo msg
2019-08-31 17:58:49 +00:00
check "Hello!" == msg
result = true
2019-09-06 07:13:47 +00:00
await allFutures(switch1.stop(), switch2.stop())
2019-08-31 17:58:49 +00:00
check:
waitFor(testSwitch()) == true