Writing Tests
- Unittest: A built-in Python framework for writing tests.
- pytest: A more advanced testing framework that offers advanced features and plugins.
Running Tests
python -m unittest discover
or pytest
- Running tests should identify errors and failures.
Using Debugger
- pdb: A built-in Python debugger that allows you to step through code.
- ipdb: A more advanced debugger that offers more features.
Debugging with Logging
- Adding logging statements to your code can help identify errors and trace code execution.
- Use the
logging
module.
Debugging with Third-Party Tools
- Visual Studio Code: An IDE with built-in debugging features.
- PyCharm: A professional IDE with advanced debugging capabilities.
Python Example
def add_numbers(a, b):
return a + b
# Unittest
import unittest
class TestAddNumbers(unittest.TestCase):
def test_positive_numbers(self):
self.assertEqual(add_numbers(1, 2), 3)
# pytest
import pytest
@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (-1, 2, 1)])
def test_add_numbers(a, b, expected):
assert add_numbers(a, b) == expected
# Using pdb
import pdb
def add_numbers_pdb(a, b):
pdb.set_trace() # Set a breakpoint
return a + b
# Running with pdb
add_numbers_pdb(1, 2)