Learn Python Β· 15/15

Testing and Debugging

9 min read

Testing and Debugging in Python 🐍

Welcome, aspiring Pythonista! You've learned to write some code, and that's fantastic. But how do you know your code works as expected? And what do you do when it inevitably breaks? This guide will walk you through the essential practices of testing and debugging your Python code.


1. The Importance of Testing Your Code πŸ§ͺ

The Problem: You've written a brilliant piece of code. It works perfectly on your machine with the inputs you've tried. But what happens when someone else uses it with unexpected data? Or when a new feature accidentally breaks an old one? Without a safety net, your brilliant code can become a source of frustration and bugs.

The Solution: Testing. Software testing is the process of evaluating a software item to detect differences between given input and expected output. It's like having a meticulous inspector who checks every part of your creation to ensure it's up to standard.

Why is it a big deal?

  • Saves Money: Finding and fixing bugs early in the development process is significantly cheaper than fixing them after the software is released.
  • Builds Confidence: A comprehensive suite of tests gives you the confidence to make changes and add new features without worrying about breaking existing functionality.
  • Improves Code Quality: Writing tests often forces you to think more clearly about your code's design and functionality, leading to better-structured and more maintainable code.
  • Enhances User Satisfaction: Delivering a product with fewer bugs leads to happier users and a better reputation for you and your team.

Real-world consequences of not testing:

  • Ariane 5 Rocket Explosion (1996): A software bug in the rocket's guidance system caused it to self-destruct 37 seconds after launch, resulting in a loss of $370 million. The error was a data conversion issue that went undetected.
  • Boeing 737 MAX Crashes (2018 & 2019): Faulty software in the Maneuvering Characteristics Augmentation System (MCAS) was a major contributing factor in two crashes that tragically killed 346 people.
  • UK Post Office Scandal: A faulty accounting software called Horizon led to the wrongful conviction of hundreds of sub-postmasters for theft and false accounting.

These examples, though extreme, highlight the critical importance of thorough testing. Now, let's get our hands dirty and learn how to write some tests!


2. Writing Unit Tests with the unittest Framework πŸ”¬

The Problem: You want to test individual pieces of your code, like functions or methods, in isolation to ensure they work correctly. This is called unit testing.

The Solution: The unittest framework. Python comes with a built-in module called unittest that provides a solid foundation for writing and running unit tests. It's inspired by the popular JUnit framework from the Java world.

Getting Started with unittest

Let's imagine we have a simple module with a function to add two numbers.

calculator.py:

python
def add(a, b):
    return a + b

Now, let's write a test for this function. By convention, test files are often placed in a tests directory and have names that start with test_.

tests/test_calculator.py:

python
import unittest
from calculator import add

class TestCalculator(unittest.TestCase):

    def test_add_integers(self):
        self.assertEqual(add(1, 2), 3)

    def test_add_floats(self):
        self.assertEqual(add(1.5, 2.5), 4.0)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -1), -2)

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

Breaking it down:

  • import unittest: We import the necessary module.
  • from calculator import add: We import the function we want to test.
  • class TestCalculator(unittest.TestCase):: We create a test class that inherits from unittest.TestCase. This is the standard way to group related tests.
  • def test_add_integers(self):: Each test is a method within the class, and its name must start with test_.
  • self.assertEqual(add(1, 2), 3): This is an assertion. We are asserting that the result of add(1, 2) is equal to 3. If the assertion is true, the test passes. If it's false, the test fails.

Common unittest Assertions:

Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIn(a, b) a is in b
assertRaises(exc, callable, *args, **kwds) callable(*args, **kwds) raises exc

Running the tests:

You can run the tests directly from the command line:

bash
python -m unittest tests/test_calculator.py

Or, to discover and run all tests in the tests directory:

bash
python -m unittest discover tests

You should see an output indicating that your tests ran and passed.

A Funny Exaggeration: Imagine your code is a stand-up comedian. The unittest framework is the toughest audience member, the one who doesn't laugh unless the joke is perfectly delivered. If your code can make unittest "laugh" (i.e., pass the tests), you know you've got some good material.


3. Introduction to pytest πŸš€

The Problem: While unittest is powerful, some developers find its syntax a bit verbose. They want a simpler, more "Pythonic" way to write tests.

The Solution: pytest. pytest is a popular third-party testing framework that has become the de facto standard for many Python developers. It allows you to write tests with less boilerplate code and offers powerful features like fixtures and a rich ecosystem of plugins.

Getting Started with pytest

First, you need to install it:

bash
pip install pytest

Now, let's rewrite our calculator test using pytest.

tests/test_calculator_pytest.py:

python
from calculator import add

def test_add_integers():
    assert add(1, 2) == 3

def test_add_floats():
    assert add(1.5, 2.5) == 4.0

def test_add_negative_numbers():
    assert add(-1, -1) == -2

Isn't that much cleaner?

  • No need to import a testing framework (most of the time).
  • No need to create a class.
  • Just plain assert statements! pytest is smart enough to inspect the assertion and provide detailed output on failure.

Running pytest:

Navigate to your project's root directory in the terminal and simply run:

bash
pytest

pytest will automatically discover and run all files named test_*.py or *_test.py and execute functions prefixed with test_.

A Key pytest Feature: Fixtures

Fixtures are functions that provide a fixed baseline for your tests. They are great for setting up resources that your tests need, like a database connection or a temporary file.

Let's imagine a more complex scenario where we have a Calculator class.

calculator.py:

python
class Calculator:
    def __init__(self):
        self.result = 0

    def add(self, a, b):
        self.result = a + b
        return self.result

tests/test_calculator_pytest.py:

python
import pytest
from calculator import Calculator

@pytest.fixture
def calculator_instance():
    """Returns a Calculator instance"""
    return Calculator()

def test_add(calculator_instance):
    assert calculator_instance.add(2, 3) == 5

Here, calculator_instance is a fixture that creates a Calculator object. By passing it as an argument to our test function, pytest automatically provides the object. This is a simple example, but fixtures can be incredibly powerful for managing complex test setups.


4. Debugging Python Code (pdb and IDE tools) 🐞

The Problem: Your code isn't working as expected. You've stared at it for hours, but you can't see the problem. print() statements are getting you nowhere. You need a way to peer into your code's execution, line by line, to see what's really going on.

The Solution: A Debugger. A debugger is a tool that allows you to pause the execution of your program at specific points, inspect the values of variables, and step through the code line by line.

The Python Debugger (pdb)

Python comes with a built-in debugger called pdb. It's a command-line tool, which makes it incredibly versatile, especially when working on remote servers.

Getting Started with pdb

You can start the debugger in a few ways. A common method is to insert breakpoint() (for Python 3.7+) or import pdb; pdb.set_trace() (for older versions) into your code where you want to pause execution.

buggy_code.py:

python
def buggy_function(x, y):
    result = x + y
    breakpoint()  # Execution will pause here
    final_result = result * 2
    return final_result

buggy_function(3, "4")

When you run this script, you'll be dropped into the pdb interactive session at the point of the breakpoint():

livescript
> /path/to/your/buggy_code.py(4)buggy_function()
-> final_result = result * 2
(Pdb)

Common pdb Commands:

Command Description
n (next) Execute the current line and go to the next line in the current function.
s (step) Step into a function call.
c (continue) Continue execution until the next breakpoint.
l (list) Show the source code around the current line.
p <variable> Print the value of a variable.
q (quit) Quit the debugger and terminate the program.
h (help) Get help on pdb commands.

In our example, if you type p result, you'll see the value of the result variable. This allows you to inspect the state of your program at that exact moment.

IDE Debugging Tools

Most modern Integrated Development Environments (IDEs) like VS Code and PyCharm have powerful graphical debuggers that are built on top of pdb or similar tools.

Debugging in VS Code:

  1. Install the Python Extension: Make sure you have the official Python extension from Microsoft installed.
  2. Set Breakpoints: Click in the gutter to the left of the line numbers to set a breakpoint (a red dot will appear).
  3. Start Debugging: Go to the "Run and Debug" view on the sidebar and click the green "Run and Debug" button, selecting the appropriate configuration (e.g., "Python File").

Debugging in PyCharm:

  1. Set Breakpoints: Click in the gutter to the left of the line numbers.
  2. Start Debugging: Right-click in the editor and select "Debug 'your_script_name'".

IDE debuggers provide a user-friendly interface with features like:

  • Variable Explorer: See the values of all variables in the current scope.
  • Call Stack: See the sequence of function calls that led to the current point.
  • Watch Window: Monitor specific expressions as you step through the code.
  • Debug Console: An interactive console where you can execute code in the current context.

A Real-Life Analogy for Debugging: Imagine you're a detective at a crime scene. A debugger is like having the ability to rewind time and watch the events unfold in slow motion. You can pause at any moment, examine the evidence (variables), and see exactly where things went wrong.


Further Reading πŸ“š

Challenge

Challenge: Write a Unit Test Suite

You are given a Python class DiscountCalculator with a single method, apply_discount. This method calculates the final price after applying a discount but also includes validation to handle invalid inputs.

Your task is to write a comprehensive test suite for the apply_discount method using Python's built-in unittest framework.

Requirements:

  1. Create a test class named TestDiscountCalculator that inherits from unittest.TestCase.
  2. Instantiate the DiscountCalculator class within your test class so you can call its method. A good place for this is in a setUp method.
  3. Implement the following five test cases as methods within your test class:
    • test_standard_discount: Verify that a 20% discount on a price of 150.0 correctly results in 120.0.
    • test_zero_discount: Verify that a 0% discount on a price of 99.99 correctly results in 99.99.
    • test_full_discount: Verify that a 100% discount on a price of 500.0 correctly results in 0.0.
    • test_negative_price_error: Assert that calling the method with a negative price (e.g., -10) raises a ValueError.
    • test_excessive_discount_error: Assert that calling the method with a discount percentage greater than 100 (e.g., 101) also raises a ValueError.

Use the appropriate assertion methods from unittest.TestCase for each scenario.

Expected result

Your solution should be a complete Python class TestDiscountCalculator that inherits from unittest.TestCase.

The class should contain five test methods, all correctly named with the test_ prefix.

  • Methods test_standard_discount, test_zero_discount, and test_full_discount should use an appropriate assertion like self.assertEqual or self.assertAlmostEqual to compare the expected output with the actual output from the apply_discount method.
  • Methods test_negative_price_error and test_excessive_discount_error must use the self.assertRaises context manager (with self.assertRaises(ValueError):) to verify that the correct exception is raised when invalid arguments are passed to the apply_discount method.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.