Practical guide to Python's Doctest
Introduction to Doctest
What is doctest?
Let's first start with an example:
def add(a:int, b:int) -> int:
"""
returns the sum of two given numbers.
Examples:
>>> add(2, 3)
5
>>> add(-1, 1)
0
"""
return a + b
So, what is it afterall?
doctest is a Python module that allows you to test code snippets embedded in the docstrings of your functions, classes, or modules. It serves as both a testing tool and documentation enhancer, making it easier to ensure that your examples in the documentation are accurate, functional and not less important up-to-date.
The doctest module executes the code examples in your docstrings and compares the output with the expected results, resulting either in success or failure.
Executing doctest
Before going any further, let's see how to execute these tests
# From the command line
$ python -m doctest -v python_file.py
within Python
import doctest
doctest.testmod()
Why Use doctest?
doctest is particularly useful when you want to:
- Ensure accuracy in documentation: By verifying that examples in your docstrings work as intended, you make your documentation more reliable.
- Simplify testing: It’s easy to write and maintain because the tests are embedded directly in the code they’re validating.
- Provide clear examples: Your users get tested examples to follow, improving their understanding of your code.
When to Use doctest?
- For simple functions or modules: doctest shines when your code is straightforward and doesn’t require extensive setup.
- As lightweight testing: It complements more comprehensive testing frameworks like unittest or pytest but doesn’t replace them.
- To encourage documentation: Developers who use doctest tend to write better documentation because the examples must be valid.
Benefits of doctest
- Dual-purpose docstrings: Combine documentation and testing in one place.
- Ease of use: Minimal setup is required, as it’s a built-in Python module.
- Early error detection: Catch issues in your code or documentation as you write them.
- Improved readability: docstring examples serve as live demonstrations of how the code works.
With doctest, you can ensure your code and documentation are always in sync, offering a seamless experience for both developers and end users.
How to Write Doctests
Basic Structure of a Doctest
As we've seen, a doctest is embedded directly into a function, class, or module’s docstring. The structure mimics an interactive Python shell session, using >>> to indicate input and showing the expected output immediately below.
Let’s review the initial example:
def add(a:int, b:int) -> int:
"""
returns the sum of two given numbers.
Examples:
>>> add(2, 3)
5
>>> add(-1, 1)
0
"""
return a + b
Formatting Rules
- Start with >>>: Each line of code starts with the >>> prompt to indicate an input command.
- Match expected output: The expected result should appear exactly as Python would output it.
- Use ellipsis (...): For multiline statements or to skip irrelevant parts of long outputs.
def greet(name: str) -> str:
"""
Greets a user with their name.
Examples:
>>> greet('Alice')
'Hello, Alice!'
>>> greet('Bob')
'Hello, Bob!'
"""
return f"Hello, {name}!"
Writing Doctests for Different Scenarios
- Simple Function Outputs: Use doctestto verify straightforward return values.
def square(n: int) -> int:
"""
Returns the square of a number.
Examples:
>>> square(4)
16
>>> square(-3)
9
"""
return n * n
- Edge Cases: Include boundary conditions or uncommon inputs.
def divide(a, b):
"""
Divides two numbers.
Examples:
>>> divide(10, 2)
5.0
>>> divide(5, 0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
"""
return a / b
- Multiline Outputs
def print_table(rows: int, cols: int) -> str:
"""
Generates a string representation of a table with given rows and columns.
Examples:
>>> print_table(2, 3)
'1\t2\t3\n4\t5\t6'
>>> print_table(3, 2)
'1\t2\n3\t4\n5\t6'
"""
return '\n'.join(
'\t'.join(str(i + j * cols + 1) for i in range(cols))
for j in range(rows)
)
- Ellipses for Partial Matching if the output is too large to simplify:
def generate_large_list(n: int) -> list[int]:
"""
Returns a large list of numbers from 0 to n-1.
Examples:
>>> generate_large_list(100) # doctest: +ELLIPSIS
[0, 1, 2, ..., 98, 99]
"""
return list(range(n))
Common Doctest Patterns
- Testing for Exceptions: Demonstrate how errors are raised.
def reciprocal(n: int) -> float:
"""
Returns the reciprocal of a number.
Examples:
>>> reciprocal(2)
0.5
>>> reciprocal(0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
"""
return 1 / n
- Strings with Special Characters: Ensure outputs match exactly, including quotes.
When dealing with strings in doctests, special characters like quotation marks (', ") or escape sequences (e.g., \n, \t) can sometimes cause confusion or mismatches between the expected and actual outputs.
Matching Quotation Marks
Python can represent strings using either single quotes (') or double quotes ("). However, the output in doctests must match exactly how Python formats the string.
Example: If the function returns a string enclosed in single quotes, your expected output in the doctest must also use single quotes:
def wrap_in_quotes(text: str) -> str:
"""
Wraps a string in single quotes.
Examples:
>>> wrap_in_quotes("hello")
"'hello'"
"""
return f"'{text}'"
Escape Sequences
Escape sequences like \n (newline) or \t (tab) must be written explicitly in the doctest and match Python’s exact representation in the output.
def add_newline(text: str) -> str:
"""
Adds a newline character at the end of the string.
Examples:
>>> add_newline("hello")
'hello\\n'
"""
return f"{text}\n"
Notice that the expected output uses double backslashes (\n) because a single backslash is interpreted as part of the string in the doctest. This is how Python represents escape sequences in strings.
Handling Strings with Mixed Quotes
When strings contain both single and double quotes, Python may switch the default quotation marks to avoid escaping. Your doctest must reflect this behavior.
def greet(name: str) -> str:
"""
Returns a greeting with a name enclosed in quotes.
Examples:
>>> greet('Alice')
'"Alice"'
>>> greet("O'Reilly")
'"O\'Reilly"'
"""
return f'"{name}"'
In the second example, the function wraps the string in double quotes to avoid escaping the single quote in O'Reilly.
- Complex Data Types: Use doctests to validate dictionaries, lists, or custom objects.
def reverse_dict(d: dict) -> dict:
"""
Reverses keys and values in a dictionary.
Examples:
>>> reverse_dict({'a': 1, 'b': 2})
{1: 'a', 2: 'b'}
>>> reverse_dict({})
{}
"""
return {v: k for k, v in d.items()}
Tips for Writing Effective Doctests
- Be precise: Ensure outputs are exactly what Python produces.
- Use realistic examples: Write examples that reflect real-world use cases.
- Include edge cases: Handle unusual inputs and exceptions.
- Keep it simple: Avoid overly complex examples that may confuse readers.
By adhering to these guidelines, you can create clear, maintainable doctests that serve both as tests and as valuable documentation.
Integration with Other Testing Frameworks
Using doctest Alongside unittest
doctest can be seamlessly integrated with the unittest framework to combine lightweight documentation-based testing with more comprehensive test cases. This approach allows you to leverage the simplicity of doctest for verifying examples while using unittest for complex scenarios requiring detailed setup and teardown logic.
Example: Running Doctests with unittest
You can create a unittest.TestSuite that includes your doctests:
import doctest
import unittest
from my_module import some_function
class TestMyModule(unittest.TestCase):
# Regular unittest case
def test_add(self):
self.assertEqual(some_function(2, 3), 5)
if __name__ == "__main__":
# Add doctests to the test suite
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(some_function.__module__))
# Run all tests, including doctests
runner = unittest.TextTestRunner()
runner.run(suite)
Using pytest with doctest
pytest natively supports doctest, allowing you to run doctests alongside your regular test files without additional configuration.
How to Run Doctests with pytest
Simply run pytest with the --doctest-modules flag to include all doctests in your project:
$ pytest --doctest-modules
Example: Combining Doctests and Pytest
Here’s a file (example.py) containing both doctests and pytest tests:
def multiply(a, b):
"""
Multiplies two numbers.
Examples:
>>> multiply(3, 4)
12
>>> multiply(5, -2)
-10
"""
return a * b
def test_multiply():
assert multiply(3, 3) == 9
assert multiply(0, 5) == 0
When running pytest --doctest-modules, it will execute both the doctests and the standard pytest test cases.
Combining Doctests and Continuous Integration (CI)
Doctests can easily be included in your CI pipelines alongside other tests. For example:
- Use a tool like GitHub Actions, Travis CI, or Jenkins to automate your testing process.
- Include doctests as part of your overall test command, e.g.:
$ pytest --doctest-modules
Advantages of Integration
- Unified Workflow: Run all tests (doctests, unittest, pytest) in a single command.
- Comprehensive Coverage: Use doctests for quick validations and unittest/pytest for complex scenarios.
- Improved Documentation: Verified examples enhance the quality and reliability of your documentation.
By integrating doctest with other testing frameworks, you can achieve a robust testing strategy that balances simplicity and thoroughness.
Mocking within Doctest
doctest does not have built-in support for using mocks, as it is designed to execute and validate examples directly from docstrings in a lightweight manner.
However, you can still incorporate mocks in doctests by manually creating them or by using mocking libraries like unittest.mock. The key is to define the mock object in the example itself so that doctest can execute it as part of the code snippet.
def fetch_data_from_api():
"""
Fetch data from an API.
Examples:
>>> from unittest.mock import MagicMock
>>> fetch_data = MagicMock(return_value={"id": 1, "name": "Mocked Data"})
>>> fetch_data()
{'id': 1, 'name': 'Mocked Data'}
"""
# Normally, this would fetch data from an API
pass
- Keep Mocks Simple: If you must use mocks in doctests, keep them minimal and easy to understand, as Mocking often involves additional setup, which can make the doctest harder to read and understand, defeating its purpose as documentation.
- Limit Use Cases: Use mocks sparingly in doctests. Reserve them for cases where including them significantly improves documentation or clarifies behavior.
Common Problems
Whitespace and Formatting Issues
- Problem: Differences in whitespace (like extra spaces or missing newlines) between the expected and actual output cause test failures.
- Solution: Use the
+NORMALIZE_WHITESPACEoption to ignore these differences.
def greet(name):
"""
Greet a user with their name.
Examples:
>>> greet("Alice") # doctest: +NORMALIZE_WHITESPACE
'Hello, Alice!'
"""
return f" Hello, {name}! "
Floating-Point Precision
- Problem: Minor differences in floating-point calculations can lead to test failures.
- Solution: Use the
+ELLIPSISoption to match approximate outputs.
def divide(a, b):
"""
Divide two numbers.
Examples:
>>> divide(10, 3) # doctest: +ELLIPSIS
3.333...
"""
return a / b
Multiline Output
- Problem: Large or multiline outputs can be cumbersome to match exactly.
- Solution: Use ellipses (...) to skip parts of the output you don’t need to verify.
def get_data():
"""
Fetch a data sample.
Examples:
>>> get_data() # doctest: +ELLIPSIS
{'id': 1, 'name': 'Sample', 'details': ...}
"""
return {'id': 1, 'name': 'Sample', 'details': {'key': 'value'}}
Unexpected Tracebacks
- Problem: Differences in traceback formatting or missing lines can cause errors.
- Solution: Use ... to match only the parts of the traceback that matter.
def raise_error():
"""
Raises an exception.
Examples:
>>> raise_error()
Traceback (most recent call last):
...
ValueError: An error occurred!
"""
raise ValueError("An error occurred!")
Environment Differences
- Problem: Output might vary across platforms or Python versions (e.g., dictionary key orders).
- Solution: Write tests that are resilient to such variations by focusing only on what’s essential. Use sorted() for dictionaries if order matters.
Conclusion and Next Steps
Conclusion
doctest is a simple yet powerful tool that bridges the gap between documentation and testing. By embedding executable examples in your code’s docstrings, you ensure that your documentation remains accurate, reliable, and practical. It’s particularly well-suited for lightweight testing and enhancing the usability of your code.
Key Takeaways
- doctest promotes good documentation practices by enforcing accuracy.
- It’s an excellent choice for verifying small, self-contained functions or modules.
- While not a replacement for full-fledged testing frameworks, doctest works effectively in tandem with them.
Next Steps
Practice Writing Doctests:
- Start by adding doctestto simple functions in your existing projects.
- Gradually incorporate them into more complex modules.
- Explore options like +NORMALIZE_WHITESPACE and +ELLIPSIS to handle edge cases.
- Experiment with integrating doctest into larger test suites.
Expand Your Testing Toolkit:
- Combine doctest with tools like unittest or pytest for comprehensive coverage.
Contribute to Open Source:
- Many open-source projects welcome contributions that include improved documentation and doctests.
By mastering doctest, you’ll enhance both your code quality and your ability to write clear, maintainable documentation.