🐍 Python Tutorial: Testing and Debugging
Writing error-free and reliable Python code requires strong testing and debugging practices. In this tutorial, we cover core debugging techniques, how to write effective unit tests using Python's built-in unittest module, and explore tools to help you develop clean, bug-free programs.
1. Debugging Python Code
Debugging involves identifying and fixing issues in your code. Common debugging techniques include:
- Print Statements: Add
print()to trace values and logic. - Using
pdb: Python's built-in debugger allows you to set breakpoints and inspect variables interactively.
import pdb
def divide(a, b):
pdb.set_trace()
return a / b
print(divide(10, 2))2. Unit Testing with unittest
Python's unittest framework helps you write tests for individual units of your code (functions, classes). A simple test looks like this:
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()🔧 Run the test with: python test_file.py
3. Popular Testing Tools
While unittest is built-in, Python has a rich ecosystem of third-party testing tools:
pytest– simple, powerful, and widely useddoctest– test your docstrings as documentation + testscoverage– measure how much of your code is tested
Example with pytest:
# test_math.py
def add(x, y):
return x + y
def test_add():
assert add(2, 3) == 5Run with pytest test_math.py