Skip to main content

TestEnvironment

Struct TestEnvironment 

Source
pub struct TestEnvironment { /* private fields */ }
Expand description

An in-process Thruput instance for testing contracts natively.

A TestEnvironment owns a fresh in-memory database and runtime context (backed by hogd via FFI). Constructors return a TestEnvironmentHandle; clone the handle to share the environment across helpers.

use thruput_native_exec::test_environment::TestEnvironment;
use thruput_xdr::types::ContractAddress;

let env = TestEnvironment::no_cost();
let addr = ContractAddress::new([0x11; 32]);
let result = env.transact(|tx| tx.call(&addr).run(|| { /* guest code */ }));
result.assert_success();

Setting the SDK_TEST_ENABLE_SYSCALL_LOGGING environment variable turns on syscall tracing for environments created afterwards.

Implementations§

Source§

impl TestEnvironment

Source

pub fn new(cost_model: Option<&StorageCostModel>) -> Rc<TestEnvironment>

Creates an environment on the default test network (test_network_hash).

Source

pub fn with_network_hash( cost_model: Option<&StorageCostModel>, network_hash: &NetworkHash, ) -> Rc<TestEnvironment>

Creates an environment on a caller-chosen network, with mock_genesis_root_contract as the genesis root.

Source

pub fn with_genesis_root_contract( cost_model: Option<&StorageCostModel>, network_hash: &NetworkHash, genesis_root_contract: &Contract, ) -> Rc<TestEnvironment>

Creates an environment installing a caller-chosen genesis root contract instead of mock_genesis_root_contract.

Source

pub fn builder() -> TestEnvironmentBuilder

Start configuring an environment that needs settings the plain constructors do not reach – notably the chain’s network config parameters.

Returns a TestEnvironmentBuilder; chain with_* methods, then finish with build:

use thruput_native_exec::test_environment::TestEnvironment;

let env = TestEnvironment::builder()
    .no_cost()
    .with_max_sha256_buffers(2)
    .build();
Source

pub fn default() -> Rc<TestEnvironment>

Environment with the chain-default cost model on the default test network. Not the Default trait: constructors return a handle.

Source

pub fn no_cost() -> Rc<TestEnvironment>

Environment in which every storage operation costs zero.

Source

pub fn enable_syscall_logging()

Turn on FFI-level syscall logging to stderr for environments created after the call.

Source

pub fn advance_block(self: &Rc<TestEnvironment>)

Advance to the next block, making committed effects visible to subsequent transactions. Panics if a transaction executed but was neither committed nor aborted.

The new block takes its timepoint from the wall clock, so thruput_sdk::block::get_block_timepoint reports a plausible present-day value that moves between blocks. Use advance_block_at to drive contract logic keyed on time – deadlines, expiry, vesting, rate limits.

The SDK path is a plain code span, not an intra-doc link: thruput-sdk depends on this crate, not the other way round, so there is nothing here to resolve it against.

Source

pub fn advance_block_at(self: &Rc<TestEnvironment>, block_timepoint: TimePoint)

Advance to the next block with its timepoint pinned to block_timepoint (Unix nanoseconds) rather than read from the clock.

Blocks only move forward in time, so this panics if block_timepoint precedes the current block’s. Note the environment opens its first block on the wall clock, so pin forward from the current thruput_sdk::block::get_block_timepoint rather than at an absolute past date.

Source

pub fn get_current_cost_model(self: &Rc<TestEnvironment>) -> StorageCostModel

The storage cost model the environment’s database is running with.

Source

pub fn get_network_config(self: &Rc<TestEnvironment>) -> NetworkConfig

The execution parameters the environment’s chain is running under (e.g. max_sha256_buffers, the VM’s live hash-stream cap).

Source

pub fn get_snapshot_storage_item( self: &Rc<TestEnvironment>, addr: &ContractAddress, key: &StorageKeyContractData, ) -> Option<WireStorageItem>

Read a committed contract-data item from the current block snapshot (None if the key holds nothing).

Source

pub fn get_snapshot_auth_data( self: &Rc<TestEnvironment>, addr: &ContractAddress, ) -> Option<AddressAuthData>

Read an address’s committed AddressAuthData (its registered keys and required weight) from the current block snapshot (None if the address has none).

Source

pub fn register_mock<F>(self: &Rc<TestEnvironment>, f: F) -> MockContract
where F: FnOnce(&mut MockContract),

Create a mock contract, register methods onto it, and make it deployable in the test environment.

The registrar may be a single generated __mock function or a closure that combines multiple interface registrars onto one mock.

Source

pub fn transaction(self: &Rc<TestEnvironment>) -> TransactionBuilder

Start configuring a transaction to execute in this environment.

Returns a TransactionBuilder; chain with_* methods (e.g. with_auth_claim) to customize the mocked transaction context, then finish with transact, transact_manual, or build.

ⓘ
env.transaction()
    .with_auth_claim(my_claim)
    .transact(|tx| tx.call(&addr).run(|| { /* ... */ }));
Source

pub fn transact( self: &Rc<TestEnvironment>, f: impl FnOnce(&mut MockTransactionHandler) -> FrameResult, ) -> TransactResult

Execute a transaction with auto-commit and the default configuration.

Creates a MockTransactionHandler, gives the closure a mutable reference, and always calls try_commit_transaction when the closure returns (hogd handles abort internally when the root frame reverted).

The transaction has exactly one root frame: a second tx.call inside the closure panics; use a child frame or another transact.

Shorthand for env.transaction().transact(f); use transaction to customize the transaction first.

Source

pub fn transact_manual<R>( self: &Rc<TestEnvironment>, f: impl FnOnce(&mut MockTransactionHandler) -> R, ) -> R

Execute a transaction with manual commit/abort control and the default configuration.

The closure receives a MockTransactionHandler and is responsible for calling tx.try_commit_transaction() or tx.abort_transaction(). The closure’s return value is forwarded as the return value of transact_manual.

Shorthand for env.transaction().transact_manual(f); use transaction to customize the transaction first.

Source

pub fn setup_create_contract( self: &Rc<TestEnvironment>, contract: &Contract, ) -> SHA256Hash

Setup phase: create a contract in Thruput state (not deployed at any address). Returns the contract hash. Run before any transactions in the test.

Source

pub fn setup_create_deployment( self: &Rc<TestEnvironment>, addr: &ContractAddress, contract: &Contract, )

Setup phase: deploy an already-created contract at addr. Run before any transactions in the test.

Source

pub fn setup_grant_storage_tokens( self: &Rc<TestEnvironment>, addr: &ContractAddress, tokens: i64, )

Setup phase: grant storage tokens to the contract at addr, as if granted in a previous block. Like setup_create_contract and setup_create_deployment, run before any transactions in the test.

Source

pub fn verify_signed_transaction_auth( self: &Rc<TestEnvironment>, tx: &SignedTransaction, ) -> AuthVerifyErrorCode

Check the auth claims on the provided transaction against the auth data loaded from the database.

May perform additional checks (such as checking block height limits) not performed by the static version. Will additionally fail if addresses without auth data are referenced.

Source

pub fn verify_signed_transaction_auth_static( tx: &SignedTransaction, source_auth_data: Option<&AddressAuthData>, network_hash: &NetworkHash, ) -> AuthVerifyErrorCode

Check the auth claims on the provided transaction against the provided source and auxiliary auth data. Does not load any information from the database.

Pass None to represent “no registered auth data” (the pubkey-claim case). Pass Some(d) to supply serialized AddressAuthData.

network_hash is part of every signature preimage, so it must be the network the signatures were produced for — see thruput_domain_separator::transaction_signature_preimage. There is no database here to read it from, so it is passed explicitly; test_network_hash is what a TestEnvironment would use.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> StaticIfNoAlloc for T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.