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:
def add(a, b):
return a + bNow, 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:
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 fromunittest.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 withtest_.self.assertEqual(add(1, 2), 3): This is an assertion. We are asserting that the result ofadd(1, 2)is equal to3. 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:
python -m unittest tests/test_calculator.pyOr, to discover and run all tests in the tests directory:
python -m unittest discover testsYou 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:
pip install pytestNow, let's rewrite our calculator test using pytest.
tests/test_calculator_pytest.py:
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) == -2Isn't that much cleaner?
- No need to import a testing framework (most of the time).
- No need to create a class.
- Just plain
assertstatements!pytestis 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:
pytestpytest 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:
class Calculator:
def __init__(self):
self.result = 0
def add(self, a, b):
self.result = a + b
return self.resulttests/test_calculator_pytest.py:
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) == 5Here, 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:
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():
> /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:
- Install the Python Extension: Make sure you have the official Python extension from Microsoft installed.
- Set Breakpoints: Click in the gutter to the left of the line numbers to set a breakpoint (a red dot will appear).
- 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:
- Set Breakpoints: Click in the gutter to the left of the line numbers.
- 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 π
- unittest: Official Python Documentation
- pytest: Official pytest Documentation
- pdb: Official Python Documentation
- Debugging in VS Code: Official VS Code Documentation
- Debugging in PyCharm: Official PyCharm Documentation
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:
- Create a test class named
TestDiscountCalculatorthat inherits fromunittest.TestCase. - Instantiate the
DiscountCalculatorclass within your test class so you can call its method. A good place for this is in asetUpmethod. - 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 aValueError.test_excessive_discount_error: Assert that calling the method with a discount percentage greater than 100 (e.g., 101) also raises aValueError.
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, andtest_full_discountshould use an appropriate assertion likeself.assertEqualorself.assertAlmostEqualto compare the expected output with the actual output from theapply_discountmethod. - Methods
test_negative_price_errorandtest_excessive_discount_errormust use theself.assertRaisescontext manager (with self.assertRaises(ValueError):) to verify that the correct exception is raised when invalid arguments are passed to theapply_discountmethod.