Skip to main content

Testing & Debugging

The Hacker’s Safety Net

Imagine you’re a hacker deploying a mission‑critical script. If it fails mid‑operation, the consequences could be disastrous. To avoid chaos, you need safety nets: automated tests that catch bugs early and debugging tools that let you dissect problems when they arise.

This chapter introduces testing with unittest and debugging with pdb. Together, they ensure your code is not only powerful but also reliable under pressure.


Why Testing & Debugging

  • Testing: Validates that code works as expected, preventing regressions.
  • Debugging: Helps identify and fix errors when things go wrong.
  • Automation: Tests run repeatedly, ensuring consistency.
  • Confidence: Reliable code builds trust in systems.
  • Real‑World Analogy: Like a hacker testing lockpicks before a mission—you don’t want surprises in the field.

Unit Testing with unittest

import unittest

def add(a, b):
    return a + b

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == "__main__":
    unittest.main()
  • Why? unittest automates checks, ensuring functions behave correctly across scenarios.

Common Assertions in unittest

  • assertEqual(a, b) → check equality
  • assertTrue(x) → check if condition is true
  • assertFalse(x) → check if condition is false
  • assertRaises(Exception, func, args) → check if exception is raised

Debugging with pdb

import pdb

def divide(a, b):
    pdb.set_trace()  # Debug breakpoint
    return a / b

print(divide(10, 0))
  • Why? pdb.set_trace() pauses execution, letting you inspect variables and step through code interactively.

Useful pdb Commands

  • n → next line
  • c → continue execution
  • p variable → print variable value
  • l → list source code around current line
  • q → quit debugger

Real‑World Example

def authenticate(user, password):
    if user == "admin" and password == "1234":
        return True
    return False

# Bug: wrong password still passes
import pdb
pdb.set_trace()
print(authenticate("admin", "wrong"))
  • Why? Debugging reveals logic errors, helping you fix vulnerabilities before deployment.

The Hacker’s Notebook

  • Testing ensures code reliability by validating expected behavior. unittest provides automated test cases with assertions.
  • Debugging with pdb lets you pause, inspect, and step through code. Combining tests and debugging builds confidence in mission‑critical scripts.

Hacker’s Mindset: treat testing and debugging as your safety nets. They catch errors before they cause damage, keeping your systems resilient and trustworthy.


Tips, Tricks, Roadmaps, Resources, Networking, Motivation, Guidance, and Cool Stuff ♥

Updated on Jan 3, 2026