Testing

As we know testing is integral to any piece of software! Cairo has support for unit and integration testing (see this chapter in The Cairo Book).

Cairo has two different test runners, integrated with scarb:

  • Starknet Foundry, which is principally aimed at Starknet development, but presents useful features for pure Cairo development as well.
  • Cairo Test, which is a lightweight, pure Cairo test runner.

We'll use Starknet Foundry in the rest of these examples.

From the testing chapters linked above, we see how to write unit tests and integration tests. Organizationally, we can place unit tests in the modules they test and integration tests in their own tests/ directory:

foo
├── Scarb.toml
├── src
│   └── lib.cairo
└── tests
    ├── my_test.cairo
    └── my_other_test.cairo

Each file in tests is a separate integration test, i.e. a test that is meant to test your library as if it were being called from a dependent crate.

The Testing chapter elaborates on the two different testing styles: Unit, and Integration.

scarb naturally provides an easy way to run all of your tests!

$ scarb test

You should see output like this:

$ scarb test 
     Running test test (snforge test)
    Blocking waiting for file lock on registry db cache
    Blocking waiting for file lock on registry db cache
   Compiling test test v0.1.0 (listings/scarb/test/Scarb.toml)
   Compiling test(listings/scarb/test/Scarb.toml)
    Finished `dev` profile target(s) in 10 seconds


Collected 4 test(s) from test package
Running 4 test(s) from tests/
[PASS] test_tests::test_bar (gas: ~1)
[PASS] test_tests::test_foo_bar (gas: ~1)
[PASS] test_tests::test_foo (gas: ~1)
[PASS] test_tests::test_baz (gas: ~1)
Running 0 test(s) from src/
Tests: 4 passed, 0 failed, 0 skipped, 0 ignored, 0 filtered out

You can also run tests whose name matches a pattern:

$ scarb test test_foo
$ scarb test test_foo
     Running test test (snforge test)
   Compiling test test v0.1.0 (listings/scarb/test/Scarb.toml)
   Compiling test(listings/scarb/test/Scarb.toml)
    Finished `dev` profile target(s) in 8 seconds


Collected 2 test(s) from test package
Running 0 test(s) from src/
Running 2 test(s) from tests/
[PASS] test_tests::test_foo_bar (gas: ~1)
[PASS] test_tests::test_foo (gas: ~1)
Tests: 2 passed, 0 failed, 0 skipped, 0 ignored, 2 filtered out