Testing and Debugging

Section 9: Testing and Debugging

Lesson 1: Unit Testing in Python

1.1 Writing and Running Tests

Unit testing is a crucial practice for ensuring the correctness of your code. The unittest module in Python provides a framework for writing and running tests.

Example: 

# Writing and running tests with unittest

import unittest


def add(a, b):

    return a + b


class TestAddFunction(unittest.TestCase):

    def test_add_positive_numbers(self):

        result = add(3, 5)

        self.assertEqual(result, 8)


    def test_add_negative_numbers(self):

        result = add(-2, 7)

        self.assertEqual(result, 5)


if __name__ == '__main__':

    unittest.main()


1.2 Test Frameworks in Python

Apart from unittest, there are other popular testing frameworks in Python, such as pytest and nose. These frameworks provide additional features and often require less boilerplate code.

Example (using pytest):

# Writing and running tests with pytest

def test_add_positive_numbers():

    result = add(3, 5)

    assert result == 8


def test_add_negative_numbers():

    result = add(-2, 7)

    assert result == 5


Lesson 2: Debugging Techniques

2.1 Using pdb and Other Debugging Tools

Python comes with a built-in debugger called pdb. You can use it to set breakpoints, inspect variables, and step through your code.

Example: 

# Using pdb for debugging

import pdb


def divide(a, b):

    result = a / b

    return result


# Set a breakpoint

pdb.set_trace()


# Calling the function

result = divide(10, 2)

print(result)

Apart from pdb, there are also visual debuggers like PyCharm and VSCode that provide a graphical interface for debugging.


In Section 9, we covered testing and debugging techniques in Python.

Unit testing is essential for verifying the correctness of your code. The unittest module and other testing frameworks like pytest provide tools for writing and running tests.

Debugging is a crucial skill for identifying and fixing issues in your code. The built-in pdb debugger and visual debuggers can help you step through your code, inspect variables, and understand the flow of execution.

By incorporating testing and debugging into your development process, you can ensure the reliability and maintainability of your code. These practices are fundamental for writing robust and error-free software.