Python ModulesPytest TutorialDebugging with pytest

Debugging with pytest

Debugging is an essential part of testing, helping identify and resolve issues efficiently. pytest provides built-in tools and integrations to streamline the debugging process.


Using --pdb for Interactive Debugging

pytest includes an option to drop into the Python Debugger (pdb) upon encountering a test failure.

Example: Using --pdb

Run pytest with the --pdb flag:

pytest --pdb

When a test fails, pytest will open an interactive pdb session, allowing you to inspect variables and the execution flow.

pdb Commands

CommandDescription
lList source code around the current line.
nExecute the next line of code.
cContinue execution until the next breakpoint.
qQuit the debugger.

Debugging Assertions

pytest enhances assertion errors by providing detailed introspection of values. This can help identify mismatches quickly.

Example: Enhanced Assertions

def test_sum():
    assert 1 + 1 == 3

Output:

E       assert 2 == 3

This shows the actual and expected values, making it easier to pinpoint the issue.


Using Breakpoints in Code

You can insert breakpoints directly into your test code for debugging.

Example: Adding a Breakpoint

def test_debug():
    x = 10
    breakpoint()  # Pauses execution here
    assert x == 20

Run the test, and execution will pause at the breakpoint() line.


Debugging with Third-Party Tools

pytest integrates well with external debugging tools for advanced scenarios.

Using ipdb

ipdb is an enhanced version of pdb with tab-completion and better usability.

  1. Install ipdb:
    pip install ipdb
  2. Use ipdb.set_trace() in your code:
    import ipdb
     
    def test_with_ipdb():
        x = 10
        ipdb.set_trace()
        assert x == 20

Debugging in IDEs

  • Most modern IDEs like PyCharm, VS Code, and Jupyter Notebook support debugging pytest tests with visual debuggers.

Debugging Tips and Best Practices

  • Run Specific Tests: Focus on a single failing test to reduce noise.

    pytest test_module.py::test_function
  • Verbose Output: Use -v for detailed output during test runs.

    pytest -v
  • Disable Capturing: Prevent pytest from capturing standard output for easier debugging.

    pytest -s
  • Use Logs: Add logging to your tests for additional context.

    import logging
     
    logging.basicConfig(level=logging.DEBUG)
     
    def test_with_logging():
        logging.debug("Debugging test case.")
        assert True

Debugging with pytest is a powerful way to quickly identify and resolve issues in your tests. By combining pytest’s built-in features with external tools, you can streamline your development and testing workflows.