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.
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(

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

    # Check the result of get_balance().
    execution_info = await contract.get_balance().call()
    assert execution_info.result == (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