Skip to main content

Announcing mojo-pytest

· 3 min read
Alex G Rice
Geodata rambler and developer, aka guidorice

mojo-pytest is a Mojo🔥 language test runner plugin for pytest. Try it for your mixed Python and Mojo codebases. Here are some tips and example command line usage...

What is Mojo​

Mojo is a new programming language that bridges the gap between research and production by combining Python syntax and ecosystem with systems programming and metaprogramming features. Mojo is still young, but it is designed to become a superset of Python over time. source: Mojo docs

What is pytest​

The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries. source: pytest docs

pytest, meet Mojo​

This package implements a pytest plugin to discover and run Mojo tests, alongside your Python tests. Although pytest does not have any awareness of Mojo source or package structure, pytest is extensible. In summary, plugin.py calls mojo test in a sub-process and parses the outputs and exit codes.

Example test using Mojo standard library​

This simple Mojo module shows testing native Mojo code, and also calling into a Python module for testing vs reference implementation.

# file: example_tests/my_package/test_fibonacci.mojo

from python import Python
from testing import assert_equal
from my_package.fibonacci import fibonacci


def test_fibonacci():
"""
Test fibonacci 10th number.
"""
var expect = 55
var got = fibonacci(10)
assert_equal(got, expect)


def test_fibonacci_reference():
"""
Test mojo fibonacci versus python "reference" implementation.
"""
var py = Python.import_module("my_package.fibonacci")
for n in range(0, 10):
var expect = py.fibonacci(n)
var got = fibonacci(n)
assert_equal(got, expect)

pytest runs both the Python tests, and the Mojo tests. Example command line usage:

$ pytest --mojo-include example_src/ example_tests/

================================ test session starts =======================
platform darwin -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0
rootdir: /Users/guidorice/mojo/mojo-pytest
configfile: pyproject.toml
plugins: mojo-24.5
collected 6 items

example_tests/my_package/my_test.mojo . [ 16%]
example_tests/my_package/test_fibonacci.mojo .. [ 50%]
example_tests/my_package/test_fibonacci.py . [ 66%]
example_tests/my_package/test_fire.🔥 . [ 83%]
example_tests/my_package/test_random_tensor.mojo . [100%]

================================ 6 passed in 13.55s =======================

Check it out at the GitHub repo: https://github.com/guidorice/mojo-pytest.

info

For compatibility, mojo-pytest follows the version numbering of mojo, ex: v24.5.

Contributor​

Thanks to Leandro Leites Barrios @lleiets for contributions and suggesting the idea of using the pytest plugin API, instead of just a config script.

Further reading​