CORDA-716 Retire TestDependencyInjectionBase (#1939)

This commit is contained in:
Andrzej Cichocki 2017-10-31 10:21:38 +00:00 committed by GitHub
parent 02a5ddb7df
commit 4b0b13dad4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
56 changed files with 433 additions and 316 deletions

View File

@ -2490,19 +2490,19 @@ public static final class net.corda.core.serialization.SerializationContext$UseC
public static net.corda.core.serialization.SerializationContext$UseCase valueOf(String)
public static net.corda.core.serialization.SerializationContext$UseCase[] values()
##
public final class net.corda.core.serialization.SerializationDefaults extends java.lang.Object
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationContext getCHECKPOINT_CONTEXT()
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationContext getP2P_CONTEXT()
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationContext getRPC_CLIENT_CONTEXT()
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationContext getRPC_SERVER_CONTEXT()
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationFactory getSERIALIZATION_FACTORY()
@org.jetbrains.annotations.NotNull public final net.corda.core.serialization.SerializationContext getSTORAGE_CONTEXT()
public final void setCHECKPOINT_CONTEXT(net.corda.core.serialization.SerializationContext)
public final void setP2P_CONTEXT(net.corda.core.serialization.SerializationContext)
public final void setRPC_CLIENT_CONTEXT(net.corda.core.serialization.SerializationContext)
public final void setRPC_SERVER_CONTEXT(net.corda.core.serialization.SerializationContext)
public final void setSERIALIZATION_FACTORY(net.corda.core.serialization.SerializationFactory)
public final void setSTORAGE_CONTEXT(net.corda.core.serialization.SerializationContext)
public final class net.corda.core.serialization.SerializationDefaults extends java.lang.Object implements net.corda.core.serialization.internal.SerializationEnvironment
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationContext getCHECKPOINT_CONTEXT()
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationContext getP2P_CONTEXT()
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationContext getRPC_CLIENT_CONTEXT()
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationContext getRPC_SERVER_CONTEXT()
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationFactory getSERIALIZATION_FACTORY()
@org.jetbrains.annotations.NotNull public net.corda.core.serialization.SerializationContext getSTORAGE_CONTEXT()
public void setCHECKPOINT_CONTEXT(net.corda.core.serialization.SerializationContext)
public void setP2P_CONTEXT(net.corda.core.serialization.SerializationContext)
public void setRPC_CLIENT_CONTEXT(net.corda.core.serialization.SerializationContext)
public void setRPC_SERVER_CONTEXT(net.corda.core.serialization.SerializationContext)
public void setSERIALIZATION_FACTORY(net.corda.core.serialization.SerializationFactory)
public void setSTORAGE_CONTEXT(net.corda.core.serialization.SerializationContext)
public static final net.corda.core.serialization.SerializationDefaults INSTANCE
##
public abstract class net.corda.core.serialization.SerializationFactory extends java.lang.Object

View File

@ -12,18 +12,22 @@ import net.corda.finance.USD
import net.corda.testing.*
import net.corda.testing.contracts.DummyContract
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.math.BigInteger
import java.security.PublicKey
import java.util.*
import kotlin.test.assertEquals
class JacksonSupportTest : TestDependencyInjectionBase() {
class JacksonSupportTest {
companion object {
private val SEED = BigInteger.valueOf(20170922L)
val mapper = JacksonSupport.createNonRpcMapper()
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var services: ServiceHub
private lateinit var cordappProvider: CordappProvider

View File

@ -3,6 +3,7 @@ package net.corda.core.serialization
import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.sha256
import net.corda.core.internal.WriteOnceProperty
import net.corda.core.serialization.internal.SerializationEnvironment
import net.corda.core.utilities.ByteSequence
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.sequence
@ -172,13 +173,13 @@ interface SerializationContext {
/**
* Global singletons to be used as defaults that are injected elsewhere (generally, in the node or in RPC client).
*/
object SerializationDefaults {
var SERIALIZATION_FACTORY: SerializationFactory by WriteOnceProperty()
var P2P_CONTEXT: SerializationContext by WriteOnceProperty()
var RPC_SERVER_CONTEXT: SerializationContext by WriteOnceProperty()
var RPC_CLIENT_CONTEXT: SerializationContext by WriteOnceProperty()
var STORAGE_CONTEXT: SerializationContext by WriteOnceProperty()
var CHECKPOINT_CONTEXT: SerializationContext by WriteOnceProperty()
object SerializationDefaults : SerializationEnvironment {
override var SERIALIZATION_FACTORY: SerializationFactory by WriteOnceProperty()
override var P2P_CONTEXT: SerializationContext by WriteOnceProperty()
override var RPC_SERVER_CONTEXT: SerializationContext by WriteOnceProperty()
override var RPC_CLIENT_CONTEXT: SerializationContext by WriteOnceProperty()
override var STORAGE_CONTEXT: SerializationContext by WriteOnceProperty()
override var CHECKPOINT_CONTEXT: SerializationContext by WriteOnceProperty()
}
/**

View File

@ -0,0 +1,13 @@
package net.corda.core.serialization.internal
import net.corda.core.serialization.SerializationContext
import net.corda.core.serialization.SerializationFactory
interface SerializationEnvironment {
val SERIALIZATION_FACTORY: SerializationFactory
val P2P_CONTEXT: SerializationContext
val RPC_SERVER_CONTEXT: SerializationContext
val RPC_CLIENT_CONTEXT: SerializationContext
val STORAGE_CONTEXT: SerializationContext
val CHECKPOINT_CONTEXT: SerializationContext
}

View File

@ -8,13 +8,16 @@ import net.corda.core.utilities.OpaqueBytes
import net.corda.testing.*
import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState
import org.junit.Rule
import org.junit.Test
import java.time.Instant
import java.util.function.Predicate
import kotlin.test.*
class CompatibleTransactionTests : TestDependencyInjectionBase() {
class CompatibleTransactionTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val dummyOutState = TransactionState(DummyState(0), DummyContract.PROGRAM_ID, DUMMY_NOTARY)
private val stateRef1 = StateRef(SecureHash.randomSHA256(), 0)
private val stateRef2 = StateRef(SecureHash.randomSHA256(), 1)

View File

@ -4,10 +4,11 @@ import net.corda.core.crypto.SecureHash
import net.corda.core.internal.UpgradeCommand
import net.corda.testing.ALICE
import net.corda.testing.DUMMY_NOTARY
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyContractV2
import net.corda.testing.node.MockServices
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@ -15,7 +16,11 @@ import kotlin.test.assertTrue
/**
* Tests for the version 2 dummy contract, to cover ensuring upgrade transactions are built correctly.
*/
class DummyContractV2Tests : TestDependencyInjectionBase() {
class DummyContractV2Tests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `upgrade from v1`() {
val services = MockServices()

View File

@ -3,21 +3,21 @@ package net.corda.core.contracts
import net.corda.core.identity.AbstractParty
import net.corda.core.transactions.LedgerTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.testing.DUMMY_NOTARY
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.chooseIdentity
import net.corda.testing.*
import net.corda.testing.contracts.DummyContract
import net.corda.testing.dummyCommand
import net.corda.testing.node.MockServices
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.function.Predicate
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class LedgerTransactionQueryTests : TestDependencyInjectionBase() {
class LedgerTransactionQueryTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val services: MockServices = MockServices()
@Before

View File

@ -10,14 +10,18 @@ import net.corda.finance.contracts.asset.DUMMY_CASH_ISSUER_KEY
import net.corda.testing.*
import net.corda.testing.contracts.DummyContract
import net.corda.testing.node.MockAttachment
import net.corda.testing.node.MockAttachmentStorage
import org.junit.Rule
import org.junit.Test
import java.security.KeyPair
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
class TransactionTests : TestDependencyInjectionBase() {
class TransactionTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private fun makeSigned(wtx: WireTransaction, vararg keys: KeyPair, notarySig: Boolean = true): SignedTransaction {
val keySigs = keys.map { it.sign(SignableData(wtx.id, SignatureMetadata(1, Crypto.findSignatureScheme(it.public).schemeNumberID))) }
val sigs = if (notarySig) {

View File

@ -9,8 +9,8 @@ import net.corda.core.serialization.serialize
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.toBase58String
import net.corda.node.utilities.*
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.kryoSpecific
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
@ -20,7 +20,10 @@ import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class CompositeKeyTests : TestDependencyInjectionBase() {
class CompositeKeyTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Rule
@JvmField
val tempFolder: TemporaryFolder = TemporaryFolder()

View File

@ -10,6 +10,7 @@ import net.corda.finance.DOLLARS
import net.corda.finance.`issued by`
import net.corda.finance.contracts.asset.Cash
import net.corda.testing.*
import org.junit.Rule
import org.junit.Test
import java.security.PublicKey
import java.util.function.Predicate
@ -17,14 +18,14 @@ import java.util.stream.IntStream
import kotlin.streams.toList
import kotlin.test.*
class PartialMerkleTreeTest : TestDependencyInjectionBase() {
class PartialMerkleTreeTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val nodes = "abcdef"
private val hashed = nodes.map {
initialiseTestSerialization()
try {
it.serialize().sha256()
} finally {
resetTestSerialization()
private val hashed = nodes.map { node ->
withTestSerialization {
node.serialize().sha256()
}
}
private val expectedRoot = MerkleTree.getMerkleTree(hashed.toMutableList() + listOf(zeroHash, zeroHash)).hash

View File

@ -2,13 +2,18 @@ package net.corda.core.crypto
import net.corda.core.serialization.SerializedBytes
import net.corda.core.serialization.serialize
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.security.SignatureException
import kotlin.test.assertEquals
class SignedDataTest : TestDependencyInjectionBase() {
class SignedDataTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Before
fun initialise() {
serialized = data.serialize()

View File

@ -1,6 +1,7 @@
package net.corda.core.crypto
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule
import org.junit.Test
import java.security.SignatureException
import kotlin.test.assertTrue
@ -8,8 +9,10 @@ import kotlin.test.assertTrue
/**
* Digital signature MetaData tests.
*/
class TransactionSignatureTest : TestDependencyInjectionBase() {
class TransactionSignatureTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
val testBytes = "12345678901234567890123456789012".toByteArray()
/** Valid sign and verify. */

View File

@ -6,47 +6,48 @@ import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize
import net.corda.node.utilities.KEYSTORE_TYPE
import net.corda.node.utilities.save
import net.corda.testing.SerializationEnvironmentRule
import net.corda.testing.getTestPartyAndCertificate
import net.corda.testing.withTestSerialization
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.math.BigInteger
import java.security.KeyStore
class PartyAndCertificateTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `kryo serialisation`() {
withTestSerialization {
val original = getTestPartyAndCertificate(Party(
CordaX500Name(organisation = "Test Corp", locality = "Madrid", country = "ES"),
entropyToKeyPair(BigInteger.valueOf(83)).public))
val copy = original.serialize().deserialize()
assertThat(copy).isEqualTo(original).isNotSameAs(original)
assertThat(copy.certPath).isEqualTo(original.certPath)
assertThat(copy.certificate).isEqualTo(original.certificate)
}
val original = getTestPartyAndCertificate(Party(
CordaX500Name(organisation = "Test Corp", locality = "Madrid", country = "ES"),
entropyToKeyPair(BigInteger.valueOf(83)).public))
val copy = original.serialize().deserialize()
assertThat(copy).isEqualTo(original).isNotSameAs(original)
assertThat(copy.certPath).isEqualTo(original.certPath)
assertThat(copy.certificate).isEqualTo(original.certificate)
}
@Test
fun `jdk serialization`() {
withTestSerialization {
val identity = getTestPartyAndCertificate(Party(
CordaX500Name(organisation = "Test Corp", locality = "Madrid", country = "ES"),
entropyToKeyPair(BigInteger.valueOf(83)).public))
val original = identity.certificate
val storePassword = "test"
val keyStoreFilePath = File.createTempFile("serialization_test", "jks").toPath()
var keyStore = KeyStore.getInstance(KEYSTORE_TYPE)
keyStore.load(null, storePassword.toCharArray())
keyStore.setCertificateEntry(identity.name.toString(), original)
keyStore.save(keyStoreFilePath, storePassword)
val identity = getTestPartyAndCertificate(Party(
CordaX500Name(organisation = "Test Corp", locality = "Madrid", country = "ES"),
entropyToKeyPair(BigInteger.valueOf(83)).public))
val original = identity.certificate
val storePassword = "test"
val keyStoreFilePath = File.createTempFile("serialization_test", "jks").toPath()
var keyStore = KeyStore.getInstance(KEYSTORE_TYPE)
keyStore.load(null, storePassword.toCharArray())
keyStore.setCertificateEntry(identity.name.toString(), original)
keyStore.save(keyStoreFilePath, storePassword)
// Load the key store back in again
keyStore = KeyStore.getInstance(KEYSTORE_TYPE)
keyStoreFilePath.read { keyStore.load(it, storePassword.toCharArray()) }
val copy = keyStore.getCertificate(identity.name.toString())
assertThat(copy).isEqualTo(original) // .isNotSameAs(original)
}
// Load the key store back in again
keyStore = KeyStore.getInstance(KEYSTORE_TYPE)
keyStoreFilePath.read { keyStore.load(it, storePassword.toCharArray()) }
val copy = keyStore.getCertificate(identity.name.toString())
assertThat(copy).isEqualTo(original) // .isNotSameAs(original)
}
}

View File

@ -2,11 +2,15 @@ package net.corda.core.serialization
import net.corda.finance.contracts.CommercialPaper
import net.corda.finance.contracts.asset.Cash
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
class CommandsSerializationTests : TestDependencyInjectionBase() {
class CommandsSerializationTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `test cash move serialization`() {

View File

@ -9,6 +9,7 @@ import net.corda.finance.POUNDS
import net.corda.testing.*
import net.corda.testing.node.MockServices
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.security.SignatureException
import java.util.*
@ -16,7 +17,10 @@ import kotlin.reflect.jvm.javaField
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class TransactionSerializationTests : TestDependencyInjectionBase() {
class TransactionSerializationTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val TEST_CASH_PROGRAM_ID = "net.corda.core.serialization.TransactionSerializationTests\$TestCash"
class TestCash : Contract {

View File

@ -5,11 +5,15 @@ import net.corda.core.crypto.SecureHash
import net.corda.core.node.services.UniquenessException
import net.corda.core.node.services.UniquenessProvider
import net.corda.testing.DUMMY_PARTY
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
class UniquenessExceptionSerializationTest : TestDependencyInjectionBase() {
class UniquenessExceptionSerializationTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun testSerializationRoundTrip() {

View File

@ -7,13 +7,16 @@ import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize
import net.corda.nodeapi.internal.serialization.KRYO_CHECKPOINT_CONTEXT
import net.corda.nodeapi.internal.serialization.KRYO_P2P_CONTEXT
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class KotlinUtilsTest : TestDependencyInjectionBase() {
class KotlinUtilsTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@JvmField
@Rule
val expectedEx: ExpectedException = ExpectedException.none()

View File

@ -7,8 +7,7 @@ import com.google.common.collect.testing.features.CollectionSize
import junit.framework.TestSuite
import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize
import net.corda.testing.initialiseTestSerialization
import net.corda.testing.resetTestSerialization
import net.corda.testing.withTestSerialization
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
@ -49,14 +48,10 @@ class NonEmptySetTest {
@Test
fun `serialize deserialize`() {
initialiseTestSerialization()
try {
withTestSerialization {
val original = NonEmptySet.of(-17, 22, 17)
val copy = original.serialize().deserialize()
assertThat(copy).isEqualTo(original).isNotSameAs(original)
} finally {
resetTestSerialization()
}
}
}

View File

@ -230,8 +230,7 @@ class CommercialPaperTestsGeneric {
// @Test
@Ignore
fun `issue move and then redeem`() {
initialiseTestSerialization()
fun `issue move and then redeem`() = withTestSerialization {
val aliceDatabaseAndServices = makeTestDatabaseAndMockServices(keys = listOf(ALICE_KEY))
val databaseAlice = aliceDatabaseAndServices.first
aliceServices = aliceDatabaseAndServices.second
@ -311,6 +310,5 @@ class CommercialPaperTestsGeneric {
validRedemption.toLedgerTransaction(aliceServices).verify()
// soft lock not released after success either!!! (as transaction not recorded)
}
resetTestSerialization()
}
}

View File

@ -29,7 +29,7 @@ import java.security.KeyPair
import java.util.*
import kotlin.test.*
class CashTests : TestDependencyInjectionBase() {
class CashTests {
private val defaultRef = OpaqueBytes(ByteArray(1, { 1 }))
private val defaultIssuer = MEGA_CORP.ref(defaultRef)
private val inState = Cash.State(
@ -51,7 +51,7 @@ class CashTests : TestDependencyInjectionBase() {
private lateinit var vaultStatesUnconsumed: List<StateAndRef<Cash.State>>
@Before
fun setUp() {
fun setUp() = withTestSerialization {
LogHelper.setLevel(NodeVaultService::class)
megaCorpServices = MockServices(listOf("net.corda.finance.contracts.asset"), MEGA_CORP_KEY)
val databaseAndServices = makeTestDatabaseAndMockServices(cordappPackages = listOf("net.corda.finance.contracts.asset"), keys = listOf(MINI_CORP_KEY, MEGA_CORP_KEY, OUR_KEY))
@ -72,7 +72,6 @@ class CashTests : TestDependencyInjectionBase() {
database.transaction {
vaultStatesUnconsumed = miniCorpServices.vaultService.queryBy<Cash.State>().states
}
resetTestSerialization()
}
@After
@ -154,8 +153,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateIssueRaw() {
initialiseTestSerialization()
fun generateIssueRaw() = withTestSerialization {
// Test generation works.
val tx: WireTransaction = TransactionBuilder(notary = null).apply {
Cash().generateIssue(this, 100.DOLLARS `issued by` MINI_CORP.ref(12, 34), owner = AnonymousParty(ALICE_PUBKEY), notary = DUMMY_NOTARY)
@ -170,8 +168,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateIssueFromAmount() {
initialiseTestSerialization()
fun generateIssueFromAmount() = withTestSerialization {
// Test issuance from an issued amount
val amount = 100.DOLLARS `issued by` MINI_CORP.ref(12, 34)
val tx: WireTransaction = TransactionBuilder(notary = null).apply {
@ -239,8 +236,7 @@ class CashTests : TestDependencyInjectionBase() {
* cash inputs.
*/
@Test(expected = IllegalStateException::class)
fun `reject issuance with inputs`() {
initialiseTestSerialization()
fun `reject issuance with inputs`() = withTestSerialization {
// Issue some cash
var ptx = TransactionBuilder(DUMMY_NOTARY)
@ -251,6 +247,7 @@ class CashTests : TestDependencyInjectionBase() {
ptx = TransactionBuilder(DUMMY_NOTARY)
ptx.addInputState(tx.tx.outRef<Cash.State>(0))
Cash().generateIssue(ptx, 100.DOLLARS `issued by` MINI_CORP.ref(12, 34), owner = MINI_CORP, notary = DUMMY_NOTARY)
Unit
}
@Test
@ -515,8 +512,7 @@ class CashTests : TestDependencyInjectionBase() {
* Try exiting an amount which matches a single state.
*/
@Test
fun generateSimpleExit() {
initialiseTestSerialization()
fun generateSimpleExit() = withTestSerialization {
val wtx = makeExit(miniCorpServices, 100.DOLLARS, MEGA_CORP, 1)
assertEquals(WALLET[0].ref, wtx.inputs[0])
assertEquals(0, wtx.outputs.size)
@ -531,8 +527,7 @@ class CashTests : TestDependencyInjectionBase() {
* Try exiting an amount smaller than the smallest available input state, and confirm change is generated correctly.
*/
@Test
fun generatePartialExit() {
initialiseTestSerialization()
fun generatePartialExit() = withTestSerialization {
val wtx = makeExit(miniCorpServices, 50.DOLLARS, MEGA_CORP, 1)
val actualInput = wtx.inputs.single()
// Filter the available inputs and confirm exactly one has been used
@ -549,53 +544,52 @@ class CashTests : TestDependencyInjectionBase() {
* Try exiting a currency we don't have.
*/
@Test
fun generateAbsentExit() {
initialiseTestSerialization()
fun generateAbsentExit() = withTestSerialization {
assertFailsWith<InsufficientBalanceException> { makeExit(miniCorpServices, 100.POUNDS, MEGA_CORP, 1) }
Unit
}
/**
* Try exiting with a reference mis-match.
*/
@Test
fun generateInvalidReferenceExit() {
initialiseTestSerialization()
fun generateInvalidReferenceExit() = withTestSerialization {
assertFailsWith<InsufficientBalanceException> { makeExit(miniCorpServices, 100.POUNDS, MEGA_CORP, 2) }
Unit
}
/**
* Try exiting an amount greater than the maximum available.
*/
@Test
fun generateInsufficientExit() {
initialiseTestSerialization()
fun generateInsufficientExit() = withTestSerialization {
assertFailsWith<InsufficientBalanceException> { makeExit(miniCorpServices, 1000.DOLLARS, MEGA_CORP, 1) }
Unit
}
/**
* Try exiting for an owner with no states
*/
@Test
fun generateOwnerWithNoStatesExit() {
initialiseTestSerialization()
fun generateOwnerWithNoStatesExit() = withTestSerialization {
assertFailsWith<InsufficientBalanceException> { makeExit(miniCorpServices, 100.POUNDS, CHARLIE, 1) }
Unit
}
/**
* Try exiting when vault is empty
*/
@Test
fun generateExitWithEmptyVault() {
initialiseTestSerialization()
fun generateExitWithEmptyVault() = withTestSerialization {
assertFailsWith<IllegalArgumentException> {
val tx = TransactionBuilder(DUMMY_NOTARY)
Cash().generateExit(tx, Amount(100, Issued(CHARLIE.ref(1), GBP)), emptyList(), OUR_IDENTITY_1)
}
Unit
}
@Test
fun generateSimpleDirectSpend() {
initialiseTestSerialization()
fun generateSimpleDirectSpend() = withTestSerialization {
val wtx =
database.transaction {
makeSpend(100.DOLLARS, THEIR_IDENTITY_1)
@ -609,8 +603,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateSimpleSpendWithParties() {
initialiseTestSerialization()
fun generateSimpleSpendWithParties() = withTestSerialization {
database.transaction {
val tx = TransactionBuilder(DUMMY_NOTARY)
@ -621,8 +614,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateSimpleSpendWithChange() {
initialiseTestSerialization()
fun generateSimpleSpendWithChange() = withTestSerialization {
val wtx =
database.transaction {
makeSpend(10.DOLLARS, THEIR_IDENTITY_1)
@ -647,8 +639,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateSpendWithTwoInputs() {
initialiseTestSerialization()
fun generateSpendWithTwoInputs() = withTestSerialization {
val wtx =
database.transaction {
makeSpend(500.DOLLARS, THEIR_IDENTITY_1)
@ -664,8 +655,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateSpendMixedDeposits() {
initialiseTestSerialization()
fun generateSpendMixedDeposits() = withTestSerialization {
val wtx =
database.transaction {
val wtx = makeSpend(580.DOLLARS, THEIR_IDENTITY_1)
@ -686,8 +676,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun generateSpendInsufficientBalance() {
initialiseTestSerialization()
fun generateSpendInsufficientBalance() = withTestSerialization {
database.transaction {
val e: InsufficientBalanceException = assertFailsWith("balance") {
@ -699,6 +688,7 @@ class CashTests : TestDependencyInjectionBase() {
makeSpend(81.SWISS_FRANCS, THEIR_IDENTITY_1)
}
}
Unit
}
/**
@ -825,8 +815,7 @@ class CashTests : TestDependencyInjectionBase() {
}
@Test
fun multiSpend() {
initialiseTestSerialization()
fun multiSpend() = withTestSerialization {
val tx = TransactionBuilder(DUMMY_NOTARY)
database.transaction {
val payments = listOf(

View File

@ -19,7 +19,6 @@ import net.corda.testing.*
import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState
import net.corda.testing.node.MockServices
import org.junit.After
import org.junit.Test
import java.time.Instant
import java.time.temporal.ChronoUnit
@ -64,11 +63,6 @@ class ObligationTests {
}
}
@After
fun reset() {
resetTestSerialization()
}
@Test
fun trivial() {
transaction {
@ -139,25 +133,23 @@ class ObligationTests {
command(MINI_CORP_PUBKEY) { Obligation.Commands.Issue() }
this.verifies()
}
initialiseTestSerialization()
// Test generation works.
val tx = TransactionBuilder(notary = null).apply {
Obligation<Currency>().generateIssue(this, MINI_CORP, megaCorpDollarSettlement, 100.DOLLARS.quantity,
beneficiary = CHARLIE, notary = DUMMY_NOTARY)
}.toWireTransaction(miniCorpServices)
assertTrue(tx.inputs.isEmpty())
val expected = Obligation.State(
obligor = MINI_CORP,
quantity = 100.DOLLARS.quantity,
beneficiary = CHARLIE,
template = megaCorpDollarSettlement
)
assertEquals(tx.getOutput(0), expected)
assertTrue(tx.commands[0].value is Obligation.Commands.Issue)
assertEquals(MINI_CORP_PUBKEY, tx.commands[0].signers[0])
resetTestSerialization()
withTestSerialization {
// Test generation works.
val tx = TransactionBuilder(notary = null).apply {
Obligation<Currency>().generateIssue(this, MINI_CORP, megaCorpDollarSettlement, 100.DOLLARS.quantity,
beneficiary = CHARLIE, notary = DUMMY_NOTARY)
}.toWireTransaction(miniCorpServices)
assertTrue(tx.inputs.isEmpty())
val expected = Obligation.State(
obligor = MINI_CORP,
quantity = 100.DOLLARS.quantity,
beneficiary = CHARLIE,
template = megaCorpDollarSettlement
)
assertEquals(tx.getOutput(0), expected)
assertTrue(tx.commands[0].value is Obligation.Commands.Issue)
assertEquals(MINI_CORP_PUBKEY, tx.commands[0].signers[0])
}
// We can consume $1000 in a transaction and output $2000 as long as it's signed by an issuer.
transaction {
attachments(Obligation.PROGRAM_ID)
@ -214,8 +206,7 @@ class ObligationTests {
* cash inputs.
*/
@Test(expected = IllegalStateException::class)
fun `reject issuance with inputs`() {
initialiseTestSerialization()
fun `reject issuance with inputs`() = withTestSerialization {
// Issue some obligation
val tx = TransactionBuilder(DUMMY_NOTARY).apply {
Obligation<Currency>().generateIssue(this, MINI_CORP, megaCorpDollarSettlement, 100.DOLLARS.quantity,
@ -228,12 +219,12 @@ class ObligationTests {
ptx.addInputState(tx.outRef<Obligation.State<Currency>>(0))
Obligation<Currency>().generateIssue(ptx, MINI_CORP, megaCorpDollarSettlement, 100.DOLLARS.quantity,
beneficiary = MINI_CORP, notary = DUMMY_NOTARY)
Unit
}
/** Test generating a transaction to net two obligations of the same size, and therefore there are no outputs. */
@Test
fun `generate close-out net transaction`() {
initialiseTestSerialization()
fun `generate close-out net transaction`() = withTestSerialization {
val obligationAliceToBob = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(ALICE, BOB), Obligation.PROGRAM_ID)
val obligationBobToAlice = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(BOB, ALICE), Obligation.PROGRAM_ID)
val tx = TransactionBuilder(DUMMY_NOTARY).apply {
@ -244,8 +235,7 @@ class ObligationTests {
/** Test generating a transaction to net two obligations of the different sizes, and confirm the balance is correct. */
@Test
fun `generate close-out net transaction with remainder`() {
initialiseTestSerialization()
fun `generate close-out net transaction with remainder`() = withTestSerialization {
val obligationAliceToBob = getStateAndRef((2000000.DOLLARS `issued by` defaultIssuer).OBLIGATION between Pair(ALICE, BOB), Obligation.PROGRAM_ID)
val obligationBobToAlice = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(BOB, ALICE), Obligation.PROGRAM_ID)
val tx = TransactionBuilder(DUMMY_NOTARY).apply {
@ -259,8 +249,7 @@ class ObligationTests {
/** Test generating a transaction to net two obligations of the same size, and therefore there are no outputs. */
@Test
fun `generate payment net transaction`() {
initialiseTestSerialization()
fun `generate payment net transaction`() = withTestSerialization {
val obligationAliceToBob = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(ALICE, BOB), Obligation.PROGRAM_ID)
val obligationBobToAlice = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(BOB, ALICE), Obligation.PROGRAM_ID)
val tx = TransactionBuilder(DUMMY_NOTARY).apply {
@ -271,8 +260,7 @@ class ObligationTests {
/** Test generating a transaction to two obligations, where one is bigger than the other and therefore there is a remainder. */
@Test
fun `generate payment net transaction with remainder`() {
initialiseTestSerialization()
fun `generate payment net transaction with remainder`() = withTestSerialization {
val obligationAliceToBob = getStateAndRef(oneMillionDollars.OBLIGATION between Pair(ALICE, BOB), Obligation.PROGRAM_ID)
val obligationAliceToBobState = obligationAliceToBob.state.data
val obligationBobToAlice = getStateAndRef((2000000.DOLLARS `issued by` defaultIssuer).OBLIGATION between Pair(BOB, ALICE), Obligation.PROGRAM_ID)
@ -294,8 +282,7 @@ class ObligationTests {
/** Test generating a transaction to mark outputs as having defaulted. */
@Test
fun `generate set lifecycle`() {
initialiseTestSerialization()
fun `generate set lifecycle`() = withTestSerialization {
// We don't actually verify the states, this is just here to make things look sensible
val dueBefore = TEST_TX_TIME - 7.days
@ -333,8 +320,7 @@ class ObligationTests {
/** Test generating a transaction to settle an obligation. */
@Test
fun `generate settlement transaction`() {
initialiseTestSerialization()
fun `generate settlement transaction`() = withTestSerialization {
val cashTx = TransactionBuilder(null).apply {
Cash().generateIssue(this, 100.DOLLARS `issued by` defaultIssuer, MINI_CORP, DUMMY_NOTARY)
}.toWireTransaction(miniCorpServices)
@ -926,8 +912,7 @@ class ObligationTests {
}
@Test
fun `summing balances due between parties`() {
initialiseTestSerialization()
fun `summing balances due between parties`() = withTestSerialization {
val simple: Map<Pair<AbstractParty, AbstractParty>, Amount<Currency>> = mapOf(Pair(Pair(ALICE, BOB), Amount(100000000, GBP)))
val expected: Map<AbstractParty, Long> = mapOf(Pair(ALICE, -100000000L), Pair(BOB, 100000000L))
val actual = sumAmountsDue(simple)

View File

@ -2,11 +2,11 @@ package net.corda.nodeapi.internal.serialization;
import com.google.common.collect.Maps;
import net.corda.core.serialization.SerializationContext;
import net.corda.core.serialization.SerializationDefaults;
import net.corda.core.serialization.SerializationFactory;
import net.corda.core.serialization.SerializedBytes;
import net.corda.testing.TestDependencyInjectionBase;
import net.corda.testing.SerializationEnvironmentRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.Serializable;
@ -16,13 +16,14 @@ import java.util.concurrent.Callable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
public final class ForbiddenLambdaSerializationTests extends TestDependencyInjectionBase {
public final class ForbiddenLambdaSerializationTests {
@Rule
public SerializationEnvironmentRule testSerialization = new SerializationEnvironmentRule();
private SerializationFactory factory;
@Before
public void setup() {
factory = SerializationDefaults.INSTANCE.getSERIALIZATION_FACTORY();
factory = testSerialization.env.getSERIALIZATION_FACTORY();
}
@Test

View File

@ -2,11 +2,11 @@ package net.corda.nodeapi.internal.serialization;
import com.google.common.collect.Maps;
import net.corda.core.serialization.SerializationContext;
import net.corda.core.serialization.SerializationDefaults;
import net.corda.core.serialization.SerializationFactory;
import net.corda.core.serialization.SerializedBytes;
import net.corda.testing.TestDependencyInjectionBase;
import net.corda.testing.SerializationEnvironmentRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.Serializable;
@ -15,14 +15,15 @@ import java.util.concurrent.Callable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
public final class LambdaCheckpointSerializationTest extends TestDependencyInjectionBase {
public final class LambdaCheckpointSerializationTest {
@Rule
public SerializationEnvironmentRule testSerialization = new SerializationEnvironmentRule();
private SerializationFactory factory;
private SerializationContext context;
@Before
public void setup() {
factory = SerializationDefaults.INSTANCE.getSERIALIZATION_FACTORY();
factory = testSerialization.env.getSERIALIZATION_FACTORY();
context = new SerializationContextImpl(SerializationSchemeKt.getKryoHeaderV0_1(), this.getClass().getClassLoader(), AllWhitelist.INSTANCE, Maps.newHashMap(), true, SerializationContext.UseCase.Checkpoint);
}

View File

@ -11,9 +11,13 @@ import net.corda.testing.*
import net.corda.testing.node.MockServices
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AttachmentsClassLoaderStaticContractTests : TestDependencyInjectionBase() {
class AttachmentsClassLoaderStaticContractTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
class AttachmentDummyContract : Contract {
companion object {

View File

@ -23,6 +23,7 @@ import net.corda.testing.node.MockServices
import org.apache.commons.io.IOUtils
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
@ -32,7 +33,7 @@ import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry
import kotlin.test.assertFailsWith
class AttachmentsClassLoaderTests : TestDependencyInjectionBase() {
class AttachmentsClassLoaderTests {
companion object {
val ISOLATED_CONTRACTS_JAR_PATH: URL = AttachmentsClassLoaderTests::class.java.getResource("isolated.jar")
private const val ISOLATED_CONTRACT_CLASS_NAME = "net.corda.finance.contracts.isolated.AnotherDummyContract"
@ -48,6 +49,9 @@ class AttachmentsClassLoaderTests : TestDependencyInjectionBase() {
}
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var serviceHub: DummyServiceHub
class DummyServiceHub : MockServices() {

View File

@ -14,7 +14,7 @@ import net.corda.core.utilities.sequence
import net.corda.node.serialization.KryoServerSerializationScheme
import net.corda.node.services.persistence.NodeAttachmentService
import net.corda.testing.ALICE_PUBKEY
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Before
@ -28,7 +28,10 @@ import java.time.Instant
import java.util.Collections
import kotlin.test.*
class KryoTests : TestDependencyInjectionBase() {
class KryoTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var factory: SerializationFactory
private lateinit var context: SerializationContext

View File

@ -7,19 +7,20 @@ import net.corda.node.services.statemachine.SessionData
import net.corda.nodeapi.internal.serialization.amqp.DeserializationInput
import net.corda.nodeapi.internal.serialization.amqp.Envelope
import net.corda.nodeapi.internal.serialization.amqp.SerializerFactory
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.amqpSpecific
import net.corda.testing.kryoSpecific
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.NotSerializableException
import java.nio.charset.StandardCharsets.US_ASCII
import java.util.*
class ListsSerializationTest : TestDependencyInjectionBase() {
class ListsSerializationTest {
private companion object {
val javaEmptyListClass = Collections.emptyList<Any>().javaClass
@ -31,6 +32,10 @@ class ListsSerializationTest : TestDependencyInjectionBase() {
}
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `check list can be serialized as root of serialization graph`() {
assertEqualAfterRoundTripSerialization(emptyList<Int>())

View File

@ -6,23 +6,28 @@ import net.corda.core.serialization.CordaSerializable
import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize
import net.corda.node.services.statemachine.SessionData
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.amqpSpecific
import net.corda.testing.kryoSpecific
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions
import org.bouncycastle.asn1.x500.X500Name
import org.junit.Assert.assertArrayEquals
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.util.*
import kotlin.test.assertEquals
class MapsSerializationTest : TestDependencyInjectionBase() {
class MapsSerializationTest {
private companion object {
val javaEmptyMapClass = Collections.emptyMap<Any, Any>().javaClass
val smallMap = mapOf("foo" to "bar", "buzz" to "bull")
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `check EmptyMap serialization`() = amqpSpecific("kotlin.collections.EmptyMap is not enabled for Kryo serialization") {
assertEqualAfterRoundTripSerialization(emptyMap<Any, Any>())

View File

@ -4,8 +4,9 @@ import net.corda.core.crypto.Crypto
import net.corda.core.serialization.SerializationContext.UseCase.*
import net.corda.core.serialization.SerializationDefaults
import net.corda.core.serialization.serialize
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@ -13,8 +14,7 @@ import java.security.PrivateKey
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class PrivateKeySerializationTest(private val privateKey: PrivateKey, private val testName: String) : TestDependencyInjectionBase() {
class PrivateKeySerializationTest(private val privateKey: PrivateKey, private val testName: String) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{1}")
@ -26,6 +26,10 @@ class PrivateKeySerializationTest(private val privateKey: PrivateKey, private va
}
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `passed with expected UseCases`() {
assertTrue { privateKey.serialize(context = SerializationDefaults.STORAGE_CONTEXT).bytes.isNotEmpty() }

View File

@ -5,22 +5,25 @@ import com.esotericsoftware.kryo.KryoException
import com.esotericsoftware.kryo.io.Output
import net.corda.core.serialization.*
import net.corda.core.utilities.OpaqueBytes
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.rigorousMock
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayOutputStream
class SerializationTokenTest : TestDependencyInjectionBase() {
class SerializationTokenTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var factory: SerializationFactory
private lateinit var context: SerializationContext
@Before
fun setup() {
factory = SerializationDefaults.SERIALIZATION_FACTORY
context = SerializationDefaults.CHECKPOINT_CONTEXT.withWhitelisted(SingletonSerializationToken::class.java)
factory = testSerialization.env.SERIALIZATION_FACTORY
context = testSerialization.env.CHECKPOINT_CONTEXT.withWhitelisted(SingletonSerializationToken::class.java)
}
// Large tokenizable object so we can tell from the smaller number of serialized bytes it was actually tokenized

View File

@ -5,19 +5,24 @@ import com.esotericsoftware.kryo.util.DefaultClassResolver
import net.corda.core.serialization.deserialize
import net.corda.core.serialization.serialize
import net.corda.node.services.statemachine.SessionData
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.kryoSpecific
import net.corda.testing.SerializationEnvironmentRule
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.util.*
class SetsSerializationTest : TestDependencyInjectionBase() {
class SetsSerializationTest {
private companion object {
val javaEmptySetClass = Collections.emptySet<Any>().javaClass
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Test
fun `check set can be serialized as root of serialization graph`() {
assertEqualAfterRoundTripSerialization(emptySet<Int>())

View File

@ -432,9 +432,7 @@ class SerializationOutputTests {
private fun serdesThrowableWithInternalInfo(t: Throwable, factory: SerializerFactory, factory2: SerializerFactory, expectedEqual: Boolean = true): Throwable = withTestSerialization {
val newContext = SerializationFactory.defaultFactory.defaultContext.withProperty(CommonPropertyNames.IncludeInternalInfo, true)
val deserializedObj = SerializationFactory.defaultFactory.asCurrent { withCurrentContext(newContext) { serdes(t, factory, factory2, expectedEqual) } }
return deserializedObj
SerializationFactory.defaultFactory.asCurrent { withCurrentContext(newContext) { serdes(t, factory, factory2, expectedEqual) } }
}
@Test

View File

@ -20,22 +20,24 @@ import net.corda.core.utilities.seconds
import net.corda.node.internal.cordapp.CordappLoader
import net.corda.node.internal.cordapp.CordappProviderImpl
import net.corda.nodeapi.User
import net.corda.testing.DUMMY_BANK_A
import net.corda.testing.DUMMY_NOTARY
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.*
import net.corda.testing.driver.DriverDSLExposedInterface
import net.corda.testing.driver.NodeHandle
import net.corda.testing.driver.driver
import net.corda.testing.eventually
import net.corda.testing.node.MockServices
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.net.URLClassLoader
import java.nio.file.Files
import kotlin.test.assertFailsWith
class AttachmentLoadingTests : TestDependencyInjectionBase() {
class AttachmentLoadingTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private class Services : MockServices() {
private val provider = CordappProviderImpl(CordappLoader.createDevMode(listOf(isolatedJAR)), attachments)
private val cordapp get() = provider.cordapps.first()

View File

@ -90,6 +90,7 @@ object BFTSMaRt {
private fun awaitClientConnectionToCluster() {
// TODO: Hopefully we only need to wait for the client's initial connection to the cluster, and this method can be moved to some startup code.
// TODO: Investigate ConcurrentModificationException in this method.
while (true) {
val inactive = sessionTable.entries.mapNotNull { if (it.value.channel.isActive) null else it.key }
if (inactive.isEmpty()) break

View File

@ -33,8 +33,9 @@ import static net.corda.testing.TestConstants.*;
import static net.corda.testing.node.MockServices.*;
import static org.assertj.core.api.Assertions.*;
public class VaultQueryJavaTests extends TestDependencyInjectionBase {
public class VaultQueryJavaTests {
@Rule
public SerializationEnvironmentRule testSerialization = new SerializationEnvironmentRule();
private MockServices services;
private MockServices issuerServices;
private VaultService vaultService;

View File

@ -4,7 +4,6 @@ import net.corda.node.services.messaging.Message
import net.corda.node.services.messaging.TopicStringValidator
import net.corda.node.services.messaging.createMessage
import net.corda.testing.node.MockNetwork
import net.corda.testing.resetTestSerialization
import org.junit.After
import org.junit.Before
import org.junit.Test
@ -23,11 +22,7 @@ class InMemoryMessagingTests {
@After
fun tearDown() {
if (mockNet.nodes.isNotEmpty()) {
mockNet.stopNodes()
} else {
resetTestSerialization()
}
mockNet.stopNodes()
}
@Test

View File

@ -42,6 +42,7 @@ import net.corda.testing.node.MockServices.Companion.makeTestIdentityService
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
import java.security.PublicKey
@ -57,6 +58,9 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
private val myInfo = NodeInfo(listOf(MOCK_HOST_AND_PORT), listOf(DUMMY_IDENTITY_1), 1, serial = 1L)
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val realClock: Clock = Clock.systemUTC()
private val stoppedClock: Clock = Clock.fixed(realClock.instant(), realClock.zone)
private val testClock = TestClock(stoppedClock)
@ -86,7 +90,6 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
@Before
fun setup() {
initialiseTestSerialization()
countDown = CountDownLatch(1)
smmHasRemovedAllFlows = CountDownLatch(1)
calls = 0
@ -137,7 +140,6 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
smmExecutor.shutdown()
smmExecutor.awaitTermination(60, TimeUnit.SECONDS)
database.close()
resetTestSerialization()
}
// Ignore IntelliJ when it says these properties can be private, if they are we cannot serialise them

View File

@ -39,7 +39,10 @@ import kotlin.test.assertEquals
import kotlin.test.assertNull
//TODO This needs to be merged into P2PMessagingTest as that creates a more realistic environment
class ArtemisMessagingTests : TestDependencyInjectionBase() {
class ArtemisMessagingTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Rule
@JvmField
val temporaryFolder = TemporaryFolder()

View File

@ -10,7 +10,7 @@ import net.corda.core.serialization.serialize
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.node.utilities.CertificateType
import net.corda.node.utilities.X509Utilities
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThat
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.cert.X509CertificateHolder
@ -23,6 +23,7 @@ import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.servlet.ServletContainer
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.InputStream
@ -37,7 +38,10 @@ import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.ok
import kotlin.test.assertEquals
class HTTPNetworkMapClientTest : TestDependencyInjectionBase() {
class HTTPNetworkMapClientTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private lateinit var server: Server
private lateinit var networkMapClient: NetworkMapClient

View File

@ -8,13 +8,14 @@ import net.corda.node.services.transactions.PersistentUniquenessProvider
import net.corda.node.utilities.CordaPersistence
import net.corda.node.utilities.configureDatabase
import net.corda.testing.LogHelper
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import net.corda.testing.node.MockServices.Companion.makeTestDatabaseProperties
import net.corda.testing.node.MockServices.Companion.makeTestIdentityService
import net.corda.testing.SerializationEnvironmentRule
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
internal fun CheckpointStorage.checkpoints(): List<Checkpoint> {
@ -26,7 +27,10 @@ internal fun CheckpointStorage.checkpoints(): List<Checkpoint> {
return checkpoints
}
class DBCheckpointStorageTests : TestDependencyInjectionBase() {
class DBCheckpointStorageTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var checkpointStorage: DBCheckpointStorage
lateinit var database: CordaPersistence

View File

@ -24,11 +24,15 @@ import net.corda.testing.node.MockServices.Companion.makeTestIdentityService
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
class DBTransactionStorageTests : TestDependencyInjectionBase() {
class DBTransactionStorageTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var database: CordaPersistence
lateinit var transactionStorage: DBTransactionStorage
lateinit var services: MockServices

View File

@ -12,8 +12,8 @@ import net.corda.core.node.services.VaultService
import net.corda.core.schemas.CommonSchemaV1
import net.corda.core.schemas.MappedSchema
import net.corda.core.schemas.PersistentStateRef
import net.corda.core.serialization.SerializationDefaults
import net.corda.core.serialization.deserialize
import net.corda.core.serialization.SerializationDefaults
import net.corda.core.transactions.SignedTransaction
import net.corda.finance.DOLLARS
import net.corda.finance.POUNDS
@ -44,10 +44,7 @@ import net.corda.testing.schemas.DummyLinearStateSchemaV2
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.hibernate.SessionFactory
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.*
import java.math.BigDecimal
import java.time.Instant
import java.util.*
@ -55,8 +52,10 @@ import javax.persistence.EntityManager
import javax.persistence.Tuple
import javax.persistence.criteria.CriteriaBuilder
class HibernateConfigurationTest : TestDependencyInjectionBase() {
class HibernateConfigurationTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var services: MockServices
lateinit var issuerServices: MockServices
lateinit var database: CordaPersistence

View File

@ -18,14 +18,18 @@ import net.corda.testing.node.MockServices.Companion.makeTestDatabaseProperties
import net.corda.testing.node.MockServices.Companion.makeTestIdentityService
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.concurrent.CompletableFuture
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class DistributedImmutableMapTests : TestDependencyInjectionBase() {
class DistributedImmutableMapTests {
data class Member(val client: CopycatClient, val server: CopycatServer)
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var cluster: List<Member>
lateinit var transaction: DatabaseTransaction
private val databases: MutableList<CordaPersistence> = mutableListOf()

View File

@ -10,11 +10,15 @@ import net.corda.testing.node.MockServices.Companion.makeTestDatabaseProperties
import net.corda.testing.node.MockServices.Companion.makeTestIdentityService
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class PersistentUniquenessProviderTests : TestDependencyInjectionBase() {
class PersistentUniquenessProviderTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
val identity = MEGA_CORP
val txID = SecureHash.randomSHA256()

View File

@ -33,6 +33,7 @@ import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import rx.observers.TestSubscriber
import java.math.BigDecimal
@ -43,11 +44,14 @@ import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class NodeVaultServiceTest : TestDependencyInjectionBase() {
class NodeVaultServiceTest {
companion object {
private val cordappPackages = listOf("net.corda.finance.contracts.asset", CashSchemaV1::class.packageName)
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var services: MockServices
private lateinit var issuerServices: MockServices
val vaultService get() = services.vaultService as NodeVaultService

View File

@ -46,7 +46,10 @@ import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
import java.util.*
class VaultQueryTests : TestDependencyInjectionBase() {
class VaultQueryTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val cordappPackages = setOf(
"net.corda.testing.contracts", "net.corda.finance.contracts",
CashSchemaV1::class.packageName, CommercialPaperSchemaV1::class.packageName, DummyLinearStateSchemaV1::class.packageName).toMutableList()

View File

@ -26,6 +26,7 @@ import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.*
import java.util.concurrent.CountDownLatch
@ -34,11 +35,14 @@ import kotlin.test.assertEquals
// TODO: Move this to the cash contract tests once mock services are further split up.
class VaultWithCashTest : TestDependencyInjectionBase() {
class VaultWithCashTest {
companion object {
private val cordappPackages = listOf("net.corda.testing.contracts", "net.corda.finance.contracts.asset", CashSchemaV1::class.packageName)
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
lateinit var services: MockServices
lateinit var issuerServices: MockServices
val vaultService: VaultService get() = services.vaultService

View File

@ -27,6 +27,7 @@ import net.corda.testing.node.createMockCordaService
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.math.BigDecimal
import java.util.function.Predicate
@ -34,7 +35,10 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
class NodeInterestRatesTest : TestDependencyInjectionBase() {
class NodeInterestRatesTest {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val TEST_DATA = NodeInterestRates.parseFile("""
LIBOR 2016-03-16 1M = 0.678
LIBOR 2016-03-16 2M = 0.685

View File

@ -18,23 +18,9 @@ import net.corda.finance.contracts.FixOf
import net.corda.finance.contracts.Frequency
import net.corda.finance.contracts.PaymentRule
import net.corda.finance.contracts.Tenor
import net.corda.testing.DUMMY_NOTARY
import net.corda.testing.DUMMY_NOTARY_KEY
import net.corda.testing.DUMMY_PARTY
import net.corda.testing.LedgerDSL
import net.corda.testing.MEGA_CORP
import net.corda.testing.MEGA_CORP_KEY
import net.corda.testing.MEGA_CORP_PUBKEY
import net.corda.testing.MINI_CORP
import net.corda.testing.MINI_CORP_KEY
import net.corda.testing.ORACLE_PUBKEY
import net.corda.testing.TEST_TX_TIME
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.TestLedgerDSLInterpreter
import net.corda.testing.TestTransactionDSLInterpreter
import net.corda.testing.ledger
import net.corda.testing.*
import net.corda.testing.node.MockServices
import net.corda.testing.transaction
import org.junit.Rule
import org.junit.Test
import java.math.BigDecimal
import java.time.LocalDate
@ -222,7 +208,10 @@ fun createDummyIRS(irsSelect: Int): InterestRateSwap.State {
}
}
class IRSTests : TestDependencyInjectionBase() {
class IRSTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
private val megaCorpServices = MockServices(listOf("net.corda.irs.contract"), MEGA_CORP_KEY)
private val miniCorpServices = MockServices(listOf("net.corda.irs.contract"), MINI_CORP_KEY)
private val notaryServices = MockServices(listOf("net.corda.irs.contract"), DUMMY_NOTARY_KEY)

View File

@ -10,10 +10,15 @@ import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState
import net.corda.testing.node.MockServices
import net.corda.testing.node.MockTransactionStorage
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
class TransactionGraphSearchTests : TestDependencyInjectionBase() {
class TransactionGraphSearchTests {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
class GraphTransactionStorage(val originTx: SignedTransaction, val inputTx: SignedTransaction) : MockTransactionStorage() {
init {
addTransaction(originTx)

View File

@ -28,13 +28,13 @@ fun ledger(
initialiseSerialization: Boolean = true,
dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit
): LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter> {
if (initialiseSerialization) initialiseTestSerialization()
val serializationEnv = initialiseTestSerialization(initialiseSerialization)
try {
val ledgerDsl = LedgerDSL(TestLedgerDSLInterpreter(services))
dsl(ledgerDsl)
return ledgerDsl
} finally {
if (initialiseSerialization) resetTestSerialization()
serializationEnv.resetTestSerialization()
}
}

View File

@ -402,7 +402,7 @@ fun <DI : DriverDSLExposedInterface, D : DriverDSLInternalInterface, A> genericD
coerce: (D) -> DI,
dsl: DI.() -> A
): A {
if (initialiseSerialization) initialiseTestSerialization()
val serializationEnv = initialiseTestSerialization(initialiseSerialization)
val shutdownHook = addShutdownHook(driverDsl::shutdown)
try {
driverDsl.start()
@ -413,7 +413,7 @@ fun <DI : DriverDSLExposedInterface, D : DriverDSLInternalInterface, A> genericD
} finally {
driverDsl.shutdown()
shutdownHook.cancel()
if (initialiseSerialization) resetTestSerialization()
serializationEnv.resetTestSerialization()
}
}
@ -440,7 +440,7 @@ fun <DI : DriverDSLExposedInterface, D : DriverDSLInternalInterface, A> genericD
coerce: (D) -> DI,
dsl: DI.() -> A
): A {
if (initialiseSerialization) initialiseTestSerialization()
val serializationEnv = initialiseTestSerialization(initialiseSerialization)
val driverDsl = driverDslWrapper(
DriverDSL(
portAllocation = portAllocation,
@ -463,7 +463,7 @@ fun <DI : DriverDSLExposedInterface, D : DriverDSLInternalInterface, A> genericD
} finally {
driverDsl.shutdown()
shutdownHook.cancel()
if (initialiseSerialization) resetTestSerialization()
serializationEnv.resetTestSerialization()
}
}

View File

@ -42,7 +42,6 @@ import net.corda.testing.DUMMY_NOTARY
import net.corda.testing.initialiseTestSerialization
import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO
import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties
import net.corda.testing.resetTestSerialization
import net.corda.testing.testNodeConfiguration
import org.apache.activemq.artemis.utils.ReusableLatch
import org.slf4j.Logger
@ -121,7 +120,7 @@ class MockNetwork(defaultParameters: MockNetworkParameters = MockNetworkParamete
private val threadPerNode: Boolean = defaultParameters.threadPerNode,
servicePeerAllocationStrategy: InMemoryMessagingNetwork.ServicePeerAllocationStrategy = defaultParameters.servicePeerAllocationStrategy,
private val defaultFactory: Factory<*> = defaultParameters.defaultFactory,
private val initialiseSerialization: Boolean = defaultParameters.initialiseSerialization,
initialiseSerialization: Boolean = defaultParameters.initialiseSerialization,
private val cordappPackages: List<String> = defaultParameters.cordappPackages) : Closeable {
/** Helper constructor for creating a [MockNetwork] with custom parameters from Java. */
constructor(parameters: MockNetworkParameters) : this(defaultParameters = parameters)
@ -136,9 +135,9 @@ class MockNetwork(defaultParameters: MockNetworkParameters = MockNetworkParamete
private val _nodes = mutableListOf<MockNode>()
/** A read only view of the current set of executing nodes. */
val nodes: List<MockNode> get() = _nodes
private val serializationEnv = initialiseTestSerialization(initialiseSerialization)
init {
if (initialiseSerialization) initialiseTestSerialization()
filesystem.getPath("/nodes").createDirectory()
}
@ -392,7 +391,7 @@ class MockNetwork(defaultParameters: MockNetworkParameters = MockNetworkParamete
fun stopNodes() {
nodes.forEach { it.started?.dispose() }
if (initialiseSerialization) resetTestSerialization()
serializationEnv.resetTestSerialization()
}
// Test method to block until all scheduled activity, active flows

View File

@ -15,10 +15,10 @@ import net.corda.node.services.config.*
import net.corda.node.utilities.ServiceIdentityGenerator
import net.corda.nodeapi.User
import net.corda.nodeapi.config.toConfig
import net.corda.testing.TestDependencyInjectionBase
import net.corda.testing.driver.addressMustNotBeBoundFuture
import net.corda.testing.getFreeLocalPorts
import net.corda.testing.node.MockServices.Companion.MOCK_VERSION_INFO
import net.corda.testing.SerializationEnvironmentRule
import org.apache.logging.log4j.Level
import org.junit.After
import org.junit.Rule
@ -31,11 +31,14 @@ import kotlin.concurrent.thread
* purposes. Use the driver if you need to run the nodes in separate processes otherwise this class will suffice.
*/
// TODO Some of the logic here duplicates what's in the driver
abstract class NodeBasedTest(private val cordappPackages: List<String> = emptyList()) : TestDependencyInjectionBase() {
abstract class NodeBasedTest(private val cordappPackages: List<String> = emptyList()) {
companion object {
private val WHITESPACE = "\\s++".toRegex()
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
@Rule
@JvmField
val tempFolder = TemporaryFolder()

View File

@ -1,78 +1,112 @@
package net.corda.testing
import com.nhaarman.mockito_kotlin.doNothing
import com.nhaarman.mockito_kotlin.whenever
import net.corda.client.rpc.internal.KryoClientSerializationScheme
import net.corda.core.crypto.SecureHash
import net.corda.core.serialization.*
import net.corda.core.serialization.internal.SerializationEnvironment
import net.corda.core.utilities.ByteSequence
import net.corda.node.serialization.KryoServerSerializationScheme
import net.corda.nodeapi.internal.serialization.*
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
inline fun <T> withTestSerialization(block: () -> T): T {
initialiseTestSerialization()
try {
return block()
} finally {
resetTestSerialization()
class SerializationEnvironmentRule : TestRule {
lateinit var env: SerializationEnvironment
override fun apply(base: Statement, description: Description?) = object : Statement() {
override fun evaluate() = withTestSerialization {
env = it
base.evaluate()
}
}
}
fun initialiseTestSerialization() {
interface TestSerializationEnvironment : SerializationEnvironment {
fun resetTestSerialization()
}
fun <T> withTestSerialization(block: (SerializationEnvironment) -> T): T {
val env = initialiseTestSerializationImpl()
try {
return block(env)
} finally {
env.resetTestSerialization()
}
}
/** @param armed true to init, false to do nothing and return a dummy env. */
fun initialiseTestSerialization(armed: Boolean): TestSerializationEnvironment {
return if (armed) {
val env = initialiseTestSerializationImpl()
object : TestSerializationEnvironment, SerializationEnvironment by env {
override fun resetTestSerialization() = env.resetTestSerialization()
}
} else {
rigorousMock<TestSerializationEnvironment>().also {
doNothing().whenever(it).resetTestSerialization()
}
}
}
private fun initialiseTestSerializationImpl() = SerializationDefaults.apply {
// Stop the CordaRPCClient from trying to setup the defaults as we're about to do it now
KryoClientSerializationScheme.isInitialised.set(true)
// Check that everything is configured for testing with mutable delegating instances.
try {
check(SerializationDefaults.SERIALIZATION_FACTORY is TestSerializationFactory)
check(SERIALIZATION_FACTORY is TestSerializationFactory)
} catch (e: IllegalStateException) {
SerializationDefaults.SERIALIZATION_FACTORY = TestSerializationFactory()
SERIALIZATION_FACTORY = TestSerializationFactory()
}
try {
check(SerializationDefaults.P2P_CONTEXT is TestSerializationContext)
check(P2P_CONTEXT is TestSerializationContext)
} catch (e: IllegalStateException) {
SerializationDefaults.P2P_CONTEXT = TestSerializationContext()
P2P_CONTEXT = TestSerializationContext()
}
try {
check(SerializationDefaults.RPC_SERVER_CONTEXT is TestSerializationContext)
check(RPC_SERVER_CONTEXT is TestSerializationContext)
} catch (e: IllegalStateException) {
SerializationDefaults.RPC_SERVER_CONTEXT = TestSerializationContext()
RPC_SERVER_CONTEXT = TestSerializationContext()
}
try {
check(SerializationDefaults.RPC_CLIENT_CONTEXT is TestSerializationContext)
check(RPC_CLIENT_CONTEXT is TestSerializationContext)
} catch (e: IllegalStateException) {
SerializationDefaults.RPC_CLIENT_CONTEXT = TestSerializationContext()
RPC_CLIENT_CONTEXT = TestSerializationContext()
}
try {
check(SerializationDefaults.STORAGE_CONTEXT is TestSerializationContext)
check(STORAGE_CONTEXT is TestSerializationContext)
} catch (e: IllegalStateException) {
SerializationDefaults.STORAGE_CONTEXT = TestSerializationContext()
STORAGE_CONTEXT = TestSerializationContext()
}
try {
check(SerializationDefaults.CHECKPOINT_CONTEXT is TestSerializationContext)
check(CHECKPOINT_CONTEXT is TestSerializationContext)
} catch (e: IllegalStateException) {
SerializationDefaults.CHECKPOINT_CONTEXT = TestSerializationContext()
CHECKPOINT_CONTEXT = TestSerializationContext()
}
// Check that the previous test, if there was one, cleaned up after itself.
// IF YOU SEE THESE MESSAGES, THEN IT MEANS A TEST HAS NOT CALLED resetTestSerialization()
check((SerializationDefaults.SERIALIZATION_FACTORY as TestSerializationFactory).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.SERIALIZATION_FACTORY}" })
check((SerializationDefaults.P2P_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.P2P_CONTEXT}" })
check((SerializationDefaults.RPC_SERVER_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.RPC_SERVER_CONTEXT}" })
check((SerializationDefaults.RPC_CLIENT_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.RPC_CLIENT_CONTEXT}" })
check((SerializationDefaults.STORAGE_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.STORAGE_CONTEXT}" })
check((SerializationDefaults.CHECKPOINT_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: ${SerializationDefaults.CHECKPOINT_CONTEXT}" })
check((SERIALIZATION_FACTORY as TestSerializationFactory).delegate == null, { "Expected uninitialised serialization framework but found it set from: $SERIALIZATION_FACTORY" })
check((P2P_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: $P2P_CONTEXT" })
check((RPC_SERVER_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: $RPC_SERVER_CONTEXT" })
check((RPC_CLIENT_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: $RPC_CLIENT_CONTEXT" })
check((STORAGE_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: $STORAGE_CONTEXT" })
check((CHECKPOINT_CONTEXT as TestSerializationContext).delegate == null, { "Expected uninitialised serialization framework but found it set from: $CHECKPOINT_CONTEXT" })
// Now configure all the testing related delegates.
(SerializationDefaults.SERIALIZATION_FACTORY as TestSerializationFactory).delegate = SerializationFactoryImpl().apply {
(SERIALIZATION_FACTORY as TestSerializationFactory).delegate = SerializationFactoryImpl().apply {
registerScheme(KryoClientSerializationScheme())
registerScheme(KryoServerSerializationScheme())
registerScheme(AMQPClientSerializationScheme())
registerScheme(AMQPServerSerializationScheme())
}
(SerializationDefaults.P2P_CONTEXT as TestSerializationContext).delegate = if (isAmqpEnabled()) AMQP_P2P_CONTEXT else KRYO_P2P_CONTEXT
(SerializationDefaults.RPC_SERVER_CONTEXT as TestSerializationContext).delegate = KRYO_RPC_SERVER_CONTEXT
(SerializationDefaults.RPC_CLIENT_CONTEXT as TestSerializationContext).delegate = KRYO_RPC_CLIENT_CONTEXT
(SerializationDefaults.STORAGE_CONTEXT as TestSerializationContext).delegate = if (isAmqpEnabled()) AMQP_STORAGE_CONTEXT else KRYO_STORAGE_CONTEXT
(SerializationDefaults.CHECKPOINT_CONTEXT as TestSerializationContext).delegate = KRYO_CHECKPOINT_CONTEXT
(P2P_CONTEXT as TestSerializationContext).delegate = if (isAmqpEnabled()) AMQP_P2P_CONTEXT else KRYO_P2P_CONTEXT
(RPC_SERVER_CONTEXT as TestSerializationContext).delegate = KRYO_RPC_SERVER_CONTEXT
(RPC_CLIENT_CONTEXT as TestSerializationContext).delegate = KRYO_RPC_CLIENT_CONTEXT
(STORAGE_CONTEXT as TestSerializationContext).delegate = if (isAmqpEnabled()) AMQP_STORAGE_CONTEXT else KRYO_STORAGE_CONTEXT
(CHECKPOINT_CONTEXT as TestSerializationContext).delegate = KRYO_CHECKPOINT_CONTEXT
}
private const val AMQP_ENABLE_PROP_NAME = "net.corda.testing.amqp.enable"
@ -80,13 +114,13 @@ private const val AMQP_ENABLE_PROP_NAME = "net.corda.testing.amqp.enable"
// TODO: Remove usages of this function when we fully switched to AMQP
private fun isAmqpEnabled(): Boolean = java.lang.Boolean.getBoolean(AMQP_ENABLE_PROP_NAME)
fun resetTestSerialization() {
(SerializationDefaults.SERIALIZATION_FACTORY as TestSerializationFactory).delegate = null
(SerializationDefaults.P2P_CONTEXT as TestSerializationContext).delegate = null
(SerializationDefaults.RPC_SERVER_CONTEXT as TestSerializationContext).delegate = null
(SerializationDefaults.RPC_CLIENT_CONTEXT as TestSerializationContext).delegate = null
(SerializationDefaults.STORAGE_CONTEXT as TestSerializationContext).delegate = null
(SerializationDefaults.CHECKPOINT_CONTEXT as TestSerializationContext).delegate = null
private fun SerializationDefaults.resetTestSerialization() {
(SERIALIZATION_FACTORY as TestSerializationFactory).delegate = null
(P2P_CONTEXT as TestSerializationContext).delegate = null
(RPC_SERVER_CONTEXT as TestSerializationContext).delegate = null
(RPC_CLIENT_CONTEXT as TestSerializationContext).delegate = null
(STORAGE_CONTEXT as TestSerializationContext).delegate = null
(CHECKPOINT_CONTEXT as TestSerializationContext).delegate = null
}
class TestSerializationFactory : SerializationFactory() {

View File

@ -1,19 +1,10 @@
package net.corda.testing
import org.junit.After
import org.junit.Before
import org.junit.Rule
/**
* The beginnings of somewhere to inject implementations for unit tests.
*/
@Deprecated("Instead of extending this class, use SerializationEnvironmentRule in the same way.")
abstract class TestDependencyInjectionBase {
@Before
fun initialiseSerialization() {
initialiseTestSerialization()
}
@After
fun resetInitialisation() {
resetTestSerialization()
}
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
}