Oppy
Oppy

Reputation: 2887

How to write tests for micropython

I would like to write tests for the micropython code I am writing for the micro:bit. The examples here use doctest. I am open to work arounds for any testing system.

Working python example called testing_python.py:

def sum(a, b):
    '''
    >>> sum(3, 0)
    3
    '''
    return a + b

print(sum(2,2))

When I test using:

python -m doctest -v testing_python.py 

I get:

4
Trying:
    sum(3, 0)
Expecting:
    3
ok

Failing example using micropython for the micro:bit called testing_micropython.py:

from microbit import *

def sum(a, b):
    '''
    >>> sum(3, 0)
    3
    '''
    return a + b

print(sum(2,2))

When I test using:

python -m doctest -v testing_micropython.py 

I get

Traceback (most recent call last):
...
ModuleNotFoundError: No module named 'microbit'

I tried wrapping the 'import microbit' statement in a try, except clause. This will make this simple example work. However, when I start using any of the other non-python library functions found in the micro:bit library, such as Image or utime, then the doctest will fail again.

Upvotes: 3

Views: 1952

Answers (1)

ukBaz
ukBaz

Reputation: 7974

unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

This can be used to write and test embedded software like micropython without the hardware.

You can go as sophisticated as you want, but a simple way to not get an error on importing the microbit module is to mock the microbit module. e.g. Have the following files:

|- testing_micropython.py
|- microbit
  |- __init__.py

My testing_micropython.py has:

from microbit import *


def sum(a, b):
    """
    >>> sum(3, 0)
    3
    """
    return a + b

display.show(sum(2,2))

The microbit/__init__.py has:

from unittest.mock import MagicMock

display = MagicMock()

Which gives the following output:

python -m doctest -v testing_micropython.py
Trying:
    sum(3, 0)
Expecting:
    3
ok
1 items had no tests:
    testing_micropython
1 items passed all tests:
   1 tests in testing_micropython.sum
1 tests in 2 items.
1 passed and 0 failed.
Test passed.

As the micro:bit hardware is very memory constrained, I would avoid putting anything unnecessary in the file that will be loaded onto the micro:bit so I would suggest avoiding doctest.

Upvotes: 5

Related Questions