From 6cf01f614f7b1be7e42c885b0566c9709f7803ef Mon Sep 17 00:00:00 2001 From: RogerWillis Date: Fri, 26 Aug 2016 13:46:11 +0100 Subject: [PATCH] Added getFreeLocalPorts() for grabbing more than one port. Fixes bug in freeLocalHostAndPort() where the same port can be picked multiple times. --- .../com/r3corda/core/testing/CoreTestUtils.kt | 21 +++++++++++++++++++ .../com/r3corda/core/testing/IRSDemoTest.kt | 10 +++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/core/src/main/kotlin/com/r3corda/core/testing/CoreTestUtils.kt b/core/src/main/kotlin/com/r3corda/core/testing/CoreTestUtils.kt index 51a4d5afaa..91ea70255b 100644 --- a/core/src/main/kotlin/com/r3corda/core/testing/CoreTestUtils.kt +++ b/core/src/main/kotlin/com/r3corda/core/testing/CoreTestUtils.kt @@ -86,11 +86,32 @@ inline fun rootCauseExceptions(body: () -> R): R { } } +/** + * Returns a free port. + * + * Unsafe for getting multiple ports! + * Use [getFreeLocalPorts] for getting multiple ports. + */ fun freeLocalHostAndPort(): HostAndPort { val freePort = ServerSocket(0).use { it.localPort } return HostAndPort.fromParts("localhost", freePort) } +/** + * Creates a specified number of ports for use by the Node. + * + * Unlikely, but in the time between running this function and handing the ports + * to the Node, some other process else could allocate the returned ports. + */ +fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List { + // Create a bunch of sockets up front. + val sockets = Array(numberToAlloc) { ServerSocket(0) } + val result = sockets.map { HostAndPort.fromParts(hostName, it.localPort) } + // Close sockets only once we've grabbed all the ports we need. + sockets.forEach(ServerSocket::close) + return result +} + /** * Creates and tests a ledger built by the passed in dsl. The provided services can be customised, otherwise a default * of a freshly built [MockServices] is used. diff --git a/src/integration-test/kotlin/com/r3corda/core/testing/IRSDemoTest.kt b/src/integration-test/kotlin/com/r3corda/core/testing/IRSDemoTest.kt index 31cc7f9f22..9efbd15a56 100644 --- a/src/integration-test/kotlin/com/r3corda/core/testing/IRSDemoTest.kt +++ b/src/integration-test/kotlin/com/r3corda/core/testing/IRSDemoTest.kt @@ -9,9 +9,11 @@ import java.nio.file.Paths class IRSDemoTest { @Test fun `runs IRS demo`() { - val nodeAddrA = freeLocalHostAndPort() - val apiAddrA = freeLocalHostAndPort() - val apiAddrB = freeLocalHostAndPort() + val hostAndPorts = getFreeLocalPorts("localhost", 4) + + val nodeAddrA = hostAndPorts[0] + val apiAddrA = hostAndPorts[1] + val apiAddrB = hostAndPorts[2] val baseDirectory = Paths.get("./build/integration-test/${TestTimestamp.timestamp}/irs-demo") var procA: Process? = null @@ -29,7 +31,7 @@ class IRSDemoTest { procB = startNode( baseDirectory = baseDirectory, nodeType = "NodeB", - nodeAddr = freeLocalHostAndPort(), + nodeAddr = hostAndPorts[3], networkMapAddr = nodeAddrA, apiAddr = apiAddrB )