corda / net.corda.testing.node / MockServices

MockServices

open class MockServices : ServiceHub

An implementation of ServiceHub that is designed for in-memory unit tests of contract validation logic. It has enough functionality to do tests of code that queries the vault, inserts to the vault, and constructs/checks transactions. However it isn't enough to test flows and other aspects of an app that require a network. For that you should investigate MockNetwork.

There are a variety of constructors that can be used to supply enough data to simulate a node. Each mock service hub must have at least an identity of its own. The other components have defaults that work in most situations.

Constructors

<init>

Create a mock ServiceHub that looks for app code in the given package names, uses the provided identity service (you can get one from makeTestIdentityService) and represents the given identity.

MockServices(cordappPackages: Iterable<String>, initialIdentity: <ERROR CLASS>, identityService: IdentityService = makeTestIdentityService(), vararg moreKeys: KeyPair)
MockServices(cordappPackages: Iterable<String>, initialIdentityName: CordaX500Name, identityService: IdentityService = makeTestIdentityService(), key: KeyPair, vararg moreKeys: KeyPair)MockServices(cordappPackages: Iterable<String>, initialIdentity: <ERROR CLASS>, identityService: IdentityService, networkParameters: NetworkParameters, vararg moreKeys: KeyPair)
MockServices(cordappPackages: Iterable<String>, initialIdentity: <ERROR CLASS>, identityService: IdentityService, networkParameters: NetworkParameters, vararg moreKeys: KeyPair, keyManagementService: KeyManagementService)
MockServices(cordappPackages: List<String>, initialIdentityName: CordaX500Name, identityService: IdentityService, networkParameters: NetworkParameters)
MockServices(cordappPackages: List<String>, initialIdentityName: CordaX500Name, identityService: IdentityService, networkParameters: NetworkParameters, key: KeyPair)
MockServices(firstIdentity: <ERROR CLASS>, networkParameters: NetworkParameters, vararg moreIdentities: <ERROR CLASS>)
MockServices(cordappPackages: List<String>, firstIdentity: <ERROR CLASS>, vararg moreIdentities: <ERROR CLASS>)
MockServices(cordappPackages: List<String>, firstIdentity: <ERROR CLASS>, networkParameters: NetworkParameters, vararg moreIdentities: <ERROR CLASS>)

Create a mock ServiceHub that can't load CorDapp code, which uses the provided identity service (you can get one from makeTestIdentityService) and which represents the given identity.

MockServices(cordappPackages: Iterable<String>, initialIdentityName: CordaX500Name, identityService: IdentityService = makeTestIdentityService())

Create a mock ServiceHub that can't load CorDapp code, and which uses a default service identity.

MockServices(cordappPackages: Iterable<String>)

Create a mock ServiceHub which uses the package of the caller to find CorDapp code. It uses the provided identity service (you can get one from makeTestIdentityService) and which represents the given identity.

MockServices(initialIdentityName: CordaX500Name, identityService: IdentityService = makeTestIdentityService(), key: KeyPair, vararg moreKeys: KeyPair)

Create a mock ServiceHub which uses the package of the caller to find CorDapp code. It uses the provided identity service (you can get one from makeTestIdentityService) and which represents the given identity. It has no keys.

MockServices(initialIdentityName: CordaX500Name, identityService: IdentityService = makeTestIdentityService())

A helper constructor that requires at least one test identity to be registered, and which takes the package of the caller as the package in which to find app code. This is the most convenient constructor and the one that is normally worth using. The first identity is the identity of this service hub, the rest are identities that it is aware of.

MockServices(firstIdentity: <ERROR CLASS>, vararg moreIdentities: <ERROR CLASS>)

Create a mock ServiceHub which uses the package of the caller to find CorDapp code. It uses a default service identity.

MockServices()

Properties

attachments

Provides access to storage of arbitrary JAR files (which may contain only data, no code).

val attachments: MockAttachmentStorage

clock

A Clock representing the node's current time. This should be used in preference to directly accessing the clock so the current time can be controlled during unit testing.

open val clock: TestClock

contractUpgradeService

The ContractUpgradeService is responsible for securely upgrading contract state objects according to a specified and mutually agreed (amongst participants) contract version.

open val contractUpgradeService: ContractUpgradeService

cordappClassloader

Returns the classloader containing all jar deployed in the 'cordapps' folder.

val cordappClassloader: ClassLoader

cordappProvider

Provides access to anything relating to cordapps including contract attachment resolution and app context

open val cordappProvider: CordappProvider

diagnosticsService

The DiagnosticsService provides diagnostic level information about the node, including the current version of the node, and the CorDapps currently installed on the node. Note that this information should be used to provide diagnostics only, and no functional decisions should be made based on this.

open val diagnosticsService: DiagnosticsService

identityService

An identity service maintains a directory of parties by their associated distinguished name/public keys and thus supports lookup of a party given its key, or name. The service also manages the certificates linking confidential identities back to the well known identity (i.e. the identity in the network map) of a party.

open val identityService: IdentityService

keyManagementService

The key management service is responsible for storing and using private keys to sign things. An implementation of this may, for example, call out to a hardware security module that enforces various auditing and frequency-of-use requirements.

open val keyManagementService: KeyManagementService

myInfo

The NodeInfo object corresponding to our own entry in the network map.

open val myInfo: NodeInfo

networkMapCache

A network map contains lists of nodes on the network along with information about their identity keys, services they provide and host names or IP addresses where they can be connected to. The cache wraps around a map fetched from an authoritative service, and adds easy lookup of the data stored within it. Generally it would be initialised with a specified network map service, which it fetches data from and then subscribes to updates of.

open val networkMapCache: NetworkMapCache

networkParameters

Returns the network parameters the node is operating under.

open val networkParameters: NetworkParameters

networkParametersService

Provides access to historical network parameters that are used in transaction resolution.

open var networkParametersService: NetworkParametersService

servicesForResolution

val servicesForResolution: ServicesForResolution

validatedTransactions

A map of hash->tx where tx has been signature/contract validated and the states are known to be correct. The signatures aren't technically needed after that point, but we keep them around so that we can relay the transaction data to other nodes that need it.

open val validatedTransactions: TransactionStorage

vaultService

The vault service lets you observe, soft lock and add notes to states that involve you or are relevant to your node in some way. Additionally you may query and track states that correspond to various criteria.

open val vaultService: VaultService

Functions

addMockCordapp

Add the given package name to the list of packages which will be scanned for cordapp contract verification code

fun addMockCordapp(contractClassName: ContractClassName): Unit

cordaService

Return the singleton instance of the given Corda service type. This is a class that is annotated with CordaService and will have automatically been registered by the node.

open fun <T : SerializeAsToken> cordaService(type: Class<T>): T

jdbcSession

Exposes a JDBC connection (session) object using the currently configured database. Applications can use this to execute arbitrary SQL queries (native, direct, prepared, callable) against its Node database tables (including custom contract tables defined by extending net.corda.core.schemas.QueryableState).

open fun jdbcSession(): Connection

loadContractAttachment

Returns a dummy Attachment, in context of signature constrains non-downgrade rule this default to contract class version 1.

open fun loadContractAttachment(stateRef: StateRef): Attachment

loadState

Given a StateRef loads the referenced transaction and looks up the specified output ContractState.

open fun loadState(stateRef: StateRef): TransactionState<*>

loadStates

Given a Set of StateRef's loads the referenced transaction and looks up the specified output ContractState.

open fun loadStates(stateRefs: Set<StateRef>): Set<StateAndRef<ContractState>>

recordTransactions

Stores the given SignedTransactions in the local transaction storage and then sends them to the vault for further processing if statesToRecord is not StatesToRecord.NONE. This is expected to be run within a database transaction.

open fun recordTransactions(statesToRecord: StatesToRecord, txs: Iterable<SignedTransaction>): Unit

registerUnloadHandler

Allows the registration of a callback that may inform services when the app is shutting down.

open fun registerUnloadHandler(runOnStop: () -> Unit): Nothing

withEntityManager

Exposes the Java Persistence API (JPA) to flows via a restricted EntityManager. This method can be used to persist and query entities which inherit from MappedSchema. This is particularly useful if off-ledger data needs to be kept in conjunction with on-ledger state data.

open fun <T> withEntityManager(block: EntityManager.() -> T): T
open fun withEntityManager(block: Consumer<EntityManager>): Unit

Companion Object Functions

makeTestDatabaseAndMockServices

Makes database and mock services appropriate for unit tests.

fun makeTestDatabaseAndMockServices(cordappPackages: List<String>, identityService: IdentityService, initialIdentity: <ERROR CLASS>, networkParameters: NetworkParameters = testNetworkParameters(modifiedTime = Instant.MIN), vararg moreKeys: KeyPair): Pair<CordaPersistence, MockServices>

makeTestDatabaseAndPersistentServices

Makes database and persistent services appropriate for unit tests which require persistence across the vault, identity service and key managment service.

fun makeTestDatabaseAndPersistentServices(cordappPackages: List<String>, initialIdentity: <ERROR CLASS>, networkParameters: NetworkParameters = testNetworkParameters(modifiedTime = Instant.MIN), moreKeys: Set<KeyPair>, moreIdentities: Set<PartyAndCertificate>, cacheFactory: TestingNamedCacheFactory = TestingNamedCacheFactory()): Pair<CordaPersistence, MockServices>

makeTestDataSourceProperties

Make properties appropriate for creating a DataSource for unit tests.

fun makeTestDataSourceProperties(nodeName: String = SecureHash.randomSHA256().toString()): Properties

Extension Functions

getCashBalance

fun ServiceHub.getCashBalance(currency: Currency): Amount<Currency>

getCashBalances

fun ServiceHub.getCashBalances(): Map<Currency, Amount<Currency>>

ledger

Creates and tests a ledger built by the passed in dsl.

fun ServiceHub.ledger(notary: Party = TestIdentity.fresh("ledger notary").party, script: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>.() -> Unit): LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>

transaction

Creates a ledger with a single transaction, built by the passed in dsl.

fun ServiceHub.transaction(notary: Party = TestIdentity.fresh("transaction notary").party, script: TransactionDSL<TransactionDSLInterpreter>.() -> EnforceVerifyOrFail): LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>