In short, the basic idea of TDD is to write tests before writing the actual implementation. Maybe the most significant benefit of the approach is that the developer focuses on writing tests which match with what the program should do. Whereas if the tests are written after the actual implementation, there is a high risk for rushing tests which just show green light for the already written logic.
Tests are first class citizens in modern, agile software development, which is why it's important to start thinking TDD early during your Python learning path.
The workflow of TDD can be summarized as follows:
These are the steps required to run pytest inside Jupyter cells.
# Let's make sure pytest and ipython_pytest plugin are installed
import sys
!{sys.executable} -m pip install pytest
!{sys.executable} -m pip install ../../utils/ipython_pytest/
# Let's load ipython_pytest extension which makes it possible to run
# pytest inside notebooks
%load_ext ipython_pytest
Due to technical limitations of Jupyter notebooks and pytest extension, all code that runs inside tests has to be in the same cell. In other words, you can not call e.g. functions that are defined in other cells.
In real applications you have separate directory and files for your tests (see TODO LINK ). The above mentioned limititation is only present for writing tests in Jupyter environment.
pytest test cases¶Pytest test cases are actually quite similar as you have already seen in the exercises. Most of the exercises are structured like pytest test cases by dividing each exercise into three cells:
See the example test case below to see the similarities between the exercises and common structure of test cases.
%%pytest
# Mention this at the top of cells which contain test(s)
# This would be in your e.g. implementation.py
def sum_of_three_numbers(num1, num2, num3):
return num1 + num2 + num3
# This would be in your test_implementation.py
def test_sum_of_three_numbers():
# 1. Setup the variables used in the test
num1 = 2
num2 = 3
num3 = 5
# 2. Call the functionality you want to test
result = sum_of_three_numbers(num1, num2, num3)
# 3. Verify that the outcome is expected
assert result == 10
Now go ahead and change the line assert result == 10 such that the assertion fails to see the output of a failed test.