Testing
Mojo includes a framework for developing and executing unit tests. The framework
also supports testing code examples in the
documentation strings
(also known as docstrings) of your API references. The Mojo testing framework
consists of a set of assertions defined as part of the
Mojo standard library and the
mojo test
command line tool.
Get started
Let’s start with a simple example of writing and running Mojo tests.
1. Write tests
For your first example of using the Mojo testing framework, create a file named
test_quickstart.mojo
containing the following code:
# Content of test_quickstart.mojo
from testing import assert_equal
def inc(n: Int) -> Int:
return n + 1
def test_inc_zero():
# This test contains an intentional logical error to show an example of
# what a test failure looks like at runtime.
assert_equal(inc(0), 0)
def test_inc_one():
assert_equal(inc(1), 2)
In this file, the inc()
function is the test target. The functions whose
names begin with test_
are the tests. Usually the target should be in a
separate source file from its tests, but you can define them in the same file
for this simple example.
A test function fails if it raises an error when executed, otherwise it
passes. The two tests in this example use the assert_equal()
function,
which raises an error if the two values provided are not equal.
The implementation of test_inc_zero()
contains an intentional logical error
so that you can see an example of a failed test when you execute it in the
next step of this tutorial.
2. Execute tests
Then in the directory containing the file, execute the following command in your shell:
mojo test test_quickstart.mojo
You should see output similar to this (note that this example elides the full filesystem paths from the output shown):
Testing Time: 1.193s
Total Discovered Tests: 2
Passed : 1 (50.00%)
Failed : 1 (50.00%)
Skipped: 0 (0.00%)
******************** Failure: 'ROOT_DIR/test_quickstart.mojo::test_inc_zero()' ********************
Unhandled exception caught during execution
Error: At ROOT_DIR/test_quickstart.mojo:8:17: AssertionError: `left == right` comparison failed:
left: 1
right: 0
********************
The output starts with a summary of the number of tests discovered, passed, failed, and skipped. Following that, each failed test is reported along with its error message.
Next steps
- The
testing
module describes the assertion functions available to help implement tests. - Writing unit tests shows how to write unit tests and organize them into test files.
- The
mojo test
command describes how to execute and collect lists of tests. - Writing API documentation tests discusses how to use the Mojo testing framework to test code examples in your API documentation.