Last active
September 25, 2018 11:12
-
-
Save dazraf/01115f0d376647f99e8fc453ba07251c to your computer and use it in GitHub Desktop.
Connect to H2 when writing debugging MockNetwork tests for Corda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package yourpackage | |
import net.corda.node.internal.StartedNode | |
import net.corda.testing.node.MockNetwork | |
import org.h2.tools.Server | |
class H2Server(nodes: MockNetwork.BasketOfNodes, private val port : Int = 9092) { | |
companion object { | |
private val H2_NAME_RE = "^jdbc:h2:(mem:[^;:]+).*$".toRegex() | |
} | |
private val server: Server = org.h2.tools.Server.createTcpServer("-tcpPort", port.toString(), "-tcpAllowOthers").start() | |
init { | |
nodes.notaryNode.writeJDBCEndpoint() | |
nodes.partyNodes.forEach { it.writeJDBCEndpoint() } | |
} | |
/** | |
* Block the current thread so that we can connect and examine the database | |
*/ | |
fun block() { | |
val lock = java.lang.Object() | |
synchronized(lock) { | |
lock.wait() | |
} | |
} | |
fun stop() { | |
server.stop() | |
} | |
private fun StartedNode<MockNetwork.MockNode>.writeJDBCEndpoint() { | |
val url = this.database.dataSource.dataSourceProperties.getProperty("url") | |
val databaseName = H2_NAME_RE.matchEntire(url)?.groupValues?.get(1) ?: throw RuntimeException("could not extract db name from $url") | |
println("Database for ${this.info.legalIdentities.first().name.organisation} database: jdbc:h2:tcp://localhost:$port/$databaseName") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HowToUseTest { | |
private lateinit var network: MockNetwork | |
private lateinit var nodes: MockNetwork.BasketOfNodes | |
@Before | |
fun setup() { | |
setCordappPackages(this.javaClass.`package`.name) | |
this.network = MockNetwork() | |
this.nodes = network.createSomeNodes(1) | |
// ... etc | |
} | |
@Test(timeout = Long.MAX_VALUE) | |
fun `some test I want to debug`() { | |
// ... | |
H2Server(nodes).block() | |
// the console will show the jdbc endpoints you can connect with your favourite, H2 compatible, client | |
// e.g. Database for Mock Company 1 database: jdbc:h2:tcp://localhost:9092/mem:node_1_net_55450354149547878_persistence | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment