Testing Python Code
Before we test our code, we need to install the pytest package. This package is a testing framework that makes it easy to write simple tests.
Installing pytest
To install pytest, run the following command in your terminal:
pip install pytestFor future projects and as best practice, you should add dependencies of your Python project into a requirements.txt file:
pytestTo install all dependencies from a requirements.txt file, run:
pip install -r requirements.txtCreating your first test
To write our first test, create a new file calculator_test.py in the root of your project:
touch calculator_test.pyIn this file, we will write a test for the interprete_equation function of the Calculator class:
from calculator import Calculator
def test_interprete_equation(): calculator = Calculator() assert calculator.interprete_equation(["1", "+", "1"]) == [1, "+", 1]We can run this test by executing the following command in your terminal:
pytestYou should see something like this:
vscode ➜ /workspaces/workspace $ pytest======================== test session starts =========================platform linux -- Python 3.10.12, pytest-8.2.1, pluggy-1.5.0rootdir: /workspaces/workspacecollected 1 item
calculator_test.py . [100%]
========================= 1 passed in 0.01s ==========================And with this, we conclude our first test for our Python code. You can run wild and add more tests to your codebase as you see fit.
Next Steps and Hints
Testing cli input
To test the input_equation function, you can use the monkeypatch fixture from pytest to simulate user input: 1
...def test_input_equation(monkeypatch): # monkeypatch the "input" function, so that it returns "1 + 1". # This simulates the user entering "1 + 1" in the terminal: monkeypatch.setattr('builtins.input', lambda _: "1 + 1") calculator = Calculator() assert calculator.input_equation() == ["1", "+", "1"]
...Testing exceptions
Our calculator does not handle division by zero yet and crashes if the user decides to calculate just that. To test this scenario and the operation function, you can use the just learned monkeypatch fixture and the pytest.raises as a context manager to check if the function raises an exception given the faulty input:
...import pytest...def test_operation_invalid_operator(monkeypatch): monkeypatch.setattr('builtins.input', lambda _: "1 / 0") calculator = Calculator() with pytest.raises(ZeroDivisionError): calculator.operation()...If you want, you can fix this issue by yourself and prevent the calculator from crashing, or keep it and sell it as feature if someone asks ;)
Footnotes
-
we learned this ourselves aswell writing this guide, its pretty cool ;) ↩