Test-driven development (TDD)
Test-Driven Development (TDD) in the Python programming language is a Python-based software source code development method in which tests are created before the actual Python program source code.

Instead of creating a complete program in Python first and then testing it, TDD follows a short Python cycle.
First write tests → Run the tests → Write the program source code → Now run your tests → Modify the existing source code
TDD in Python is commonly used with popular Python testing tools like UnitTest and PyTest.
What is TDD in the Python programming language?
TDD in the Python programming language stands for Test-Driven Development, a software development testing tool or concept.
The main purpose of TDD is.
Test-driven development helps us guide the development of source code by identifying the expected behavior of a program.
For example, suppose we need a function in a Python program that adds two integers.
Instead of writing it directly.
def plus(p, q):
return p + q
we first create a test that indicates what we expect.
def test_plus():
assert plus(4, 7) == 11
Initially, this test fails because the plus() function is not implemented.
We then create the minimum source code required to pass this test.
A TDD cycle representation in Python programming.
TDD, a Python-based test-driven development (TDD), consists of three main stages, which we will explore in detail below.
┌───────────────┐
│ RED │
│ Here you write a new source code test │
└──────┬──────┘
↓
┌─────────────┐
│ GREEN │
│ Now pass the test you wrote in │
└────────┬───────┘
↓
┌────────────┐
│ Refactor │
│ Now modify the source code as needed │
└──────┬──────┘
↓
Now repeat all of this.
These stages are called in Test-Driven Development (TDD).
- Red Test Stage
- Green Test Stage
- Refactor Test Stage
Step 1 – Red Light TDD Stage.
First, the Python user writes a source code test for their desired behavior.
Let’s say we need a function called plus().
def test_plus():
assert plus(4, 5) == 9
If we run this test now, it fails because the plus() function is missing.
This is the red stage.
Source code written test
↓
If the test fails
↓
RED stage
The red stage test has a chance of failure because we haven’t written an implementation yet.
Step 2 – Green Light TDD Stage.
Now the Python user writes a simple program source code test that will easily pass.
def plus(p, q):
return p + q
Now run this test again.
Test → PASS
This is the green stage in Python source code TDD.
Your goal in this testing stage isn’t to write perfect test code. Our goal here is simply to satisfy the test.
Step 3 – Refactor TDD Stage.
Here, after the test passes in the TDD stage, we improve the program source code without changing its behavior.
For example, we might improve the organization, naming, or structure of the source code. Then, after refactoring, run the test again.
Refactor
↓
Run the test
↓
Pass
This is the refactor stage in the TDD testing phase.
Complete the TDD cycle in the Python test stage.
A complete TDD testing process in a Python program looks something like this.
First, write a failing test.
↓
RED TDD Stage🔴
↓
Write minimal program source code.
↓
GREEN TDD Stage🟢
↓
Improve your source code.
↓
REFACTOR TDD Stage🔵
↓
Now run your test again.
↓
Refactor it again.
This TDD cycle is often referred to as the Red-Green-Refactor test stage.
Example of TDD using pytest in Python programming.
Let’s say we want to create a Python program function that checks whether a number is even or not.
Step 1: First, write a test
def test_is_even_num():
assert is_even_num(8) is True
Initially, this test fails because the is_even_num() function doesn’t exist.
Step 2: Write your source code
def is_even_num(number):
return number % 2 == 0
Now, with this condition, this test should pass.
Step 3: Add more tests
def test_is_even_num():
assert is_even_num(8) is True
def test_is_odd_num():
assert is_even_num(7) is False
def test_zero_is_even_num():
assert is_even_num(0) is True
Now run it in Python.
pytest
Now, let’s verify the test in this program that the function works in several cases.
Example of TDD using Python unittests.
Python users can also apply this idea using Python’s built-in unittest module.
import unittest
def is_even_num(number):
return number % 2 == 0
class TestEvenNum(unittest.TestCase):
def test_even_num(self):
self.assertTrue(is_even_num(8))
def test_odd_num(self):
self.assertFalse(is_even_num(7))
def test_zero(self):
self.assertTrue(is_even_num(0))
if __name__ == “__main__”:
unittest.main()
Now run it using.
python -m unittest
Advantages of the TDD testing stage in Python.
- Fewer bugs – Because tests are continuously created in Python TDD, it can be used to find issues and problems immediately.
- Better Code Design – Python TDD forces software developers to create small functions and clear interfaces, making it easier to test.
- Immediate Feedback – This lets Python software developers know immediately whether a new change they’ve made is working properly.
- Safer Refactoring – Tests provide a safety net when improving or restructuring existing Python program source code.
- Living Documentation – Program source tests created in the proper order show how a function or component in an existing program is expected to work.
- Easy Maintenance – When Python developers’ needs change, software developers can modify tests and then update their implementation.
Disadvantages of the TDD Testing Stage in Python.
TDD testing in Python programs also has some challenges or drawbacks.
- Time-consuming initially – Creating tests before implementation in Python TDD can initially be a slow and time-consuming task.
- Requires practice – In Python TDD, software developers must learn how to create focused tests that only meet the necessary requirements.
- Bad tests can be misleading – If tests in Python TDD are poorly designed or poorly developed, passing the program source code tests does not mean that your entire application is in order.
- Not everything is easy to test – Some user-interface behaviors, complex integrations, and external systems in Python TDD may require testing techniques other than unit-level TDD.
Python TDD vs. Traditional Development.
Traditional Source Code Testing Approach
First write the program source code
↓
And write other code logic statements
↓
Complete the program
↓
Test the program
↓
Fix program bugs
TDD testing approach in Python programming.
First write the Python program source code test
↓
If the test fails
↓
Write the program code
↓
Test passes
↓
Refactor
↓
Write the next test
↓
Refactor it
Python TDD vs. The main difference from traditional development is that TDD uses tests to guide test implementation from the start, rather than considering source code testing a task that is performed only after development.
TDD and Unit Testing Concepts in Python.
TDD and Unit Testing are very similar concepts or methods, but both concepts operate in their own ways.
Unit Python Testing.
Unit testing in Python programming is a testing technique or method used to test or analyze individual units of program source code.
TDD Python Testing.
TDD is a development method or concept in Python programming in which tests are created before program implementation, and program tests are used to guide development. For example,
Unit Testing
↓
This Python program tests different parts of the source code.
TDD Testing
↓
This Python program uses this test to run the source code development process.
Python users can create unit tests without practicing TDD testing.
Best Practices for TDD Testing in Python.
This keeps your Python source code tests small.
Each program source code test should focus on a single behavior.
Always use clear TDD test names.
For example.
def test_zero_is_even():
…
This is easier for you to understand.
def test1():
…
Python TDD test edge cases.
For example.
0
Negative number
Empty input
Large value
Invalid input
First, write minimal code in your source code tests.
During green stage testing, avoid over-engineering or over-customizing your implementation.
Regularly refactor it as needed.
After Python TDD testing passes, improve your existing source code while still maintaining the passing test.
Real-world TDD source code testing example in Python.
Let’s assume we’re developing a bank account application.
We need a function to allow a client to withdraw money from their bank account.
First, we define its expected behavior with a test.
def test_withdraw_amt():
client_account = Account(1000)
client_account.withdraw_amt(332)
assert account.balance == 668
Initially, the program source code test fails because it doesn’t implement the user Account or the withdraw_amt() function code.
Next, we implement the minimal source code functionality.
class Account:
def __init__(self, balance):
self.balance = balance
def withdrawal(self, amount):
self.balance -= amount
Then run the source code test again.
PASS
Next, we can add another program source code requirement.
def test_cannot_withdraw_more_than_balance():
account = Account(1000)
# Source code Expected behavior will be defined here.
We then implement that behavior, and continue the Red → Green → Refactor tdd testing stage cycle.
TDD testing concepts in a Python-based project.
A Test-Driven Development (TDD) project in the Python programming language can be organized or structured like this:
testproject/
│
├── calculation.py
│
└── tests/
└── test_calculation.py
Python source code development happens in short cycles.
User source code requirement
↓
Write a failing test first
↓
Implement the required feature
↓
Run the test
↓
Refactor
↓
Check the next requirement
Conclusion of Python Test-driven development (TDD).
Test-driven development (TDD) in the Python programming language is a program source code software development method or concept in which tests are created before implementation code.
The basic Test-driven development (TDD) cycle is.
- 🔴 RED → In this, you write a test that fails.
- 🟢 GREEN → In this, you write enough program source code to pass.
- 🔵 REFACTOR → In this, you improve your program source code by making it pass the test.
TDD helps Python software developers create properly tested, maintainable, and reliable programs. In Python programming, this can be practiced using popular advanced source code testing frameworks like unittest and pytest.
An easy formula to remember in Python programming is.
TDD = Test the source code first → Update the code → Apply refactoring → Repeat as needed

