Sitemap

Python — Test-driven development

6 min readJun 29, 2023

--

Press enter or click to view image in full size

Test-driven development (TDD) is a software development methodology that emphasizes writing tests before writing the actual code. It follows a specific cycle of writing tests, running them, and then writing the code to make the tests pass. TDD promotes a disciplined approach to software development and can lead to more reliable, maintainable, and well-designed code.

Documentation for a Module and a Function

Here’s an example of how you can write documentation for a module and a function, including examples for each:

Documentation for a Module:

"""
my_module.py

This module provides functions for performing basic mathematical operations.

Functions:
- add(x, y): Adds two numbers together.
- multiply(x, y): Multiplies two numbers.
"""

def add(x, y):
"""
Adds two numbers together.

Parameters:
x (int): The first number.
y (int): The second number.

Returns:
int: The sum of x and y.

Example:
>>> add(2, 3)
5
"""
return x + y

def multiply(x, y):
"""
Multiplies two numbers.

Parameters:
x (int): The first number.
y (int): The second number.

Returns:
int: The product of x and y.

Example:
>>> multiply(2, 3)
6
"""
return x * y

In this example, the documentation for the my_module module provides an overview of its purpose and lists the functions it contains. Each function is documented with a docstring, including a description, parameters, return value, and an example demonstrating its usage and expected output.

Documentation for a Function.

def add(x, y):
"""
Adds two numbers together.

Parameters:
x (int): The first number.
y (int): The second number.
Returns:
int: The sum of x and y.

Example:
>>> add(2, 3)
5
>>> add(-2, 5)
3
"""
return x + y

In this example, the documentation for the add function provides a description of its purpose, explains the parameters, specifies the return value, and includes an example showcasing how to use the function and the expected output.

Note that the examples in the documentation are typically written using the >>> prompt to indicate a code example, followed by the function call and the expected output. These examples serve as a clear and concise way to demonstrate the usage and expected behavior of the module or function.

Remember to adapt the documentation style and conventions based on your project’s requirements and any existing documentation standards or guidelines. Consistency and clarity are key when writing documentation to ensure that users can easily understand and utilize your code.

The TDD cycle typically consists of the following steps:

  1. Write a test: Start by writing a test that defines the expected behavior of a specific piece of functionality. This test is often written as a function or method that asserts certain conditions or outcomes.
  2. Run the test: Execute the test to verify that it fails. This is an important step because it ensures that the test is valid and the expected behavior is not already implemented.
  3. Write the code: Implement the minimal amount of code necessary to make the test pass. Focus on solving the specific problem addressed by the test, rather than adding unnecessary functionality.
  4. Run the test again: Execute the test again to check if the code change has successfully made the test pass. If the test fails, iterate and modify the code until the test passes.
  5. Refactor the code: Once the test passes, you can refactor the code to improve its design, structure, or performance while keeping the tests passing. Refactoring ensures that the code remains clean and maintainable.
  6. Repeat the cycle: Move on to the next feature or piece of functionality and repeat the process. Write a new test, run it (which should fail initially), write the code to make it pass, and continue the cycle.

Example to explain step by step

Here’s an example to illustrate the six steps of Test-driven development (TDD) using a simple function that calculates the factorial of a number:

def factorial(n):
"""
Calculates the factorial of a number.

Parameters:
n (int): The input number.

Returns:
int: The factorial of n.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

Step 1: Write a test (test_factorial.py):

def test_factorial():
"""
Test case for the factorial() function.

This test checks if the factorial() function correctly calculates the factorial of a number.

Example:
>>> assert factorial(0) == 1
>>> assert factorial(1) == 1
>>> assert factorial(5) == 120
"""
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(5) == 120

Step 2: Run the test (pytest test_factorial.py):

$ pytest test_factorial.py
============================= test session starts ==============================
...
collected 1 item
test_factorial.py . [100%]
=================== 1 passed in 0.01s ===============================

Step 3: Write the code to make the test pass (factorial.py):

def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

Step 4: Run the test again (pytest test_factorial.py):

$ pytest test_factorial.py
============================= test session starts ==============================
...
collected 1 item
test_factorial.py . [100%]
============================== 1 passed in 0.01s ===============================

Step 5: Refactor the code (No changes required in this example).

Get Muiru Jackson’s stories in your inbox

Join Medium for free to get updates from this writer.

Step 6: Repeat the cycle for additional features or functionality.

By following these six steps, you can iteratively develop and validate your code using tests, ensuring that each new feature is thoroughly tested and functions as expected. This approach helps catch bugs early, improves code quality, and provides a safety net for making changes or refactoring existing code.

By following the TDD approach, developers gain several benefits:

  • Reliability: TDD helps uncover defects or issues early in the development process, allowing them to be fixed before they become larger problems.
  • Design improvement: The focus on writing tests first forces developers to think about the interface and desired behavior of their code. This often leads to more modular, decoupled, and testable designs.
  • Confidence: A comprehensive test suite built through TDD provides developers with confidence in their code. It allows them to make changes or refactor code without fear of introducing regressions.
  • Documentation: Test cases serve as executable documentation that describes the expected behavior of the code. This helps developers understand the codebase and can aid in onboarding new team members.
  • Faster feedback: TDD encourages running tests frequently, providing quick feedback on the correctness of the code. This helps identify issues early, reducing the time and effort spent on debugging.

Python, with its rich ecosystem of testing frameworks like unittest, pytest, and doctest, is well-suited for practicing TDD. These frameworks provide tools and features to support writing and executing tests effectively.

By adopting TDD practices, developers can create higher quality software with better test coverage, improved code design, and increased confidence in the correctness of their code.

The specific option flags for creating tests can vary depending on the testing framework you are using. However, I can provide you with examples of common option flags for two popular testing frameworks: unittest and pytest.

Option flags for unittest:

  1. -v or --verbose: Increases the verbosity of the test output.
python -m unittest -v test_module.py
  1. -f or --failfast: Stops the test execution immediately after the first failure or error.
python -m unittest -f test_module.py
  1. -p PATTERN or --pattern PATTERN: Runs only the tests matching the given pattern.
python -m unittest -p "*test*.py"

Option flags for pytest:

  1. -v or --verbose: Increases the verbosity of the test output.
pytest -v test_module.py
  1. -x or --exitfirst: Stops the test execution immediately after the first failure or error.
pytest -x test_module.py
  1. -k EXPRESSION or --keyword EXPRESSION: Runs only the tests whose names match the given expression
pytest -k "test_function"
  1. -m MARKER or --mark MARKER: Runs tests based on the markers assigned to them.
pytest -m slow
  1. --cov or --coverage: Enables code coverage analysis during test execution.
pytest --cov=my_module test_module.py

Note that these are just a few examples of commonly used option flags. Both unittest and pytest offer a wide range of additional flags and customization options. It's always recommended to consult the documentation of the specific testing framework you are using for a comprehensive list of available option flags and their descriptions.

--

--

Muiru Jackson
Muiru Jackson

Written by Muiru Jackson

I am a Software Engineer with a strong background in CS. I believe in continuous learning & knowledge-sharing to improve software development practices.