Writing unit tests

This page demonstrates how to write unit tests for your StarkNet contracts. The cairo-lang package provides a set of python classes that simulates the behavior of the StarkNet system. We’ll use pytest as the unit test infrastructure.

Start by installing pytest:

pip install pytest pytest-asyncio

Let’s write a unit test for the contract from Your first contract. Create a file named contract.cairo and copy the contract code into it.

Now, copy the following code into a python file named contract_test.py:

import os
import pytest

from starkware.starknet.testing.starknet import Starknet

# The path to the contract source code.
CONTRACT_FILE = os.path.join(
    os.path.dirname(__file__), "contract.cairo")


# The testing library uses python's asyncio. So the following
# decorator and the ``async`` keyword are needed.
@pytest.mark.asyncio
async def test_increase_balance():
    # Create a new Starknet class that simulates the StarkNet
    # system.
    starknet = await Starknet.empty()

    # Deploy the contract.
    contract = await starknet.deploy(CONTRACT_FILE)

    # Invoke increase_balance() twice.
    await contract.increase_balance(amount=10).invoke()
    await contract.increase_balance(amount=20).invoke()

    # Check the result of get_balance().
    assert await contract.get_balance().call() == (30,)

This test creates an instance of the Starknet testing class. This class allows deploying StarkNet contracts and interacting with them. The test deploys our contract and invokes increase_balance twice. At the end it verifies that calling the get_balance() method returns the expected result.

Run the test using pytest:

pytest contract_test.py