Minor: auto-format of module: test-utils

This commit is contained in:
Mike Hearn 2017-04-11 12:48:56 +02:00
parent 9948815df1
commit cda04b0e7b
12 changed files with 38 additions and 21 deletions

View File

@ -68,6 +68,7 @@ inline fun <reified E : Any> expect(
* @param expectations The pieces of DSL that should run sequentially when events arrive.
*/
fun <E> sequence(vararg expectations: ExpectCompose<E>): ExpectCompose<E> = ExpectCompose.Sequential(listOf(*expectations))
fun <E> sequence(expectations: List<ExpectCompose<E>>): ExpectCompose<E> = ExpectCompose.Sequential(expectations)
/**
@ -76,6 +77,7 @@ fun <E> sequence(expectations: List<ExpectCompose<E>>): ExpectCompose<E> = Expec
* @param expectations The pieces of DSL all of which should run but in an unspecified order depending on what sequence events arrive.
*/
fun <E> parallel(vararg expectations: ExpectCompose<E>): ExpectCompose<E> = ExpectCompose.Parallel(listOf(*expectations))
fun <E> parallel(expectations: List<ExpectCompose<E>>): ExpectCompose<E> = ExpectCompose.Parallel(expectations)
/**
@ -202,6 +204,7 @@ private sealed class ExpectComposeState<E : Any> {
override fun nextState(event: E) = null
override fun getExpectedEvents(): List<Class<E>> = listOf()
}
class Single<E : Any, T : E>(val single: ExpectCompose.Single<E, T>) : ExpectComposeState<E>() {
override fun nextState(event: E): Pair<() -> Unit, ExpectComposeState<E>>? =
if (single.expect.clazz.isAssignableFrom(event.javaClass)) {
@ -215,6 +218,7 @@ private sealed class ExpectComposeState<E : Any> {
} else {
null
}
override fun getExpectedEvents() = listOf(single.expect.clazz)
}
@ -266,6 +270,7 @@ private sealed class ExpectComposeState<E : Any> {
}
return null
}
override fun getExpectedEvents() = states.flatMap { it.getExpectedEvents() }
}

View File

@ -1,6 +1,8 @@
package net.corda.testing
import net.corda.core.contracts.*
import net.corda.core.contracts.ContractState
import net.corda.core.contracts.StateAndRef
import net.corda.core.contracts.TransactionState
import net.corda.core.crypto.SecureHash
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.transactions.WireTransaction
@ -122,7 +124,7 @@ interface LedgerDSLInterpreter<out T : TransactionDSLInterpreter> : Verifies, Ou
* functionality then first add your primitive to [LedgerDSLInterpreter] and then add the convenience defaults/extension
* methods here.
*/
class LedgerDSL<out T : TransactionDSLInterpreter, out L : LedgerDSLInterpreter<T>> (val interpreter: L) :
class LedgerDSL<out T : TransactionDSLInterpreter, out L : LedgerDSLInterpreter<T>>(val interpreter: L) :
LedgerDSLInterpreter<TransactionDSLInterpreter> by interpreter {
/**
@ -132,6 +134,7 @@ class LedgerDSL<out T : TransactionDSLInterpreter, out L : LedgerDSLInterpreter<
fun transaction(label: String? = null, transactionBuilder: TransactionBuilder = TransactionBuilder(notary = DUMMY_NOTARY),
dsl: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail) =
_transaction(label, transactionBuilder, dsl)
/**
* @see LedgerDSLInterpreter._unverifiedTransaction
*/

View File

@ -4,13 +4,13 @@ import com.google.common.net.HostAndPort
import java.io.IOException
import java.io.InputStreamReader
import java.net.ConnectException
import java.net.SocketException
import java.net.HttpURLConnection
import java.net.SocketException
import java.net.URL
import kotlin.test.assertEquals
class NodeApi {
class NodeDidNotStartException(message: String): Exception(message)
class NodeDidNotStartException(message: String) : Exception(message)
companion object {
// Increased timeout to two minutes.

View File

@ -200,8 +200,8 @@ data class TestLedgerDSLInterpreter private constructor(
internal inline fun <reified S : ContractState> resolveStateRef(stateRef: StateRef): TransactionState<S> {
val transactionWithLocation =
transactionWithLocations[stateRef.txhash] ?:
nonVerifiedTransactionWithLocations[stateRef.txhash] ?:
throw TransactionResolutionException(stateRef.txhash)
nonVerifiedTransactionWithLocations[stateRef.txhash] ?:
throw TransactionResolutionException(stateRef.txhash)
val output = transactionWithLocation.transaction.outputs[stateRef.index]
return if (S::class.java.isAssignableFrom(output.data.javaClass)) @Suppress("UNCHECKED_CAST") {
output as TransactionState<S>

View File

@ -1,5 +1,6 @@
package net.corda.testing
import net.corda.testing.TestTimestamp.Companion.timestamp
import java.text.SimpleDateFormat
import java.util.*

View File

@ -84,6 +84,7 @@ class TransactionDSL<out T : TransactionDSLInterpreter>(val interpreter: T) : Tr
}
input(transaction.outRef<ContractState>(0).ref)
}
fun input(stateClosure: () -> ContractState) = input(stateClosure())
/**
@ -92,6 +93,7 @@ class TransactionDSL<out T : TransactionDSLInterpreter>(val interpreter: T) : Tr
@JvmOverloads
fun output(label: String? = null, notary: Party = DUMMY_NOTARY, encumbrance: Int? = null, contractStateClosure: () -> ContractState) =
_output(label, notary, encumbrance, contractStateClosure())
/**
* @see TransactionDSLInterpreter._output
*/
@ -106,6 +108,7 @@ class TransactionDSL<out T : TransactionDSLInterpreter>(val interpreter: T) : Tr
*/
fun command(vararg signers: CompositeKey, commandDataClosure: () -> CommandData) =
_command(listOf(*signers), commandDataClosure())
/**
* @see TransactionDSLInterpreter._command
*/

View File

@ -1,6 +1,5 @@
package net.corda.testing.http
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.common.net.HostAndPort
import java.net.URL
@ -11,6 +10,7 @@ class HttpApi(val root: URL) {
* @param data String values are assumed to be valid JSON. All other values will be mapped to JSON.
*/
fun putJson(path: String, data: Any = Unit) = HttpUtils.putJson(URL(root, path), toJson(data))
/**
* Send a POST with a payload to the path on the API specified.
*
@ -21,7 +21,7 @@ class HttpApi(val root: URL) {
/**
* Send a GET request to the path on the API specified.
*/
inline fun<reified T: Any> getJson(path: String, params: Map<String, String> = mapOf()) = HttpUtils.getJson<T>(URL(root, path), params)
inline fun <reified T : Any> getJson(path: String, params: Map<String, String> = mapOf()) = HttpUtils.getJson<T>(URL(root, path), params)
private fun toJson(any: Any) = any as? String ?: HttpUtils.defaultMapper.writeValueAsString(any)

View File

@ -25,18 +25,18 @@ object HttpUtils {
ObjectMapper().registerModule(JavaTimeModule()).registerModule(KotlinModule())
}
fun putJson(url: URL, data: String) : Boolean {
fun putJson(url: URL, data: String): Boolean {
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data)
return makeRequest(Request.Builder().url(url).header("Content-Type", "application/json").put(body).build())
}
fun postJson(url: URL, data: String) : Boolean {
fun postJson(url: URL, data: String): Boolean {
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data)
return makeRequest(Request.Builder().url(url).header("Content-Type", "application/json").post(body).build())
}
inline fun<reified T: Any> getJson(url: URL, params: Map<String, String> = mapOf()) : T {
val paramString = if(params.isEmpty()) "" else "?" + params.map { "${it.key}=${it.value}" }.joinToString("&")
inline fun <reified T : Any> getJson(url: URL, params: Map<String, String> = mapOf()): T {
val paramString = if (params.isEmpty()) "" else "?" + params.map { "${it.key}=${it.value}" }.joinToString("&")
val parameterisedUrl = URL(url.toExternalForm() + paramString)
return defaultMapper.readValue(parameterisedUrl, T::class.java)
}

View File

@ -17,7 +17,7 @@ import rx.subjects.PublishSubject
class MockNetworkMapCache : InMemoryNetworkMapCache() {
override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>()
data class MockAddress(val id: String): SingleMessageRecipient
data class MockAddress(val id: String) : SingleMessageRecipient
init {
val mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")), MOCK_VERSION)
@ -41,7 +41,7 @@ class MockNetworkMapCache : InMemoryNetworkMapCache() {
* not a change being received.
*/
@VisibleForTesting
fun deleteRegistration(legalIdentity: Party) : Boolean {
fun deleteRegistration(legalIdentity: Party): Boolean {
return registeredNodes.remove(legalIdentity.owningKey) != null
}
}

View File

@ -56,7 +56,7 @@ import java.util.concurrent.atomic.AtomicInteger
class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
private val threadPerNode: Boolean = false,
servicePeerAllocationStrategy: InMemoryMessagingNetwork.ServicePeerAllocationStrategy =
InMemoryMessagingNetwork.ServicePeerAllocationStrategy.Random(),
InMemoryMessagingNetwork.ServicePeerAllocationStrategy.Random(),
private val defaultFactory: Factory = MockNetwork.DefaultFactory) {
private var nextNodeId = 0
val filesystem: FileSystem = Jimfs.newFileSystem(unix())
@ -246,7 +246,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
fun createNode(networkMapAddress: SingleMessageRecipient? = null, forcedID: Int = -1, nodeFactory: Factory = defaultFactory,
start: Boolean = true, legalName: String? = null, overrideServices: Map<ServiceInfo, KeyPair>? = null,
vararg advertisedServices: ServiceInfo): MockNode
= createNode(networkMapAddress, forcedID, nodeFactory, start, legalName, overrideServices, BigInteger.valueOf(random63BitValue()), *advertisedServices)
= createNode(networkMapAddress, forcedID, nodeFactory, start, legalName, overrideServices, BigInteger.valueOf(random63BitValue()), *advertisedServices)
/**
* Returns a node, optionally created by the passed factory method.

View File

@ -85,7 +85,10 @@ class MockIdentityService(val identities: List<Party>) : IdentityService, Single
private val nameToParties: Map<String, Party>
get() = synchronized(identities) { identities.associateBy { it.name } }
override fun registerIdentity(party: Party) { throw UnsupportedOperationException() }
override fun registerIdentity(party: Party) {
throw UnsupportedOperationException()
}
override fun getAllIdentities(): Iterable<Party> = ArrayList(keyToParties.values)
override fun partyFromAnonymous(party: AnonymousParty): Party? = keyToParties[party.owningKey]
override fun partyFromAnonymous(partyRef: PartyAndReference): Party? = partyFromAnonymous(partyRef.party)
@ -171,7 +174,7 @@ class MockStorageService(override val attachments: AttachmentStorage = MockAttac
override val validatedTransactions: TransactionStorage = MockTransactionStorage(),
override val uploaders: List<FileUploader> = listOf<FileUploader>(),
override val stateMachineRecordedTransactionMapping: StateMachineRecordedTransactionMappingStorage = MockStateMachineRecordedTransactionMappingStorage())
: SingletonSerializeAsToken(), TxWritableStorageService
: SingletonSerializeAsToken(), TxWritableStorageService
/**
* Make properties appropriate for creating a DataSource for unit tests.

View File

@ -6,8 +6,8 @@ import com.google.common.util.concurrent.SettableFuture
import net.corda.core.crypto.composite
import net.corda.core.crypto.generateKeyPair
import net.corda.core.messaging.RPCOps
import net.corda.testing.MOCK_NODE_VERSION_INFO
import net.corda.node.services.RPCUserServiceImpl
import net.corda.node.services.api.MonitoringService
import net.corda.node.services.config.NodeConfiguration
import net.corda.node.services.messaging.ArtemisMessagingServer
import net.corda.node.services.messaging.NodeMessagingClient
@ -15,12 +15,12 @@ import net.corda.node.services.network.InMemoryNetworkMapCache
import net.corda.node.utilities.AffinityExecutor.ServiceAffinityExecutor
import net.corda.node.utilities.configureDatabase
import net.corda.node.utilities.databaseTransaction
import net.corda.testing.MOCK_NODE_VERSION_INFO
import net.corda.testing.freeLocalHostAndPort
import org.jetbrains.exposed.sql.Database
import java.io.Closeable
import java.security.KeyPair
import kotlin.concurrent.thread
import net.corda.node.services.api.MonitoringService
/**
* This is a bare-bones node which can only send and receive messages. It doesn't register with a network map service or
@ -51,7 +51,9 @@ class SimpleNode(val config: NodeConfiguration, val address: HostAndPort = freeL
fun start() {
broker.start()
net.start(
object : RPCOps { override val protocolVersion = 0 },
object : RPCOps {
override val protocolVersion = 0
},
userService)
thread(name = config.myLegalName) {
net.run()