Skip to content

Mojo Testing

A test is a small piece of code that checks your real code gives the right answer. Once you have a few, you can change your program without worrying that you quietly broke something: just run the tests again. Mojo’s standard library has everything you need in std.testing. One thing to know up front: Mojo 1.2 has no mojo test command. Older versions had one, and you’ll still see it in blog posts, but now a test file is a normal Mojo program that you run with mojo run. The official testing guide describes this current way.

The std.testing module has assert functions that raise an error when a check fails. The quickest test is a main that calls a few of them:

from std.testing import assert_equal, assert_true
def double(n: Int) -> Int:
return n * 2
def main() raises:
assert_equal(double(4), 8)
assert_true(double(0) == 0)
print("all checks passed")

Output:

all checks passed

assert_equal(a, b) does nothing if a == b, and raises an error if not. Because they raise, main needs raises (see Mojo Errors). Now add a wrong check:

from std.testing import assert_equal
def double(n: Int) -> Int:
return n * 2
def main() raises:
assert_equal(double(4), 8)
assert_equal(double(3), 7)
print("not printed")

You’ll see:

stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: At checks.mojo:8:17: AssertionError: `left == right` comparison failed:
left: 6
right: 7
mojo: error: execution exited with a non-zero result: 1

The message gives the file and line of the failed check, the value you got (left) and the value you expected (right). This works, but the first failure stops everything. For real tests you want each check run on its own, with a report at the end. That’s what TestSuite does.

Put each test in its own function whose name starts with test_, and let TestSuite find and run them:

from std.testing import assert_equal, TestSuite
def round_to_ten(n: Int) -> Int:
return (n + 5) // 10 * 10
def test_round_down() raises:
assert_equal(round_to_ten(42), 40)
def test_round_up() raises:
assert_equal(round_to_ten(47), 50)
def test_exact() raises:
assert_equal(round_to_ten(30), 30)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

Run it with mojo run test_rounding.mojo, and you’ll see (the numbers in brackets are times in seconds, and yours will differ):

Running 3 tests for test_rounding.mojo
PASS [ 0.001 ] test_round_down
PASS [ 0.001 ] test_round_up
PASS [ 0.001 ] test_exact
--------
Summary [ 0.001 ] 3 tests run: 3 passed , 0 failed , 0 skipped

Here’s how it fits together:

  • A test function starts with test_, takes no arguments, returns nothing and is marked raises. It passes if it finishes, and fails if it raises.
  • __functions_in_module() gives TestSuite a list of every function in this file. discover_tests picks the ones whose names start with test_.
  • .run() runs them one by one and prints the report.

That main line is the same in every test file, so you can just copy it.

Let’s break round_to_ten so it always rounds down, and give one check a msg that explains what we expected:

from std.testing import assert_equal, TestSuite
def round_to_ten(n: Int) -> Int:
return n // 10 * 10
def test_round_down() raises:
assert_equal(round_to_ten(42), 40)
def test_round_up() raises:
assert_equal(round_to_ten(47), 50, msg="47 should round up to 50")
def test_exact() raises:
assert_equal(round_to_ten(30), 30)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

You’ll see:

stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution:
Running 3 tests for test_rounding.mojo
PASS [ 0.001 ] test_round_down
FAIL [ 0.088 ] test_round_up
At test_rounding.mojo:10:17: AssertionError: `left == right` comparison failed:
left: 40
right: 50
reason: 47 should round up to 50
PASS [ 0.001 ] test_exact
--------
Summary [ 0.089 ] 3 tests run: 2 passed , 1 failed , 0 skipped
Test suite' test_rounding.mojo 'failed!
mojo: error: execution exited with a non-zero result: 1

Read it from the top: two tests passed, test_round_up failed on line 10, it got 40 where we wanted 50, and our msg shows up as reason:. The other tests still ran. At the end, the whole suite raises an error, so the program exits with a non-zero code. That’s what tools like CI servers look at to decide whether your tests passed.

The output looks a bit odd at the top (“Unhandled exception caught during execution:” right before the report). That’s just how 1.2 prints a failed suite: the report is the error message.

All of these live in std.testing, and all take an optional msg= that’s shown when the check fails:

Function Passes when
assert_true(x) x is True
assert_false(x) x is False
assert_equal(a, b) a == b
assert_not_equal(a, b) a != b
assert_almost_equal(a, b) two floats are close (you can set atol= or rtol=)
with assert_raises(): the code inside the block raises an error

Prefer assert_equal over assert_true(a == b): when it fails, it shows both values instead of just “condition was unexpectedly False”. The testing module reference lists every option.

Floats are stored in binary, so some decimal values can’t be exact. Compare them with assert_almost_equal, never assert_equal:

from std.testing import assert_almost_equal
def main() raises:
var a = 0.1
var b = 0.2
print(a + b)
assert_almost_equal(a + b, 0.3)
print("close enough")

Output:

0.30000000000000004
close enough

assert_equal(a + b, 0.3) would fail here, with left: 0.30000000000000004 and right: 0.3.

Good tests also check that bad input is rejected. assert_raises is used with with: the block must raise, or the test fails. Add contains= to check the message too:

from std.testing import assert_raises, TestSuite
def parse_age(text: String) raises -> Int:
var age = Int(text)
if age < 0:
raise Error("age can't be negative")
return age
def test_negative_age() raises:
with assert_raises(contains="negative"):
_ = parse_age("-4")
def test_not_a_number() raises:
with assert_raises():
_ = parse_age("ten")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

You’ll see:

Running 2 tests for test_age.mojo
PASS [ 0.001 ] test_negative_age
PASS [ 0.001 ] test_not_a_number
--------
Summary [ 0.002 ] 2 tests run: 2 passed , 0 failed , 0 skipped

_ = parse_age(...) throws the result away: we only care whether it raises. If the block doesn’t raise, the test fails with AssertionError: Didn't raise at .... If it raises an error that doesn’t contain the contains= text, that error fails the test.

Usually your code and its tests live in separate files. Say you have shop.mojo:

def total_price(price: Int, quantity: Int) raises -> Int:
if quantity < 0:
raise Error("quantity can't be negative")
return price * quantity

Then test_shop.mojo, in the same folder, imports from it by file name:

from shop import total_price
from std.testing import assert_equal, assert_raises, TestSuite
def test_total_price() raises:
assert_equal(total_price(3, 4), 12)
assert_equal(total_price(5, 0), 0)
def test_negative_quantity() raises:
with assert_raises(contains="negative"):
_ = total_price(3, -1)

Finish the file with the same main as before, and run it:

Terminal window
mojo run test_shop.mojo

If your code lives in a different folder, say src/, with tests in test/, tell Mojo where to look for imports with -I:

Terminal window
mojo run -I src test/test_shop.mojo

Without -I src you’d get error: unable to locate module 'shop'. Modules and imports get their own lesson, Mojo Modules.

A test file with TestSuite understands a few options. Put them after the file name:

Terminal window
mojo run test_shop.mojo --only test_total_price
mojo run test_shop.mojo --skip test_negative_quantity
mojo run test_shop.mojo --skip-all

--only runs just the named tests, --skip runs everything else, and --skip-all lists the tests without running any. Skipped tests show up as SKIP in the report. You can name several tests, separated by spaces. A name that doesn’t exist is an error (explicitly allowed test not found in suite: ...), which protects you from typos.

You can also skip a test in the code itself, for example one that needs a network connection:

from std.testing import assert_equal, TestSuite
def test_fast() raises:
assert_equal(1 + 1, 2)
def test_needs_network() raises:
raise Error("no network here")
def main() raises:
var suite = TestSuite.discover_tests[__functions_in_module()]()
suite.skip[test_needs_network]()
suite^.run()

You’ll see:

Running 2 tests for test_skip.mojo
PASS [ 0.001 ] test_fast
SKIP [ 0.001 ] test_needs_network
--------
Summary [ 0.001 ] 2 tests run: 1 passed , 0 failed , 1 skipped

Note the suite^.run(): run takes the suite over, so you hand it on with ^ (see Mojo Transfer).

Here’s a function that counts words separated by single spaces. Write a test file with three tests: "hello world" has 2 words, "mojo" has 1, and "" has 0. Run it. Does one fail?

def count_words(text: String) -> Int:
if text == "":
return 0
var count = 1
for c in text.codepoints():
if c == Codepoint.ord(" "):
count += 1
return count

Hint: copy the TestSuite layout from the rounding example and use assert_equal.

Show solution
from std.testing import assert_equal, TestSuite
def count_words(text: String) -> Int:
if text == "":
return 0
var count = 1
for c in text.codepoints():
if c == Codepoint.ord(" "):
count += 1
return count
def test_two_words() raises:
assert_equal(count_words("hello world"), 2)
def test_one_word() raises:
assert_equal(count_words("mojo"), 1)
def test_empty() raises:
assert_equal(count_words(""), 0)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

You’ll see:

Running 3 tests for test_words.mojo
PASS [ 0.001 ] test_two_words
PASS [ 0.001 ] test_one_word
PASS [ 0.001 ] test_empty
--------
Summary [ 0.001 ] 3 tests run: 3 passed , 0 failed , 0 skipped

All three pass. Try adding a test for "two spaces" (two spaces in a row) expecting 2: it fails with left: 3, which is exactly the kind of bug tests are for.

Write a test that checks parse_quantity("abc") raises an error whose message contains not convertible. Put the function and the test in one file.

def parse_quantity(text: String) raises -> Int:
return Int(text)

Hint: with assert_raises(): and _ = ... inside it.

Show solution
from std.testing import assert_raises, TestSuite
def parse_quantity(text: String) raises -> Int:
return Int(text)
def test_rejects_text() raises:
with assert_raises(contains="not convertible"):
_ = parse_quantity("abc")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()

You’ll see:

Running 1 tests for test_quantity.mojo
PASS [ 0.001 ] test_rejects_text
--------
Summary [ 0.001 ] 1 tests run: 1 passed , 0 failed , 0 skipped

Int("abc") raises “String is not convertible to integer…”, so the block raises and the message contains not convertible.

  • There’s no mojo test in 1.2: a test file is a program, run with mojo run.
  • Assert functions from std.testing raise an error when a check fails; add msg= to explain why.
  • Test functions start with test_, take no arguments and are marked raises.
  • TestSuite.discover_tests[__functions_in_module()]().run() finds and runs them, and prints PASS/FAIL per test.
  • A failing suite exits with a non-zero code, which is what CI tools check.
  • Use assert_almost_equal for floats and with assert_raises(): to check that bad input is rejected.
  • --only, --skip and suite.skip[...]() run just some tests; -I src helps tests find your code.

Next up: debugging, how to find out why a test fails.

Quick check

1. How do you run Mojo tests in Mojo 1.2?
2. When does a test function fail?
3. Which check should you use for 0.1 + 0.2 stored in variables?
4. What does TestSuite.discover_tests[__functions_in_module()]() pick up?