Skip to content

Testing contracts ​

After you have created a test scenario as described in Test scenarios, you can originate (deploy) your contracts to it and test their operation.

Instantiating and originating contracts ​

To originate a contract within a test scenario, create an instance of the contract, which automatically calls its class's __init__() method. Then add it to the scenario with the += operator, as in this example:

smartpy
def main():
    class MyContract(sp.Contract):
        def __init__(self):
            pass

    class MyContract2(sp.Contract):
        def __init__(self, x):
            self.data.x = x
            pass

    class MyContract3(sp.Contract):
        def __init__(self, x, y):
            self.data.x = x
            self.data.y = y


@sp.add_test()
def test():
    scenario = sp.test_scenario(main, "A Test")
    c1 = main.MyContract()
    c2 = main.MyContract2(2)
    c3 = main.MyContract3(x=5, y=2)
    scenario += c1
    scenario += c2
    scenario += c3

The contract object's origination_result property includes information about the simulated origination transaction, such as the compiled Michelson code of the contract. See Origination result for the available fields.

Origination result ​

After scenario += contract, contract.origination_result exposes the compiled contract and initial storage from Python.

For example:

smartpy
@sp.module
def main():
    class C(sp.Contract):
        def __init__(self):
            self.data.x = 0

        @sp.entrypoint
        def ep(self, x):
            self.data.x = x


@sp.add_test()
def test():
    scenario = sp.test_scenario("origination result")
    c = main.C()
    scenario += c

    # Plain Michelson, ready to copy into a .tz file or pass to octez-client
    print(c.origination_result["code_tz"])

    # Same contract with SmartPy comments and stack annotations (for debugging)
    print(c.origination_result["code_tz_annotated"])

Michelson and storage fields ​

FieldDescription
code_tzCompiled contract as plain Michelson text, without comments. Use this field when you need deployable Michelson (for example with octez-client originate).
code_tz_annotatedCompiled contract as Michelson text with SmartPy comments and stack annotations. This matches the annotated output written to step_*_contract.tz files when running a scenario.
code_jsonCompiled contract as Micheline JSON.
storage_tzInitial storage as Michelson text.
storage_jsonInitial storage as Micheline JSON.
storage_pyInitial storage as a SmartPy expression.
types_pySmartPy type definitions (tstorage, tparameter, and related types) for the contract.

The scenario output folder also contains related files (step_*_contract.tz, step_*_contract.json, step_*_storage.tz, and so on). The code_tz_annotated field matches the content of step_*_contract.tz; code_tz is the plain Michelson variant without comments.

Other fields ​

origination_result also includes metadata used by the IDE and scenario UI, such as address, balance, code_html, code_micheline, storage_html, code_size, storage_size, and errors.

Interacting with contracts ​

As described in Test scenarios, a test scenario runs contracts in a simulated Tezos environment. You can interact with contracts only within this simulation.

For example, if you access a variable within a contract's storage, the result is an expression. To get the value of that storage variable, you must evaluate it in the context of the simulation, such as with the scenario.verify function.

For example, this code shows how to get a value from a contract's storage as an expression and evaluate it:

smartpy
@sp.add_test()
def test():
    scenario = sp.test_scenario("simple_test", main)
    contract = main.MyContract(4)
    scenario += contract

    # Contract values are expressions until evaluated
    storage_expression = contract.data.value

    # scenario.p(storage_expression)
    # TypeError: Object of type Expr is not JSON serializable

    # if storage_expression > 2:
    #     scenario.p("Larger than 2")
    # Exception: Cannot convert expression to bool. Conditionals are forbidden on contract expressions.

    scenario.verify(storage_expression == 4)  # True

Calling entrypoints ​

After you create an instance of a contract and add it to the scenario, you can call its entrypoints as methods on the contract object. For example, this test scenario calls an entrypoint and verifies that its storage changed as expected:

smartpy
@sp.module
def main():
    class MyCounter(sp.Contract):
        def __init__(self, initialValue: sp.nat):
            self.data.value = initialValue

        @sp.entrypoint
        def increment(self, update):
            self.data.value += update


@sp.add_test()
def test():
    # Create a test scenario
    # Specify the output folder and a module or list of modules to import
    scenario = sp.test_scenario("Test for my smart contract", main)

    # Create an instance of a contract
    # Automatically calls the __init__() method of the contract's class
    contract = main.MyCounter(5)
    # Add the contract to the scenario
    scenario += contract
    # Check the expected value in the contract storage
    scenario.verify(contract.data.value == 5)

    # Call an entrypoint
    contract.increment(3)
    # Check the expected value in the contract storage
    scenario.verify(contract.data.value == 8)

When a name is both an entrypoint and a view, contract.foo(...) is ambiguous and raises an error. Call the entrypoint through the entrypoints namespace:

smartpy
contract.entrypoints.foo(args)

Use contract.onchain_views.foo(...) or contract.offchain_views.foo(...) for the view. See Calling views.

If the entrypoint accepts more than one parameter, you must pass the values as a record or as an implied record by naming the values, as in this example:

smartpy
@sp.add_test()
def test():
    scenario = sp.test_scenario(main, "A Test")
    contract = main.MyContract()
    scenario += contract

    # Implied record
    contract.exampleEntrypoint(a=5, b=6)
    # Explicit record
    contract.exampleEntrypoint(sp.record(a=5, b=6))

After the entrypoint parameters, you can include any of these context parameters to change how the entrypoint runs and is evaluated:

ParameterTypeAccessorDescription
_sendersp.address or sp.test_accountsp.senderThe simulated sender of the computation.
Specific to computation.
_sourcesp.address or sp.test_accountsp.sourceThe simulated source of the computation.
Specific to computation.
_chain_idsp.chain_idsp.chain_idThe simulated chain_id.
Preserved until changed.
_levelsp.natsp.levelThe simulated block level.
Preserved until changed.
_nowsp.timestampsp.nowThe simulated block timestamp.
Preserved until changed.
_voting_powerssp.map[sp.key_hash, sp.nat]sp.total_voting_power,
sp.voting_power
The simulated voting powers for the test.
Preserved until changed.
_amountsp.mutezsp.amountThe simulated amount of mutez to send with the smart contract call.
_validsp.boolNoneTells the interpreter if the transaction is expected to fail or not. True by default.
_exceptionany typeNoneThe value the transaction is expected to fail with. If present, valid must be False.

For example, to set the account that calls an entrypoint, create a test account as described in Test accounts and use that account as the _sender or _source parameter. This example limits an entrypoint to a specific caller and fails if another address calls it:

smartpy
import smartpy as sp


@sp.module
def main():
    class MyContract(sp.Contract):
        def __init__(self, admin):
            self.data.admin = admin
            self.data.counter = 0

        @sp.entrypoint
        def myEntryPoint(self):
            assert self.data.admin == sp.sender
            self.data.counter += 1


@sp.add_test()
def test():
    scenario = sp.test_scenario("test_scenario", main)

    admin = sp.test_account("admin").address
    c1 = main.MyContract(admin)
    scenario += c1
    scenario.verify(c1.data.counter == 0)

    # Call the entrypoint as admin
    c1.myEntryPoint(_sender=admin)
    scenario.verify(c1.data.counter == 1)

    # Verify that you can't call as any other address
    alice = sp.test_account("alice").address
    c1.myEntryPoint(_sender=alice, _valid=False)
    scenario.verify(c1.data.counter == 1)

The scenario object keeps track of calls to smart contracts in its entrypoint_calls property. This property includes information like the entrypoint called, the parameter passed, the addresses of the caller and contract, and the contract balance. For example, you can get the Michelson-encoded parameter passed in the most recent call with this command:

smartpy
print(scenario.entrypoint_calls[-1][1]["message"]["arg_michelson"])

Verifying the state of storage ​

To evaluate whether a call to an entrypoint worked as intended, you can check the value of the contract storage via the data property of the contract object, as in the test in the previous example. As described in Interacting with contracts, accessing the contract storage results in an expression, not the actual value in storage.

To evaluate the storage expression, use scenario functions like scenario.verify, scenario.verify_equal, and scenario.show. You can assign the value of the storage to a variable in the test and manipulate that variable (such as adding to numbers), but you cannot evaluate that variable outside of contract calls and those scenario functions.

For example, this test stores the contract storage in a variable named currentStorage. The test can use the variable but cannot evaluate it except within the scenario functions:

smartpy
@sp.module
def main():
    class Counter(sp.Contract):
        def __init__(self, initial_value):
            sp.cast(initial_value, sp.int)
            self.data.value = initial_value

        @sp.entrypoint
        def add(self, delta):
            self.data.value += delta

        @sp.entrypoint
        def sub(self, delta):
            self.data.value -= delta


@sp.add_test()
def test():
    scenario = sp.test_scenario("MyCounter tests")
    contract = main.Counter(5)
    scenario += contract

    # Call an entrypoint
    contract.add(3)

    # Get the value of the storage and use it in
    # a scenario function
    scenario.verify(contract.data.value == 8)

    # Get the value of storage
    currentStorage = contract.data.value

    # Use it in a contract call
    contract.add(currentStorage)

    # Can't access the storage variable in this way
    # if (currentStorage != 16):
    #     scenario.show("Storage is incorrect")

    # Verify the value within a scenario function
    scenario.verify(currentStorage == 16)
scenario.verify(expression) → 

To verify conditions within a scenario, use scenario.verify(<condition>).

smartpy
scenario.verify(contract.data.myParameter == 51)
scenario.verify_equal(expr1, expr2) → 

To verify an equality condition, use scenario.verify_equal(<left_expression>, <right_expression>) which works on both comparable and non-comparable types.

smartpy
scenario.verify_equal(contract.data.myList, [2, 3, 5, 7])

Testing exceptions ​

You can test exceptions in entrypoints either by catching the error in an ordinary Python try block (recommended) or by passing _valid=False when you call the entrypoint. For more information about exceptions, see Exceptions.

For example, this code includes an entrypoint that throws an exception and uses both ways of testing the exception:

python
import smartpy as sp


@sp.module
def main():
    class MyCounter(sp.Contract):
        def __init__(self, initialValue: sp.nat):
            self.data.value = initialValue

        @sp.entrypoint
        def increment(self, update):
            assert update < 6, "Increment by less than 6"
            self.data.value += update


@sp.add_test()
def test():
    scenario = sp.test_scenario("Test for my smart contract", main)
    contract = main.MyCounter(5)
    scenario += contract

    # Test exceptions
    # Using native try-catch (recommended).
    try:
        contract.increment(10)
    except sp.FailwithException as e:
        assert e.error == "Increment by less than 6"
    else:
        raise "Entrypoint should have failed"

    # Using the SmartPy _valid argument
    contract.increment(10, _valid=False, _exception="Increment by less than 6")

_exception matches the value the compiled contract fails with. A failure without an error message of its own fails with a value that the exceptions flag generates, by default its line number in the SmartPy source, so a test expecting it breaks whenever the lines above move. We recommend giving each failure you test an error message (see Error messages).

When the value does not tell what failed, the simulator shows a context below it, in the logs as in the IDE: what SmartPy reports about the failure beyond the value. Mockup mode shows none. For example:

Expected error: 113
  Context: Missing item in map

_exception is compared with the value only, and with its type, as scenario.verify_equal compares: the types must unify, and the values be equal. A literal takes the type of the failure: 5 matches the nat 5, while sp.int(5) does not, nor does the string "5". A record matches neither the tuple of its fields nor a record of another layout; a record whose layout is not given takes that of the failure. Mockup mode gets the value as Michelson, as a caller of the contract does, without its type: there, values that compile alike match, such as the nat 5 and the int 5, or a record and the tuple of its fields in the order of its layout, and a record whose layout is not given has the default layout.

_exception only matches the value of a failure, raised by raise, assert or a failing unwrap_some. Other failures, such as a contract spending more than its balance or a mutez overflow, are protocol errors: the call raises sp.RuntimeException with the protocol's message, which a scenario catches with try:

python
try:
    contract.withdraw(sp.mutez(2000))
except sp.RuntimeException as e:
    assert e.message.startswith("Balance of contract ")
else:
    raise AssertionError("Entrypoint should have failed")

You can test exceptions in expressions that return a value, including lambdas and views, with the sp.catch_exception function. This function returns an option that contains sp.Some with the exception or None if the expression succeeds. This example uses the sp.catch_exception function to test a view that throws an exception:

python
import smartpy as sp


@sp.module
def main():
    class MyCounter(sp.Contract):
        def __init__(self, initialValue: sp.nat):
            self.data.value = initialValue

        @sp.entrypoint
        def increment(self, update):
            assert update < 6, "Increment by less than 6"
            self.data.value += update

        @sp.onchain_view()
        def pass_even_value(self, value):
            assert sp.mod(value, 2) == 0, "Pass an even value"
            return self.data.value


@sp.add_test()
def test():
    scenario = sp.test_scenario("Test for my smart contract", main)
    contract = main.MyCounter(5)
    scenario += contract

    # Test view

    scenario.verify(
        sp.catch_exception(contract.pass_even_value(11))
        == sp.Some("Pass an even value")
    )
sp.catch_exception(expression, [t]) → sp.option[t]

Catches an exception in a SmartPy expression.

Optionally, you can pass the type of the value returned by the exception as the parameter t.

This method is used to test failing conditions of expressions (views, lambdas, ...). It returns an sp.option of type t that contains sp.Some(<exception>) if the expression fails or None if it succeeds.

Testing tickets ​

As described in Tickets, tickets always have the address of the contract that created the ticket as the ticketer field. If you need to test that a ticket came from another contract, such as sending a ticket to an entrypoint, you can create it in the test scenario with the sp.test_ticket function. This function allows you to set the ticketer to any address. You can use tickets created in this way only in test scenarios.

sp.test_ticket(ticketer: sp.address, contents: t, amount: sp.nat) → sp.ticket

Creates a ticket that you can use in test scenarios. Tickets created with the sp.test_ticket function are useful only in test scenarios; you cannot use these tickets in real transactions because doing so would allow you to create a false ticket.

For example, this contract has an entrypoint that accepts tickets. The test scenario creates a ticket with the sp.test_ticket function and sends it to the entrypoint:

smartpy
import smartpy as sp


@sp.module
def main():
    class TicketTest(sp.Contract):
        def __init__(self, initial_value):
            sp.cast(initial_value, sp.nat)
            self.data.value = initial_value
            self.data.ticket_sender = None
            sp.cast(self.data.ticket_sender, sp.option[sp.address])

        # Accept ticket, add the value and address to storage, and destroy the ticket
        @sp.entrypoint
        def accept_ticket(self, passed_ticket):
            sp.cast(passed_ticket, sp.ticket[sp.string])
            (ticket_data, new_ticket) = sp.read_ticket(passed_ticket)
            self.data.ticket_sender = sp.Some(ticket_data.ticketer)
            self.data.value += ticket_data.amount


@sp.add_test()
def test():
    scenario = sp.test_scenario("ticket_test", main)
    contract = main.TicketTest(0)
    scenario += contract

    arbitrary_address = sp.address("KT1R2LTg3mQoLvHtUjo2xSi7RMBUJ1sJkDiD")
    test_ticket = sp.test_ticket(arbitrary_address, "hello", sp.nat(5))
    contract.accept_ticket(test_ticket)
    scenario.verify_equal(contract.data.value, sp.nat(5))
    scenario.verify_equal(contract.data.ticket_sender, sp.Some(arbitrary_address))

Contract instance methods ​

In addition to methods for each entrypoint, contracts have these instance methods:

contract.get_source() → 

Returns the source code of the contract. See metadata.

contract.get_offchain_views() → 

Returns the off-chain views of the contract. See metadata.

contract.get_onchain_views() → 

Returns the on-chain views of the contract.

contract.get_generated_michelson() → 

Returns the Michelson code the contract. See metadata.

contract.get_error_map() → 

Returns the contract's error map. See metadata and "exceptions" flag.

These instance methods can be called only before adding the contract to the scenario:

contract.set_initial_balance(balance: sp.tez) → 

Set the initial balance for the contract.

python
@sp.module
def main():
    class MyContract(sp.Contract):
        def __init__(self):
            pass


scenario = sp.test_scenario("test_scenario", main)
contract = main.MyContract()
contract.set_initial_balance(sp.tez(20))
scenario += contract
contract.data =  x: any → 
Replace a field in the contract's storage.

This is mostly useful to initialize the metadata big map. See metadata.

Contract data ​

When a variable contract represents a contract in a scenario, we can access some associated data:

  • contract.data: Contract storage

  • contract.balance: Contract balance

  • contract.baker: Contract optional delegated baker

  • contract.address: Contract address within the scenario

    Details

    In storage or similar circumstances, deployed contracts get addresses of the form:

    • KT1TezoooozzSmartPyzzSTATiCzzzwwBFA1
    • KT1Tezooo1zzSmartPyzzSTATiCzzzyfC8eF
    • KT1Tezooo2zzSmartPyzzSTATiCzzzwqqQ4H
    • KT1Tezooo3zzSmartPyzzSTATiCzzzseJjWC
    • KT1Tezooo4zzSmartPyzzSTATiCzzzyPVdv3
    • KT1Tezooo5zzSmartPyzzSTATiCzzzz48Z4p
    • KT1Tezooo6zzSmartPyzzSTATiCzzztY1196
    • KT1Tezooo7zzSmartPyzzSTATiCzzzvTbG1z
    • KT1Tezooo8zzSmartPyzzSTATiCzzzzp29d1
    • KT1Tezooo9zzSmartPyzzSTATiCzzztdBMLX
    • KT1Tezoo1ozzSmartPyzzSTATiCzzzw8CmuY
    • ...
  • contract.typed

    Retrieve its testing typed contract value.

    To access entrypoints, you can use field notation:

    • contract.typed.my_entrypoint: Typed entrypoint my_entrypoint of contract contract.

Testing expressions (views and lambdas) ​

Testing views and lambdas is different from testing entrypoints because views and lambdas return SmartPy expressions. SmartPy does not evaluate these expressions until you tell it to.

Calling views ​

When a contract has a single view with a given name, call it directly on the contract instance:

smartpy
expression = contract.getValue()

When a contract defines both an on-chain and an off-chain view with the same name, use the onchain_views or offchain_views namespace to choose which one to call:

smartpy
expression = contract.onchain_views.is_operator(args)
expression = contract.offchain_views.is_operator(args)

Calling contract.is_operator(args) in this case raises an error that explains how to disambiguate.

When a name is both an entrypoint and a view, contract.foo(...) also raises. Use contract.entrypoints.foo(...) for the entrypoint, or contract.onchain_views.foo(...) / contract.offchain_views.foo(...) for the view. See Calling entrypoints.

sp.View(contract, view_name) → callable

Returns a callable that invokes the named view on contract. The view kind is resolved from the contract metadata. If the name is unique, the call works whether the view is on-chain or off-chain. If both kinds exist, SmartPy raises an error and you must use contract.onchain_views or contract.offchain_views instead.

smartpy
expression = sp.View(contract, "get_balance")(args)

Dynamic contract handles returned by scenario.dynamic_contract support the same calling conventions, including entrypoints, onchain_views, and offchain_views.

sp.is_failing(expression) → 

Returns True when an expression results in failure and False when the expression succeeds.

sp.catch_exception(expression, [t]) → sp.option[t]

Evaluates an expression, catches any failures in it, and returns an option.

This method is used to test failing conditions of expressions. It returns an sp.option of type t that contains sp.Some(<exception>) when the expression fails or None when it succeeds. The t parameter is optional; in most cases you can leave it out.

scenario.show(expression, html = True) → 

Evaluate an expression and writes its result to the log.

ParameterTypeDescription
htmlboolTrue by default, False to export not in HTML but in source code format.
python
expression = sp.record(a=1, b=2)
scenario.show(expression, html=True)

scenario.show(contract.data.myParameter1 * 12)
scenario.show(contract.data)
scenario.compute(expression, **context_args) → t

Evaluate an expression and return its result.

smartpy
x = scenario.compute(c1.data.myParameter1 * 12)

This example calls an on-chain view and then evaluates the expression it returns:

smartpy
@sp.module
def main():
    class MyCounter(sp.Contract):
        def __init__(self, initialValue: sp.nat):
            self.data.value = initialValue

        @sp.onchain_view
        def getValue(self):
            return self.data.value


@sp.add_test()
def test():
    scenario = sp.test_scenario("view_test", main)
    contract = main.MyCounter(5)
    scenario += contract

    expression = contract.getValue()
    scenario.show(expression)
    scenario.verify(expression == 5)

This example tests an expression that fails. Note that the creation of the expression does not fail because SmartPy has not evaluated the expression yet. Then the test scenario tests the failure, which implicitly evaluates the expression.

smartpy
@sp.module
def main():
    class MyContract(sp.Contract):
        @sp.onchain_view
        def alwaysFails(self):
            assert 1 == 2, "Failure"


@sp.add_test()
def test():
    scenario = sp.test_scenario("expression_test", main)
    contract = main.MyContract()
    scenario += contract

    expression = contract.alwaysFails()  # No exception yet
    scenario.verify(sp.is_failing(expression))
    scenario.verify(sp.catch_exception(expression, sp.string) == sp.Some("Failure"))

Testing dynamic contracts ​

Contracts in SmartPy can be created in two ways, statically as shown above, or dynamically via a call to the [sp.create_contract] statement from within an entrypoint.

We can refer to a contract that was created dynamically using scenario.dynamic_contract(<module>.<Contract>, offset), this returns a handle that can then be used as for static contracts.

scenario.dynamic_contract(template_ref: sp.Contract, offset:int | None) → sp.contract[t]

Returns a handle to the dynamic contract of class type template_ref=<module>.<Contract> that was created at offset.

The template_ref is used to check that the referenced contract has the correct class type.

The offset, if given, specifies the position in the list of dynamic contracts created so far. So offset=0 would refer to the first dynamically created contract and offset=-1 would refer to the most recently created dynamic contract. If not given it will default to the most recently created dynamic contract.

For example, to refer to the most recently created dynamic contract and check the class type is main.MyContract, we would use

python
dyn = scenario.dynamic_contract(main.MyContract)

Where-as

python
dyn = scenario.dynamic_contract(main.MyContract, offset=-2)

will refer to the last but one dynamic contract and check the class type is main.MyContract.

The handle dyn can now be used to call entrypoints, verify data etc

python
dyn.myEntrypoint(3)
scenario.verify(dyn.data == 3)