Test Scenario

For complicated transaction testing, Sui features the test_scenario module. This module provides functions to emulate transactions, define senders, and check the results of transactions.

/// This module contains a dummy store implementation where anyone can purchase
/// the same book for any amount of SUI greater than zero. The store owner can
/// collect the proceeds using the `StoreOwnerCap` capability.
///
/// In the tests section, we use the `test_scenario` module to simulate a few
/// transactions and test the store functionality. The test scenario is a very
/// powerful tool which can be used to simulate multiple transactions in a single
/// test.
///
/// The reference for this module is the "Black Books" TV series.
module examples::black_books {
    use sui::transfer;
    use sui::sui::SUI;
    use sui::coin::{Self, Coin};
    use sui::object::{Self, UID};
    use sui::balance::{Self, Balance};
    use sui::tx_context::{Self, TxContext};

    /// Trying to purchase the book for 0 SUI.
    const ECantBeZero: u64 = 0;

    /// A store owner capability. Allows the owner to collect proceeds.
    struct StoreOwnerCap has key, store { id: UID }

    /// The "Black Books" store located in London.
    /// Only sells one book: "The Little Book of Calm".
    struct BlackBooks has key {
        id: UID,
        balance: Balance<SUI>,
    }

    /// The only book sold by the Black Books store.
    struct LittleBookOfCalm has key, store { id: UID }

    /// Share the store object and transfer the store owner capability to the sender.
    fun init(ctx: &mut TxContext) {
        transfer::transfer(StoreOwnerCap {
            id: object::new(ctx)
        }, tx_context::sender(ctx));

        transfer::share_object(BlackBooks {
            id: object::new(ctx),
            balance: balance::zero()
        })
    }

    /// Purchase the "Little Book of Calm" for any amount of SUI greater than zero.
    public fun purchase(
        store: &mut BlackBooks, coin: Coin<SUI>, ctx: &mut TxContext
    ): LittleBookOfCalm {
        assert!(coin::value(&coin) > 0, ECantBeZero);
        coin::put(&mut store.balance, coin);

        // create a new book
        LittleBookOfCalm { id: object::new(ctx) }
    }

    /// Collect the proceeds from the store and return them to the sender.
    public fun collect(
        store: &mut BlackBooks, _cap: &StoreOwnerCap, ctx: &mut TxContext
    ): Coin<SUI> {
        let amount = balance::value(&store.balance);
        coin::take(&mut store.balance, amount, ctx)
    }

    // === Tests ===

    #[test_only]
    // The `init` is not run in tests, and normally a test_only function is
    // provided so that the module can be initialized in tests. Having it public
    // is important for tests located in other modules.
    public fun init_for_testing(ctx: &mut TxContext) {
        init(ctx);
    }

    // using a test-only attibute because this dependency can't be used in
    // production code and `sui move build` will complain about unused imports.
    //
    // the `sui::test_scenario` module is only available in tests.
    #[test_only] use sui::test_scenario;
    #[test_only] use std::vector;
    #[test_only] use sui::vec_map;

    #[test]
    // This test uses `test_scenario` to emulate actions performed by 3 accounts.
    // A single scenario follows this structure:
    //
    // - `begin` - starts the first tx and creates the sceanario
    // - `next_tx` ... - starts the next tx and sets the sender
    // - `end` - wraps up the scenario
    //
    // It provides functions to start transactions, get the `TxContext, pull
    // objects from account inventory and shared pool, and check transaction
    // effects.
    //
    // In this test scenario:
    // 1. Bernard opens the store;
    // 2. Manny buys the book for 10 SUI and sends it to Fran;
    // 3. Fran sends the book back and buys it herself for 5 SUI;
    // 4. Bernard collects the proceeds and transfers the store to Fran;
    fun the_book_store_drama() {
        // it's a good idea to name addresses for readability
        // Bernard is the store owner, Manny is searching for the book,
        // and Fran is the next door store owner.
        let (bernard, manny, fran) = (@0x1, @0x2, @0x3);

        // create a test scenario with sender; initiates the first transaction
        let scenario = test_scenario::begin(bernard);

        // === First transaction ===

        // run the module initializer
        // we use curly braces to explicitly scope the transaction;
        {
            // `test_scenario::ctx` returns the `TxContext`
            let ctx = test_scenario::ctx(&mut scenario);
            init_for_testing(ctx);
        };

        // `next_tx` is used to initiate a new transaction in the scenario and
        // set the sender to the specified address. It returns `TransactionEffects`
        // which can be used to check object changes and events.
        let prev_effects = test_scenario::next_tx(&mut scenario, manny);

        // make assertions on the effects of the first transaction
        let created_ids = test_scenario::created(&prev_effects);
        let shared_ids = test_scenario::shared(&prev_effects);
        let sent_ids = test_scenario::transferred_to_account(&prev_effects);
        let events_num = test_scenario::num_user_events(&prev_effects);

        assert!(vector::length(&created_ids) == 2, 0);
        assert!(vector::length(&shared_ids) == 1, 1);
        assert!(vec_map::size(&sent_ids) == 1, 2);
        assert!(events_num == 0, 3);

        // === Second transaction ===

        // we will store the `book_id` in a variable so we can use it later
        let book_id = {
            // test scenario can pull shared and sender-owned objects
            // here we pull the store from the pool
            let store = test_scenario::take_shared<BlackBooks>(&scenario);
            let ctx = test_scenario::ctx(&mut scenario);
            let coin = coin::mint_for_testing<SUI>(10_000_000_000, ctx);

            // call the purchase function
            let book = purchase(&mut store, coin, ctx);
            let book_id = object::id(&book);

            // send the book to Fran
            sui::transfer::transfer(book, fran);

            // now return the store to the pool
            test_scenario::return_shared(store);

            // return the book ID so we can use it across transactions
            book_id
        };

        // === Third transaction ===

        // next transaction - Fran looks in her inventory and finds the book
        // she decides to return it to Manny and buy another one herself
        test_scenario::next_tx(&mut scenario, fran);
        {
            // objects can be taken from the sender by ID (if there's multiple)
            // or if there's only one object: `take_from_sender<T>(&scenario)`
            let book = test_scenario::take_from_sender_by_id<LittleBookOfCalm>(&scenario, book_id);
            // send the book back to Manny
            sui::transfer::transfer(book, manny);

            // now repeat the same steps as before
            let store = test_scenario::take_shared<BlackBooks>(&scenario);
            let ctx = test_scenario::ctx(&mut scenario);
            let coin = coin::mint_for_testing<SUI>(5_000_000_000, ctx);

            // same as before - purchase the book
            let book = purchase(&mut store, coin, ctx);
            sui::transfer::transfer(book, fran);

            // don't forget to return
            test_scenario::return_shared(store);
        };

        // === Fourth transaction ===

        // last transaction - Bernard collects the proceeds and transfers the store to Fran
        test_scenario::next_tx(&mut scenario, bernard);
        {
            let store = test_scenario::take_shared<BlackBooks>(&scenario);
            let cap = test_scenario::take_from_sender<StoreOwnerCap>(&scenario);
            let ctx = test_scenario::ctx(&mut scenario);
            let coin = collect(&mut store, &cap, ctx);

            sui::transfer::public_transfer(coin, bernard);
            sui::transfer::transfer(cap, fran);
            test_scenario::return_shared(store);
        };

        // finally, the test scenario needs to be finalized
        test_scenario::end(scenario);
    }
}