Techniques

Debugging Techniques

  • Print Statements: Insert print() statements throughout your code to display the values of variables or expressions at specific points.

    def calculate_sum(a, b):
                  print(f"a: {a}, b: {b}")
                  sum = a + b
                  print(f"Sum: {sum}")
                  return sum
              
              result = calculate_sum(10, 20)
              print(f"Result: {result}")
              

    Source: https://docs.python.org/3/library/functions.html#print

  • Debuggers: Use a debugger to step through your code line by line, inspect variables, and set breakpoints. Popular debuggers include:

    • pdb (Python Debugger): Built-in debugger, invoked by adding import pdb; pdb.set_trace() to your code.
    • IPython: Interactive shell with debugging features.
    • Visual Studio Code: Integrated Development Environment (IDE) with a built-in debugger.
    import pdb
              
              def calculate_average(numbers):
                  total = 0
                  for number in numbers:
                      pdb.set_trace()  # Set breakpoint
                      total += number
                  average = total / len(numbers)
                  return average
              
              numbers = [1, 2, 3, 4, 5]
              result = calculate_average(numbers)
              print(f"Average: {result}")
              

    Source: https://docs.python.org/3/library/pdb.html Source: https://ipython.org/ Source: https://code.visualstudio.com/

  • Logging: Implement a logging system to record messages at different severity levels (e.g., DEBUG, INFO, WARNING, ERROR, CRITICAL).

    import logging
              
              logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
              
              def process_data(data):
                  logging.debug(f"Processing data: {data}")
                  # ... data processing logic ...
                  logging.info(f"Data processed successfully.")
              
              data = [1, 2, 3]
              process_data(data)
              

    Source: https://docs.python.org/3/library/logging.html

Testing Techniques

  • Unit Tests: Create individual tests for specific functions or modules to verify their correctness.

    import unittest
              
              def add(x, y):
                  return x + y
              
              class TestAdd(unittest.TestCase):
                  def test_add_positive(self):
                      self.assertEqual(add(2, 3), 5)
              
                  def test_add_negative(self):
                      self.assertEqual(add(-2, 3), 1)
              
              if __name__ == '__main__':
                  unittest.main()
              

    Source: https://docs.python.org/3/library/unittest.html

  • Integration Tests: Test the interaction between different parts of your application.

    # Example integration test for a web application
              import requests
              
              def test_login(self):
                  response = requests.post('https://example.com/login', data={'username': 'testuser', 'password': 'testpassword'})
                  self.assertEqual(response.status_code, 200)
              
  • End-to-End Tests: Verify the complete workflow of your application from start to finish.

    # Example end-to-end test for a web application
              from selenium import webdriver
              
              def test_user_registration(self):
                  driver = webdriver.Chrome()
                  driver.get('https://example.com/register')
                  # ... simulate user registration steps ...
                  driver.quit()
              

    Source: https://www.selenium.dev/