Test-Driven Development (TDD) in Python#
Test-Driven Development (TDD) is a software development process that relies on the repetition of a very short development cycle:
Write a test that fails
Write the minimal code to make it pass
Refactor if necessary
“Make incremental changes.” → TDD is an incremental process. Commit often.
This tutorial walks you through a simple example using a Line
class.
Step 1: Write the Failing Test#
Create a file called test_line.py
:
# test_line.py
from line import Line
def test_length():
line = Line(0, 0, 3, 4)
assertEqual(line.length(), 5)
This test assumes that the Line
class and a length()
method exist and that it calculates the distance between (0,0) and (3,4), which is 5.
At this point, the test will fail because we haven’t written line.py
.
Step 2: Make the Test Pass#
Now create line.py
:
# line.py
import math
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def length(self):
dx = self.x2 - self.x1
dy = self.y2 - self.y1
return math.sqrt(dx**2 + dy**2)
Now, run the test again:
python test_line.py
The test should now pass.
Step 3: Refactor#
Now that your test passes, you can safely refactor the code. For example, you might want to rename the length()
method to get_length()
. Pycharm has a built-in refactor function that helps you with this. Right-click on the method name and select Refactor
–> Rename
. Type in the new name for the method. Note that Pycharm automatically changes the name everywhere it occurs.
Make sure to run tests after each change to verify correctness.
Summary#
TDD helps you:
Define clear goals before you start coding
Prevent overengineering
Catch bugs early
Write better structured and testable code
Happy testing!