Skip to content

Commit

Permalink
test: Fix up doc tests and run them on CI
Browse files Browse the repository at this point in the history
  • Loading branch information
igamigo committed Jan 9, 2025
1 parent 206e247 commit 2e21253
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 41 deletions.
14 changes: 14 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,17 @@ jobs:
run: make test-default
- name: test-prove
run: make test-prove

doc-tests:
name: doc-tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@main
- uses: Swatinem/rust-cache@v2
with:
key: doc-tests-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
save-if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/next' }}
- name: Install rust
run: rustup update --no-self-update
- name: Run doc-tests
run: make test-docs
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ test-default: ## Run default tests excluding `prove`
$(DEBUG_ASSERTIONS) $(BACKTRACE) cargo nextest run --profile default --cargo-profile test-release --features concurrent,testing --filter-expr "not test(prove)"


.PHONY: test-docs
test-docs: ## Run documentation tests
$(WARNINGS) $(DEBUG_ASSERTIONS) cargo test --doc $(ALL_FEATURES_BUT_ASYNC)


.PHONY: test-prove
test-prove: ## Run `prove` tests (tests which use the Miden prover)
$(DEBUG_ASSERTIONS) $(BACKTRACE) cargo nextest run --profile prove --cargo-profile test-release --features concurrent,testing --filter-expr "test(prove)"
Expand Down
35 changes: 28 additions & 7 deletions miden-tx/src/testing/mock_chain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ impl MockFungibleFaucet {
&self.0
}

pub fn id(&self) -> AccountId {
self.0.id()
}

pub fn mint(&self, amount: u64) -> Asset {
FungibleAsset::new(self.0.id(), amount).unwrap().into()
}
Expand Down Expand Up @@ -201,15 +205,27 @@ impl PendingObjects {
///
/// # Examples
///
/// ## Create mock objects
/// ## Create mock objects and build a transaction context
/// ```
/// let mut mock_chain = MockChain::default();
/// # use miden_tx::testing::{Auth, MockChain, TransactionContextBuilder};
/// # use miden_objects::{assets::FungibleAsset, Felt, notes::NoteType};
/// let mut mock_chain = MockChain::new();
/// let faucet = mock_chain.add_new_faucet(Auth::BasicAuth, "USDT", 100_000); // Create a USDT faucet
/// let asset = faucet.mint(1000);
/// let note = mock_chain.add_p2id_note(asset, sender...);
/// let sender = mock_chain.add_new_wallet(Auth::BasicAuth);
///
/// mock_chain.build_tx_context(sender.id(), &[note.id()], &[]).build().execute()
/// let target = mock_chain.add_new_wallet(Auth::BasicAuth);
/// let note = mock_chain
/// .add_p2id_note(
/// faucet.id(),
/// target.id(),
/// &[FungibleAsset::mock(10)],
/// NoteType::Public,
/// None,
/// )
/// .unwrap();
/// mock_chain.seal_block(None);
/// let tx_context = mock_chain.build_tx_context(sender.id(), &[note.id()], &[]).build();
/// // tx_context.execute();
/// ```
///
/// ## Executing a Simple Transaction
Expand All @@ -218,12 +234,17 @@ impl PendingObjects {
/// an authenticator.
///
/// ```
/// # use miden_tx::testing::{Auth, MockChain, TransactionContextBuilder};
/// # use miden_objects::{assets::FungibleAsset, Felt, transaction::TransactionScript};
/// # use miden_lib::transaction::TransactionKernel;
/// let mut mock_chain = MockChain::new();
/// let sender = mock_chain.add_existing_wallet(Auth::BasicAuth, vec![asset]); // Add a wallet with assets
/// let sender = mock_chain.add_existing_wallet(Auth::BasicAuth, vec![FungibleAsset::mock(256)]); // Add a wallet with assets
/// let receiver = mock_chain.add_new_wallet(Auth::BasicAuth); // Add a recipient wallet
///
/// let tx_context = mock_chain.build_tx_context(sender.id(), &[], &[]);
/// let tx_script = TransactionScript::compile("...", vec![], TransactionKernel::testing_assembler()).unwrap();
///
/// let script = "begin nop end";
/// let tx_script = TransactionScript::compile(script, vec![], TransactionKernel::testing_assembler()).unwrap();
///
/// let transaction = tx_context.tx_script(tx_script).build().execute().unwrap();
/// mock_chain.apply_executed_transaction(&transaction); // Apply transaction
Expand Down
19 changes: 8 additions & 11 deletions miden-tx/src/testing/tx_context/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,32 +40,29 @@ pub type MockAuthenticator = BasicAuthenticator<ChaCha20Rng>;

/// [TransactionContextBuilder] is a utility to construct [TransactionContext] for testing
/// purposes. It allows users to build accounts, create notes, provide advice inputs, and
/// execute code.
/// execute code. The VM process can be inspected afterward.
///
/// # Examples
///
/// Create a new account and execute code:
/// ```
/// let tx_context = TransactionContextBuilder::with_fungible_faucet(
/// acct_id.into(),
/// Felt::ZERO,
/// Felt::new(1000),
/// )
/// .build();
/// # use miden_tx::testing::TransactionContextBuilder;
/// # use miden_objects::{accounts::AccountBuilder,Felt, FieldElement};
/// let tx_context = TransactionContextBuilder::with_standard_account(Felt::ONE).build();
///
/// let code = "
/// use.kernel::prologue
/// use.test::account
///
/// begin
/// exec.prologue::prepare_transaction
/// push.0
/// exec.account::get_item
/// push.5
/// swap drop
/// end
/// ";
///
/// let process = tx_context.execute_code(code);
/// assert!(process.is_ok());
/// let process = tx_context.execute_code(code).unwrap();
/// assert_eq!(process.stack.get(0), Felt::new(5),);
/// ```
pub struct TransactionContextBuilder {
assembler: Assembler,
Expand Down
4 changes: 2 additions & 2 deletions objects/src/accounts/component/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use vm_processor::MastForest;

mod template;
pub use template::{
AccountComponentMetadata, AccountComponentTemplate, InitStorageData, StorageEntry,
StoragePlaceholder, StorageValue,
AccountComponentMetadata, AccountComponentTemplate, FeltRepresentation, InitStorageData,
StorageEntry, StoragePlaceholder, StorageValue, WordRepresentation,
};

use crate::{
Expand Down
53 changes: 34 additions & 19 deletions objects/src/accounts/component/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use super::AccountType;
use crate::errors::AccountComponentTemplateError;

mod storage;
pub use storage::{InitStorageData, StorageEntry, StoragePlaceholder, StorageValue};
pub use storage::*;

// ACCOUNT COMPONENT TEMPLATE
// ================================================================================================
Expand Down Expand Up @@ -134,40 +134,55 @@ impl AccountComponentMetadata {
Ok(component)
}

/// Retrieves the set of storage placeholder keys (identified by a string) that require a value
/// at the moment of component instantiation. These values will be used for initializing
/// storage slot values, or storage map entries.
/// Retrieves the set of storage placeholder keys (identified by a string) that
/// require a value at the moment of component instantiation. These values will
/// be used for initializing storage slot values, or storage map entries.
///
/// # Examples
///
/// An [AccountComponentMetadata] may have a single-slot storage entry where the last element
/// of the slot's word is templated:
/// # Example
///
/// ```
/// let first_felt = FeltRepresentation::Decimal(Felt::ZERO);
/// # use semver::Version;
/// # use std::collections::BTreeSet;
/// # use miden_objects::{testing::account_code::CODE, accounts::{
/// # AccountComponent, AccountComponentMetadata, InitStorageData, StorageEntry,
/// # StoragePlaceholder, StorageValue,
/// # AccountComponentTemplate, FeltRepresentation, WordRepresentation},
/// # assembly::Assembler, Felt};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let first_felt = FeltRepresentation::Decimal(Felt::new(0u64));
/// let second_felt = FeltRepresentation::Decimal(Felt::new(1u64));
/// let third_felt = FeltRepresentation::Decimal(Felt::new(2u64));
/// // Templated element:
/// let last_element = FeltRepresentation::Template(StoragePlaceholder::new("foo"));
/// let last_element = FeltRepresentation::Template(StoragePlaceholder::new("foo")?);
///
/// let storage_entry = StorageEntry::new_value(
/// "test-entry",
/// "a test entry",
/// Some("a test entry"),
/// 0,
/// WordRepresentation::new([first_felt, second_felt, third_felt, last_element]),
/// WordRepresentation::Array([first_felt, second_felt, third_felt, last_element]),
/// );
/// ```
///
/// At the moment of instantiating a component that defines this storage entry, we
/// must pass a value that replaces "foo":
///
/// ```
/// let init_storage_data = InitStorageData::new([(
/// StoragePlaceholder::new("foo")?,
/// StorageValue::Felt(Felt::new(300u64)),
/// )]);
///
/// let component_template = AccountComponentMetadata::new(
/// "test".into(),
/// "desc".into(),
/// Version::parse("0.1.0").unwrap(),
/// BTreeSet::new(),
/// vec![],
/// )?;
///
/// let library = Assembler::default().assemble_library([CODE]).unwrap();
/// let template = AccountComponentTemplate::new(component_template, library);
///
/// let component = AccountComponent::from_template(&template, &init_storage_data)?;
/// # Ok(())
/// # }
/// ```
pub fn get_storage_placeholders(&self) -> BTreeSet<StoragePlaceholder> {
let mut placeholder_set = BTreeSet::new();
for storage_entry in &self.storage {
Expand Down Expand Up @@ -307,9 +322,9 @@ mod tests {
)
.unwrap();

let serialized = toml::to_string(&original_config).unwrap();
let deserialized: AccountComponentMetadata = toml::from_str(&serialized).unwrap();
let serialized = original_config.as_toml().unwrap();

let deserialized = AccountComponentMetadata::from_toml(&serialized).unwrap();
assert_eq!(deserialized, original_config)
}

Expand Down
4 changes: 2 additions & 2 deletions objects/src/accounts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ pub use code::{procedure::AccountProcedureInfo, AccountCode};

mod component;
pub use component::{
AccountComponent, AccountComponentMetadata, AccountComponentTemplate, InitStorageData,
StorageEntry, StoragePlaceholder, StorageValue,
AccountComponent, AccountComponentMetadata, AccountComponentTemplate, FeltRepresentation,
InitStorageData, StorageEntry, StoragePlaceholder, StorageValue, WordRepresentation,
};

pub mod delta;
Expand Down

0 comments on commit 2e21253

Please sign in to comment.