scalus.testing

package scalus.testing

Members list

Type members

Classlikes

object ArbitraryDerivation extends AutoDerivation[Arbitrary]

Derives an Arbitrary instance for a given type T using Magnolia.

Derives an Arbitrary instance for a given type T using Magnolia.

Attributes

Example
   given Arbitrary[AddrKeyHash] = ArbitraryDerivation.autoDerived[AddrKeyHash]
Supertypes
trait AutoDerivation[Arbitrary]
trait Derivation[Arbitrary]
trait SealedTraitDerivation
trait CommonDerivation[Arbitrary]
class Object
trait Matchable
class Any
Show all
Self type
case class CheckFailure(predicate: String, message: String, location: SourceLocation) extends Exception

Error thrown when a Scenario.check fails.

Error thrown when a Scenario.check fails.

Attributes

Supertypes
trait Product
trait Equals
class Exception
class Throwable
trait Serializable
class Object
trait Matchable
class Any
Show all
case class CommandsState[S](emulator: ImmutableEmulator, contractState: S, rng: Seed)

State for ScalaCheck Commands testing (abstract model).

State for ScalaCheck Commands testing (abstract model).

This state is used by ScalaCheck's Commands framework to track the abstract model state during property-based testing. It wraps an ImmutableEmulator (which provides the blockchain state), the contract-specific state of type S, and an RNG seed for deterministic command generation.

Type parameters

S

the contract state type

Value parameters

contractState

the contract-specific state extracted from UTxOs

emulator

the immutable emulator representing blockchain state

rng

ScalaCheck RNG seed for deterministic generation

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
class ContractScalaCheckCommands[S](initialEmulator: ImmutableEmulator, step: ContractStepVariations[S], timeout: FiniteDuration = ...)(checkInvariants: (BlockchainReader, S) => Future[Prop] = ...)(using ec: ExecutionContext) extends Commands

Bridges ContractStepVariations with ScalaCheck's stateful testing framework.

Bridges ContractStepVariations with ScalaCheck's stateful testing framework.

This adapter enables property-based testing of smart contract interactions by:

==Two Emulators Pattern==

Per ScalaCheck Commands pattern, we maintain two separate emulators:

  • '''State''' (CommandsState): The abstract model - wraps ImmutableEmulator + contract state S + RNG seed. Used for genCommand, nextState, and preCondition.
  • '''Sut''' (scalus.cardano.node.Emulator): The system under test - the existing mutable Emulator class. Used for run (actual execution) and postCondition verification.

This separation allows ScalaCheck to detect discrepancies between model and implementation.

==Slot Advancement==

Slot advancement is controlled by overriding ContractStepVariations.slotDelays in the step. This returns slot delays that are included as StepAction.Wait actions alongside transaction submissions.

==JVM-Only==

This class uses Await.result for synchronous execution and is JVM-only. For cross-platform testing, use ScenarioExplorer instead.

==Example Usage==

val auctionBidStep = new ContractStepVariations[AuctionState] {
 def extractState(reader: BlockchainReader)(using EC) = ???
 def makeBaseTx(reader: BlockchainReader, state: AuctionState)(using EC) = ???
 def variations = TxVariations.standard.default(...)
 override def slotDelays(state: AuctionState) = Seq(10L, 100L)
}

// Without invariant checking
val emulator = ImmutableEmulator.withAddresses(Seq(Alice.address, Bob.address))
val commands = ContractScalaCheckCommands(emulator, auctionBidStep)()
commands.property().check()

// With invariant checking
val commandsWithInvariants = ContractScalaCheckCommands(emulator, auctionBidStep) {
 (reader, state) => Future {
   Prop(state.balance >= Coin.zero) && Prop(state.highestBidder.isDefined)
 }
}

Type parameters

S

the contract state type

Value parameters

checkInvariants

async function to check invariants after successful transactions

ec

execution context for async operations

initialEmulator

the starting emulator state with funded addresses

step

the contract step variations to test

timeout

timeout for async operations (default: 30 seconds)

Attributes

Companion
object
Supertypes
trait Commands
class Object
trait Matchable
class Any

Attributes

Companion
class
Supertypes
class Object
trait Matchable
class Any
Self type

Bundles contract step state extraction, base template building, and variations.

Bundles contract step state extraction, base template building, and variations.

ContractStepVariations represents a single step in a contract interaction (e.g., "bid on auction", "claim HTLC"). It combines:

  • State extraction from blockchain UTxOs
  • Base template construction (builder + sponsor + signer)
  • Transaction variations for testing

Use with ScenarioExplorer for exhaustive testing.

Type parameters

S

the contract state type

Attributes

Supertypes
class Object
trait Matchable
class Any
case class ImmutableEmulator(state: State, env: UtxoEnv, slotConfig: SlotConfig = ..., evaluatorMode: EvaluatorMode = ..., validators: Iterable[Validator] = ..., mutators: Iterable[Mutator] = ...)

An immutable emulator for Cardano transactions.

An immutable emulator for Cardano transactions.

Unlike Emulator, this emulator is fully immutable: every state-changing operation (submit, advanceSlot) returns a new ImmutableEmulator instance, leaving the original unchanged.

This makes it suitable for use in functional state-threading patterns such as the Scenario monad, where branching and backtracking require independent state copies.

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
object IntegrationTest extends Tag

Tag for integration tests that require external services (blockchain nodes, APIs).

Tag for integration tests that require external services (blockchain nodes, APIs).

Tests tagged with this tag are excluded from default test runs. To run integration tests, use:

sbt "project/testOnly -- -n scalus.testing.IntegrationTest"

Attributes

Supertypes
class Tag
class Object
trait Matchable
class Any
Self type
sealed trait Scenario[A]

A non-deterministic, state-threading monad for testing Cardano transaction scenarios.

A non-deterministic, state-threading monad for testing Cardano transaction scenarios.

Scenario is a sealed ADT:

Use async[Scenario] (from dotty-cps-async) for imperative-looking syntax.

Type parameters

A

the result type

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Branches[A]
class Done[A]
class FromStream[A]
class Leaf[A]
class ScenarioError[A]
class WaitFuture[A]
Show all
object Scenario

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
Scenario.type
object ScenarioCheck

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type

Explores contract state space by applying actions at each step.

Explores contract state space by applying actions at each step.

ScenarioExplorer performs bounded exploration of contract interactions. At each depth it:

  1. Gets a snapshot reader
  2. Calls the step function which performs one interaction using normal Scenario operations
  3. Actions (Scenario.submit, Scenario.sleep) are automatically logged
  4. On successful step, recurses to next depth
  5. On check failure, captures violation with the full action path
  6. On other errors, propagates

The step function can use Scenario.choices/Scenario.fromCollection for branching, Scenario.submit for transactions, Scenario.sleep for time advancement, and Scenario.check for invariant verification.

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
case class ScenarioState(emulator: ImmutableEmulator, rng: Seed, actionLog: List[StepAction] = ...)

State threaded through Scenario computations.

State threaded through Scenario computations.

Value parameters

actionLog

log of actions taken during exploration (newest first for O(1) append)

emulator

the immutable emulator state

rng

ScalaCheck RNG seed for deterministic generation

Attributes

Companion
object
Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
object ScenarioState

Attributes

Companion
class
Supertypes
trait Product
trait Mirror
class Object
trait Matchable
class Any
Self type
case class SourceLocation(file: String, line: Int)

Source location captured at compile time.

Source location captured at compile time.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all

Standard transaction variation patterns for property-based and exhaustive testing.

Standard transaction variation patterns for property-based and exhaustive testing.

This object provides factory methods for creating common transaction variation patterns. Each method returns a TxVariations[S] or TxSamplingVariations[S] that can be combined with other variations using the ++ operator.

Variations receive a TxTemplate containing the base transaction builder, sponsor, and signer. They modify the builder or create new transactions using the template's sponsor/signer.

==Example Usage==

val stealVariation = StandardTxVariations.removeContractOutput[AuctionState](
 extractUtxo = _.utxo,
 redeemer = _ => BidRedeemer.toData,
 script = auctionScript
)

// Combine with other variations
val allVariations = stealVariation ++ corruptDatumVariation

// Use in testing - txTemplate provides base tx, sponsor, signer
stealVariation.enumerate(provider, state, txTemplate)

Attributes

Supertypes
class Object
trait Matchable
class Any
Self type
sealed trait StepAction

An action taken during scenario exploration.

An action taken during scenario exploration.

Used to track the path of actions that led to a violation or successful exploration.

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
class Submit
class Wait
object StepAction

Attributes

Companion
trait
Supertypes
trait Sum
trait Mirror
class Object
trait Matchable
class Any
Self type
StepAction.type
trait TxSamplingVariations[S] extends TxVariations[S]

Sampling-based variations for fuzz testing.

Sampling-based variations for fuzz testing.

Unlike TxVariations which enumerates all variations exhaustively, TxSamplingVariations uses a generator to sample variations. This is useful for large or continuous variation spaces.

The primary method is gen; enumerate samples from the generator.

Type parameters

S

the contract state type

Attributes

Supertypes
trait TxVariations[S]
class Object
trait Matchable
class Any
case class TxTemplate(builder: TxBuilder, sponsor: Address, signer: TransactionSigner)

A transaction template bundling a builder with its sponsor and signer.

A transaction template bundling a builder with its sponsor and signer.

TxTemplate represents a transaction that is ready to be completed and signed. It bundles:

  • builder: the TxBuilder with inputs, outputs, etc.
  • sponsor: the address that pays fees (provides UTxOs for fees/collateral)
  • signer: signs the completed transaction

This allows variations to be self-contained - each variation knows who will sign it.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all
trait TxVariations[S]

Transaction variations generator for property-based and exhaustive testing.

Transaction variations generator for property-based and exhaustive testing.

TxVariations generates multiple transaction variations from a given contract state and base template. Each variation represents a different way to construct a transaction (e.g., different input selection, datum values, redeemer arguments).

The TxTemplate provides the sponsor (who pays fees) and signer, while variations build the transaction body.

Type parameters

S

the contract state type, typically extracted from blockchain UTxOs

Attributes

Companion
object
Supertypes
class Object
trait Matchable
class Any
Known subtypes
object TxVariations

Attributes

Companion
trait
Supertypes
class Object
trait Matchable
class Any
Self type
case class Violation(predicate: String, message: String, location: SourceLocation, path: Seq[StepAction])

A violation found during scenario exploration.

A violation found during scenario exploration.

Attributes

Supertypes
trait Serializable
trait Product
trait Equals
class Object
trait Matchable
class Any
Show all