Introduction to Test-Driven Development (TDD) in Python

Test-Driven Development (TDD) is a software development methodology that involves writing tests before implementing the code. This approach helps ensure that the code is reliable, maintainable, and well-designed.

Stages of TDD

  1. Write a failing test: the test describes an expected behavior.
  2. Write the minimal code to make it pass: basic implementation to pass the test.
  3. Refactoring: improve the code structure while keeping tests green.

Tools in Python

In Python, the unittest module is included in the standard library. Other popular tools include pytest and nose2.

Practical example with unittest

Suppose we want to create a function that adds two numbers.

1. Write the test

import unittest

from calculator import add

class TestCalculator(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

if __name__ == '__main__':
    unittest.main()

2. Implement the function

# calculator.py
def add(a, b):
    return a + b

3. Refactoring (if necessary)

In our case, the function is already simple and readable, so no refactoring is needed.

Advantages of TDD

  • Greater code reliability
  • Ease of refactoring and maintenance
  • Behavior-driven design

Conclusion

TDD is a powerful practice that can significantly improve software quality. Although it requires discipline and a shift in mindset, the long-term benefits are clear.

Back to top