Tuesday, November 11, 2025

thumbnail

Testing and Debugging in Python

 ⚡ 1. Testing in Python


Python has multiple ways to test your code: unit tests, integration tests, and end-to-end tests.


1.1 Unit Testing with unittest (Built-in)

# my_module.py

def add(a, b):

    return a + b


# test_my_module.py

import unittest

from my_module import add


class TestMathFunctions(unittest.TestCase):

    def test_add_positive_numbers(self):

        self.assertEqual(add(2, 3), 5)

    

    def test_add_negative_numbers(self):

        self.assertEqual(add(-2, -3), -5)


if __name__ == "__main__":

    unittest.main()



Run: python test_my_module.py


Key methods: assertEqual, assertTrue, assertFalse, assertRaises


1.2 Using pytest (Simpler & More Powerful)

# test_my_module.py

from my_module import add


def test_add_positive():

    assert add(2, 3) == 5


def test_add_negative():

    assert add(-2, -3) == -5



Run: pytest (automatically discovers test_*.py files)


Supports fixtures, parameterized tests, and plugins.


1.3 Mocking External Dependencies


Sometimes functions depend on APIs, databases, or files. Use unittest.mock:


from unittest.mock import patch

import requests


def get_status(url):

    response = requests.get(url)

    return response.status_code


@patch('requests.get')

def test_get_status(mock_get):

    mock_get.return_value.status_code = 200

    assert get_status("http://example.com") == 200



Prevents real network calls and isolates the function being tested.


1.4 Test Coverage


Measure how much of your code is tested using coverage:


pip install coverage

coverage run -m pytest

coverage report -m


๐Ÿ” 2. Debugging in Python


Debugging is the process of finding and fixing errors in your code. Python provides multiple tools:


2.1 Print Statements (Quick & Dirty)

def divide(a, b):

    print(f"a={a}, b={b}")

    return a / b


divide(5, 0)  # Will help track variables



Simple but can clutter code.


2.2 Using pdb (Python Debugger)

import pdb


def divide(a, b):

    pdb.set_trace()  # Pauses execution here

    return a / b


divide(5, 0)



Commands inside pdb:


n → next line


s → step into function


c → continue execution


p variable → print variable


2.3 Using IDE Debuggers


Most IDEs (PyCharm, VS Code) provide graphical debugging:


Set breakpoints


Inspect variables


Step over / into / out


Watch expressions and call stack


2.4 Exception Handling & Logging


Instead of letting errors crash your program:


import logging


logging.basicConfig(level=logging.INFO)


def divide(a, b):

    try:

        return a / b

    except ZeroDivisionError as e:

        logging.error(f"Error: {e}")

        return None



Logging is preferred over print for production code.


You can configure different log levels: DEBUG, INFO, WARNING, ERROR.


2.5 Profiling & Performance Debugging


cProfile: Find slow parts of your code:


python -m cProfile my_script.py



Helps optimize performance bottlenecks.


✅ 3. Best Practices


Write tests before or alongside code (Test-Driven Development).


Keep tests small and independent.


Use mocking to isolate external dependencies.


Debug systematically:


Reproduce the bug


Inspect variables & stack trace


Apply logging


Automate tests using CI/CD pipelines.


Combine testing and debugging: tests often reveal bugs, debugging fixes them.

Learn Fullstack Python Training in Hyderabad

Read More

How to Test Your API Endpoints in Python

Building Versioned APIs in Python

How to Handle Errors and Responses in Full Stack Python APIs

Integrating Third-Party APIs with Full Stack Python

At Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive