Reformat files in testing

This commit is contained in:
Tommy Lillehagen
2017-10-06 15:32:23 +01:00
parent f98942d7ad
commit fcc4bdae7e
47 changed files with 1327 additions and 1269 deletions

View File

@ -13,7 +13,8 @@ import java.util.concurrent.CompletableFuture.supplyAsync
class AttachmentDemoTest {
// run with a 10,000,000 bytes in-memory zip file. In practice, a slightly bigger file will be used (~10,002,000 bytes).
@Test fun `attachment demo using a 10MB zip file`() {
@Test
fun `attachment demo using a 10MB zip file`() {
val numOfExpectedBytes = 10_000_000
driver(isDebug = true, portAllocation = PortAllocation.Incremental(20000)) {
val demoUser = listOf(User("demo", "demo", setOf(startFlowPermission<AttachmentDemoFlow>())))

View File

@ -141,7 +141,8 @@ class FloatingRatePaymentEvent(date: LocalDate,
val CSVHeader = RatePaymentEvent.CSVHeader + ",FixingDate"
}
override val flow: Amount<Currency> get() {
override val flow: Amount<Currency>
get() {
// TODO: Should an uncalculated amount return a zero ? null ? etc.
val v = rate.ratioUnit?.value ?: return Amount(0, notional.token)
return Amount(dayCountFactor.times(BigDecimal(notional.quantity)).times(v).toLong(), notional.token)

View File

@ -141,6 +141,7 @@ class IRSSimulation(networkSendManuallyPumped: Boolean, runAsync: Boolean, laten
node2.internals.registerInitiatedFlow(FixingFlow.Fixer::class.java)
val notaryId = node1.rpcOps.notaryIdentities().first()
@InitiatingFlow
class StartDealFlow(val otherParty: Party,
val payload: AutoOffer) : FlowLogic<SignedTransaction>() {

View File

@ -162,8 +162,10 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean,
// These are used from the network visualiser tool.
private val _allFlowSteps = PublishSubject.create<Pair<SimulatedNode, ProgressTracker.Change>>()
private val _doneSteps = PublishSubject.create<Collection<SimulatedNode>>()
@Suppress("unused") val allFlowSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allFlowSteps
@Suppress("unused") val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
@Suppress("unused")
val allFlowSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allFlowSteps
@Suppress("unused")
val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
private var pumpCursor = 0

View File

@ -21,7 +21,8 @@ class IRSSimulationTest {
unsetCordappPackages()
}
@Test fun `runs to completion`() {
@Test
fun `runs to completion`() {
LogHelper.setLevel("+messages") // FIXME: Don't manipulate static state in tests.
val sim = IRSSimulation(false, false, null)
val future = sim.start()

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata;

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata;
@ -25,6 +25,7 @@ public final class ExampleData {
}
//-------------------------------------------------------------------------
/**
* Loads a golden copy of expected results from a text file.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata;
@ -22,6 +22,7 @@ public final class ExampleMarketData {
}
//-------------------------------------------------------------------------
/**
* Gets a market data builder for the built-in example market data.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata;
@ -93,6 +93,7 @@ public abstract class ExampleMarketDataBuilder {
private static final String QUOTES_FILE = "quotes.csv";
//-------------------------------------------------------------------------
/**
* Creates an instance from a given classpath resource root location using the class loader
* which created this class.
@ -165,6 +166,7 @@ public abstract class ExampleMarketDataBuilder {
}
//-------------------------------------------------------------------------
/**
* Builds a market data snapshot from this environment.
*
@ -393,6 +395,7 @@ public abstract class ExampleMarketDataBuilder {
}
//-------------------------------------------------------------------------
/**
* Gets all available resources from a given subdirectory.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata;

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;
@ -186,6 +186,7 @@ public class MarkitIndexCreditCurveDataParser {
}
//-------------------------------------------------------------------------
/**
* Stores the parsed static data.
*/
@ -222,6 +223,7 @@ public class MarkitIndexCreditCurveDataParser {
}
//-------------------------------------------------------------------------
/**
* Stores the parsed data points.
*/

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;
@ -32,6 +32,7 @@ public final class MarkitRedCode
public static final String MARKIT_REDCODE_SCHEME = "MarkitRedCode";
//-------------------------------------------------------------------------
/**
* Obtains an instance from the specified name.
* <p>
@ -78,6 +79,7 @@ public final class MarkitRedCode
}
//-------------------------------------------------------------------------
/**
* Converts this RED code to a standard identifier.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;
@ -48,6 +48,7 @@ public enum MarkitRestructuringClause {
XR14;
//-------------------------------------------------------------------------
/**
* Converts Markit code to standard restructuring clause.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;
@ -40,6 +40,7 @@ public enum MarkitSeniorityLevel {
JRSUBUT2;
//-------------------------------------------------------------------------
/**
* Converts Markit code to standard seniority level.
*

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;

View File

@ -1,6 +1,6 @@
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
*/
package com.opengamma.strata.examples.marketdata.credit.markit;
@ -98,6 +98,7 @@ public class MarkitYieldCurveDataParser {
}
//-------------------------------------------------------------------------
/**
* Stores the parsed data points.
*/

View File

@ -1,7 +1,9 @@
/**
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
* <p>
* Credit market data for examples.
*/
/**

View File

@ -1,7 +1,9 @@
/**
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* <p>
* Please see distribution for license.
* <p>
* Market data for examples.
*/
/**

View File

@ -254,7 +254,8 @@ class PortfolioApi(val rpc: CordaRPCOps) {
val parties = rpc.networkMapSnapshot()
val notaries = rpc.notaryIdentities()
// TODO We are not able to filter by network map node now
val counterParties = parties.filterNot { it.legalIdentities.any { it in notaries }
val counterParties = parties.filterNot {
it.legalIdentities.any { it in notaries }
|| ownParty in it.legalIdentities
}
return AvailableParties(

View File

@ -70,6 +70,7 @@ object SimmFlow {
private val existing: StateAndRef<PortfolioState>?)
: FlowLogic<RevisionedState<PortfolioState.Update>>() {
constructor(otherParty: Party, valuationDate: LocalDate) : this(otherParty, valuationDate, null)
lateinit var notary: Party
lateinit var otherPartySession: FlowSession

View File

@ -108,7 +108,7 @@ public class SwapExampleX {
/**
* Loads the curve group definition from data files.
*
* <p>
* A curve group maps from curve name to index for forward curves and curve name to currency for discount curves.
*/
private static CurveGroupDefinition loadCurveGroup() {

View File

@ -27,7 +27,8 @@ import java.util.*
* Interface for communicating with nodes running the trader demo.
*/
class TraderDemoClientApi(val rpc: CordaRPCOps) {
val cashCount: Long get() {
val cashCount: Long
get() {
val count = builder { VaultSchemaV1.VaultStates::recordedTime.count() }
val countCriteria = QueryCriteria.VaultCustomQueryCriteria(count)
return rpc.vaultQueryBy<Cash.State>(countCriteria).otherResults.single() as Long
@ -35,7 +36,8 @@ class TraderDemoClientApi(val rpc: CordaRPCOps) {
val dollarCashBalance: Amount<Currency> get() = rpc.getCashBalance(USD)
val commercialPaperCount: Long get() {
val commercialPaperCount: Long
get() {
val count = builder { VaultSchemaV1.VaultStates::recordedTime.count() }
val countCriteria = QueryCriteria.VaultCustomQueryCriteria(count)
return rpc.vaultQueryBy<CommercialPaper.State>(countCriteria).otherResults.single() as Long

View File

@ -31,7 +31,9 @@ class CommercialPaperIssueFlow(private val amount: Amount<Currency>,
companion object {
val PROSPECTUS_HASH = SecureHash.parse("decd098666b9657314870e192ced0c3519c2c9d395507a238338f8d003929de9")
object ISSUING : ProgressTracker.Step("Issuing and timestamping some commercial paper")
fun tracker() = ProgressTracker(ISSUING)
}

View File

@ -39,11 +39,13 @@ class PredefinedTestNode internal constructor(party: Party, driver: DriverDSLExp
* for it: you won't have [ALICE_KEY].
*/
fun DriverDSLExposedInterface.alice(): PredefinedTestNode = PredefinedTestNode(ALICE, this, null)
/**
* Returns a plain, entirely stock node pre-configured with the [BOB] identity. Note that a random key will be generated
* for it: you won't have [BOB_KEY].
*/
fun DriverDSLExposedInterface.bob(): PredefinedTestNode = PredefinedTestNode(BOB, this, null)
/**
* Returns a plain single node notary pre-configured with the [DUMMY_NOTARY] identity. Note that a random key will be generated
* for it: you won't have [DUMMY_NOTARY_KEY].

View File

@ -20,7 +20,8 @@ import java.nio.file.Path
* 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.
*/
@JvmOverloads fun ledger(
@JvmOverloads
fun ledger(
services: ServiceHub = MockServices(),
initialiseSerialization: Boolean = true,
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit
@ -40,7 +41,8 @@ import java.nio.file.Path
*
* @see LedgerDSLInterpreter._transaction
*/
@JvmOverloads fun transaction(
@JvmOverloads
fun transaction(
transactionLabel: String? = null,
transactionBuilder: TransactionBuilder = TransactionBuilder(notary = DUMMY_NOTARY),
initialiseSerialization: Boolean = true,
@ -54,6 +56,7 @@ fun testNodeConfiguration(
myLegalName: CordaX500Name,
notaryConfig: NotaryConfig? = null): NodeConfiguration {
abstract class MockableNodeConfiguration : NodeConfiguration // Otherwise Mockito is defeated by val getters.
val nc = spy<MockableNodeConfiguration>()
whenever(nc.baseDirectory).thenReturn(baseDirectory)
whenever(nc.myLegalName).thenReturn(myLegalName)

View File

@ -180,16 +180,19 @@ interface RPCDriverExposedDSLInterface : DriverDSLExposedInterface {
brokerHandle: RpcBrokerHandle
): RpcServerHandle
}
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startInVmRpcClient(
username: String = rpcTestUser.username,
password: String = rpcTestUser.password,
configuration: RPCClientConfiguration = RPCClientConfiguration.default
) = startInVmRpcClient(I::class.java, username, password, configuration)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRandomRpcClient(
hostAndPort: NetworkHostAndPort,
username: String = rpcTestUser.username,
password: String = rpcTestUser.password
) = startRandomRpcClient(I::class.java, hostAndPort, username, password)
inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
rpcAddress: NetworkHostAndPort,
username: String = rpcTestUser.username,
@ -200,7 +203,8 @@ inline fun <reified I : RPCOps> RPCDriverExposedDSLInterface.startRpcClient(
interface RPCDriverInternalDSLInterface : DriverDSLInternalInterface, RPCDriverExposedDSLInterface
data class RpcBrokerHandle(
val hostAndPort: NetworkHostAndPort?,/** null if this is an InVM broker */
val hostAndPort: NetworkHostAndPort?,
/** null if this is an InVM broker */
val clientTransportConfiguration: TransportConfiguration,
val serverControl: ActiveMQServerControl
)
@ -253,6 +257,7 @@ private class SingleUserSecurityManager(val rpcUser: User) : ActiveMQSecurityMan
override fun validateUser(user: String?, password: String?, certificates: Array<out X509Certificate>?): String? {
return validate(user, password)
}
override fun validateUserAndRole(user: String?, password: String?, roles: MutableSet<Role>?, checkType: CheckType?, address: String?, connection: RemotingConnection?): String? {
return validate(user, password)
}
@ -260,6 +265,7 @@ private class SingleUserSecurityManager(val rpcUser: User) : ActiveMQSecurityMan
private fun isValid(user: String?, password: String?): Boolean {
return rpcUser.username == user && rpcUser.password == password
}
private fun validate(user: String?, password: String?): String? {
return if (isValid(user, password)) user else null
}
@ -303,6 +309,7 @@ data class RPCDriverDSL(
}
)
}
fun createInVmRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long): Configuration {
return ConfigurationImpl().apply {
acceptorConfigurations = setOf(TransportConfiguration(InVMAcceptorFactory::class.java.name))
@ -310,6 +317,7 @@ data class RPCDriverDSL(
configureCommonSettings(maxFileSize, maxBufferedBytesPerClient)
}
}
fun createRpcServerArtemisConfig(maxFileSize: Int, maxBufferedBytesPerClient: Long, baseDirectory: Path, hostAndPort: NetworkHostAndPort): Configuration {
val connectionDirection = ConnectionDirection.Inbound(acceptorFactoryClassName = NettyAcceptorFactory::class.java.name)
return ConfigurationImpl().apply {
@ -321,6 +329,7 @@ data class RPCDriverDSL(
configureCommonSettings(maxFileSize, maxBufferedBytesPerClient)
}
}
val inVmClientTransportConfiguration = TransportConfiguration(InVMConnectorFactory::class.java.name)
fun createNettyClientTransportConfiguration(hostAndPort: NetworkHostAndPort): TransportConfiguration {
return ArtemisTcpTransport.tcpTransport(ConnectionDirection.Outbound(), hostAndPort, null)
@ -503,6 +512,7 @@ class RandomRpcUser {
add(Generator.string())
add(Generator.int())
}
data class Call(val method: Method, val call: () -> Any?)
@JvmStatic

View File

@ -143,7 +143,8 @@ class InMemoryMessagingNetwork(
}
/** This can be set to an object which can inject artificial latency between sender/recipient pairs. */
@Volatile var latencyCalculator: LatencyCalculator? = null
@Volatile
var latencyCalculator: LatencyCalculator? = null
private val timer = Timer()
@Synchronized

View File

@ -247,7 +247,9 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
// This does not indirect through the NodeInfo object so it can be called before the node is started.
// It is used from the network visualiser tool.
@Suppress("unused") val place: WorldMapLocation get() = findMyLocation()!!
@Suppress("unused")
val place: WorldMapLocation
get() = findMyLocation()!!
private var dbCloser: (() -> Any?)? = null
override fun <T> initialiseDatabasePersistence(schemaService: SchemaService, insideTransaction: () -> T) = super.initialiseDatabasePersistence(schemaService) {

View File

@ -82,7 +82,9 @@ open class MockServices(
fun makeTestDatabaseProperties(key: String? = null, value: String? = null): Properties {
val props = Properties()
props.setProperty("transactionIsolationLevel", "repeatableRead") //for other possible values see net.corda.node.utilities.CordaPeristence.parserTransactionIsolationLevel(String)
if (key != null) { props.setProperty(key, value) }
if (key != null) {
props.setProperty(key, value)
}
return props
}
@ -154,7 +156,8 @@ open class MockServices(
override val contractUpgradeService: ContractUpgradeService get() = throw UnsupportedOperationException()
override val networkMapCache: NetworkMapCache get() = throw UnsupportedOperationException()
override val clock: Clock get() = Clock.systemUTC()
override val myInfo: NodeInfo get() {
override val myInfo: NodeInfo
get() {
val identity = getTestPartyAndCertificate(MEGA_CORP.name, key.public)
return NodeInfo(emptyList(), listOf(identity), 1, serial = 1L)
}

View File

@ -25,7 +25,8 @@ class TestClock(private var delegateClock: Clock = Clock.systemUTC()) : MutableC
/**
* Advance this [Clock] by the specified [Duration] for testing purposes.
*/
@Synchronized fun advanceBy(duration: Duration) {
@Synchronized
fun advanceBy(duration: Duration) {
delegateClock = offset(delegateClock, duration)
notifyMutationObservers()
}
@ -35,7 +36,8 @@ class TestClock(private var delegateClock: Clock = Clock.systemUTC()) : MutableC
*
* This will only be approximate due to the time ticking away, but will be some time shortly after the requested [Instant].
*/
@Synchronized fun setTo(newInstant: Instant) = advanceBy(instant() until newInstant)
@Synchronized
fun setTo(newInstant: Instant) = advanceBy(instant() until newInstant)
@Synchronized override fun instant(): Instant {
return delegateClock.instant()

View File

@ -46,6 +46,7 @@ class NodeProcess(
class Factory(val buildDirectory: Path = Paths.get("build"),
val cordaJar: Path = Paths.get(this::class.java.getResource("/corda.jar").toURI())) {
val nodesDirectory = buildDirectory / formatter.format(Instant.now())
init {
nodesDirectory.createDirectories()
}

View File

@ -165,6 +165,7 @@ inline fun <reified T : Any> T.amqpSpecific(reason: String, function: () -> Unit
* TODO: Should be removed after multiple identities are introduced.
*/
fun NodeInfo.chooseIdentityAndCert(): PartyAndCertificate = legalIdentitiesAndCerts.first()
fun NodeInfo.chooseIdentity(): Party = chooseIdentityAndCert().party
/** Returns the identity of the first notary found on the network */
fun ServiceHub.getDefaultNotary(): Party = networkMapCache.notaryIdentities.first()

View File

@ -14,7 +14,8 @@ inline fun <reified E : Throwable, R>eventually(duration: Duration, f: () -> R):
return f()
} catch (e: Throwable) {
when (e) {
is E -> {}// ignore and continue
is E -> {
}// ignore and continue
else -> throw e // unexpected exception type - rethrow
}
}

View File

@ -78,7 +78,8 @@ class FlowStackSnapshotFactoryImpl : FlowStackSnapshotFactory {
return FlowStackSnapshot(Instant.now(), flowClass.name, frames)
}
private val StackTraceElement.instrumentedAnnotation: Instrumented? get() {
private val StackTraceElement.instrumentedAnnotation: Instrumented?
get() {
Class.forName(className).methods.forEach {
if (it.name == methodName && it.isAnnotationPresent(Instrumented::class.java)) {
return it.getAnnotation(Instrumented::class.java)

View File

@ -12,10 +12,13 @@ import kotlin.reflect.jvm.reflect
fun <A : Any, R> measure(a: Iterable<A>, f: (A) -> R) =
measure(listOf(a), f.reflect()!!) { f(uncheckedCast(it[0])) }
fun <A : Any, B : Any, R> measure(a: Iterable<A>, b: Iterable<B>, f: (A, B) -> R) =
measure(listOf(a, b), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1])) }
fun <A : Any, B : Any, C : Any, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, f: (A, B, C) -> R) =
measure(listOf(a, b, c), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1]), uncheckedCast(it[2])) }
fun <A : Any, B : Any, C : Any, D : Any, R> measure(a: Iterable<A>, b: Iterable<B>, c: Iterable<C>, d: Iterable<D>, f: (A, B, C, D) -> R) =
measure(listOf(a, b, c, d), f.reflect()!!) { f(uncheckedCast(it[0]), uncheckedCast(it[1]), uncheckedCast(it[2]), uncheckedCast(it[3])) }

View File

@ -19,8 +19,7 @@ class DummyDealContract : Contract {
data class State(
override val participants: List<AbstractParty>,
override val linearId: UniqueIdentifier) : DealState, QueryableState
{
override val linearId: UniqueIdentifier) : DealState, QueryableState {
constructor(participants: List<AbstractParty> = listOf(),
ref: String) : this(participants, UniqueIdentifier(ref))

View File

@ -29,6 +29,7 @@ class HttpApi(val root: URL, val mapper: ObjectMapper = defaultMapper) {
companion object {
fun fromHostAndPort(hostAndPort: NetworkHostAndPort, base: String, protocol: String = "http", mapper: ObjectMapper = defaultMapper): HttpApi
= HttpApi(URL("$protocol://$hostAndPort/$base/"), mapper)
private val defaultMapper: ObjectMapper by lazy {
net.corda.client.jackson.JacksonSupport.createNonRpcMapper()
}