TIL

Testing a Single-File Python Script

Handy for one-off scripts or small AWS Lambda functions.

#!/usr/bin/env python3
import sys
import unittest


# your code here
def add(a: int, b: int) -> int:
    return a + b


if __name__ == "__main__":
    print(add(int(sys.argv[1]), int(sys.argv[2])))

# your tests here
class TestCase(unittest.TestCase):
    def test_add(self):
        assert add(1, 2) == 3, "should return the sum of the two numbers"

To run the tests (assuming the code above is in a file named myscript.py):

$ python -m unittest myscript.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK