Simple testing for Python

2026-04-22 published

Sometimes, I need a simple testing method for a simple prototype script. This is my pydt.sh that is executable and in PATH:

#!/bin/sh
set -eu
python3 -c "import doctest ; import ${1%%.*} ; doctest.testmod(${1%%.*})"

Now, consider a Python script h.py:

def hypotenuse_for(a, b):
    """
    >>> assert 5 == hypotenuse_for(3, 4)
    >>> assert 10 == hypotenuse_for(6, 8)
    """
    return (a**2 + b**2)**0.5


if __name__ == "__main__":
    print(f"Hypotenuse for 3 and 4 is {hypotenuse_for(3, 4)}")

When we run it, the result is:

$ python3 h.py
Hypotenuse for 3 and 4 is 5.0

To test it, we run:

$ pydt.sh h.py
$

Nothing shown? That’s good. How we know it works, though? Let introduce failing test:

-    >>> assert 5 == hypotenuse_for(3, 4)
+    >>> assert 5 == hypotenuse_for(10, 4)

And run again:

$ pydt.sh h.py
**********************************************************************
File "/home/jiri/h.py", line 3, in h.hypotenuse_for
Failed example:
    assert 5 == hypotenuse_for(10, 4)
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python3.13/doctest.py", line 1395, in __run
        exec(compile(example.source, filename, "single",
        ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     compileflags, True), test.globs)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "<doctest h.hypotenuse_for[0]>", line 1, in <module>
        assert 5 == hypotenuse_for(10, 4)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
    AssertionError
**********************************************************************
1 item had failures:
   1 of   2 in h.hypotenuse_for
***Test Failed*** 1 failure.
go back | CC0 1.0