Testing and Debugging with Copilot
When you start writing more complex programs, it’s important to make sure your code works as expected. Testing helps you catch mistakes early, and debugging helps you find and fix problems when things go wrong.
In this module, you’ll learn how to write unit tests, use assertions, and debug code — with the help of Copilot prompts.
Why is testing important?
- Ensures your code behaves correctly.
- Helps prevent bugs from breaking existing features when you make changes.
- Makes your code more reliable and easier to maintain.
Writing Unit Tests
A unit test checks whether a small piece of your code (like a function) works correctly. In Python, we often use the built-in unittest
module for this.
Prompt
1
# Create a simple unit test for a function that adds two numbers
Example Copilot Suggestion
1 2 3 4 5 6 7 8 9 10 11 12 13
def add(a, b): return a + b import unittest class TestMathFunctions(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-1, 1), 0) self.assertEqual(add(0, 0), 0) if __name__ == "__main__": unittest.main()
Explanation
def add(a, b)
: Function to test.unittest.TestCase
: A class for creating tests.self.assertEqual
: Checks if the function's output equals the expected result.unittest.main()
: Runs all tests when the script is executed.
How to run it
Save the file (e.g., test_add.py
), then run:
1
python test_add.py
What happens if a test fails?
If a test fails, you’ll see an error message showing which test failed and what the expected value was.
Using Assertions
An assertion is a statement that checks if a condition is True. If not, it stops the program and raises an error. Assertions are a simple way to add quick checks in your code.
Prompt
1
# Add assertions to check if a list is sorted in ascending order
Example Copilot Suggestion
1 2 3 4 5 6 7 8 9 10
def is_sorted(lst): for i in range(len(lst) - 1): assert lst[i] <= lst[i + 1], f"List is not sorted at index {i}" return True numbers = [1, 2, 3, 4, 5] is_sorted(numbers) # This will pass unsorted_numbers = [1, 3, 2, 5] is_sorted(unsorted_numbers) # This will raise an AssertionError
Explanation
assert condition, message
: Checks ifcondition
is True. If not, it raises anAssertionError
with the message.- In this example,
assert lst[i] <= lst[i + 1]
checks if each element is smaller than or equal to the next one.
When to use assertions
- For simple internal checks during development.
- Not recommended for user-facing error handling in production code.
Basic Debugging in VS Code
When something goes wrong in your code, debugging helps you find and fix the issue step by step.
Prompt
1
# Suggest debugging steps for a function returning incorrect results
Example Copilot Suggestion
1 2 3 4 5 6
# Steps for debugging in VS Code: # 1. Add print statements to check variable values. # 2. Use breakpoints: click to the left of the line number in your code. # 3. Run the debugger (click "Run and Debug" or press F5). # 4. Inspect variables in the Debug panel. # 5. Step through your code line by line to see where things go wrong.
Example Debugging Steps
Let’s say your function isn’t returning what you expect:
1 2 3
def multiply(a, b): result = a * b + 2 return result
Expected: multiply(3, 4)
→ 12
Actual: 14 (because of + 2
)
Step-by-step
1. Add print statements
1 2 3 4
def multiply(a, b): result = a * b + 2 print(f"a: {a}, b: {b}, result: {result}") return result
2. Add a breakpoint
- Click in the margin to the left of
result = a * b + 2
. - Press F5 to start debugging.
- Use "Step Over" (F10) to go line by line.
3. Check variables
- Hover over variables to see their current values.
- Use the Debug panel to watch variables.
4. Fix the bug
1 2 3
def multiply(a, b): result = a * b # Removed +2 return result
Key Takeaways
- Unit tests verify your code works correctly.
- Assertions check conditions during execution and help catch logic errors early.
- VS Code’s debugger lets you inspect your code step by step and find exactly where things break.
- Copilot can help generate test cases, assertions, and even suggest debugging strategies — but always review them carefully.
Mini Challenge
Prompt
1
# Write a unit test for a function that returns the maximum element in a list
Try writing the function first, then generate the unit test using Copilot.
Extra Practice
- Create a function that checks if a string is a palindrome. Write unit tests for it.
- Write assertions to check if a dictionary has certain keys.
- Use the debugger to fix a function that calculates the factorial but gives the wrong result for input 0.
Tips for Beginners
- Start by testing small functions before testing large code blocks.
- Use clear prompts when asking Copilot for tests, like "Create a unit test for function X."
- Don’t be afraid to step through your code slowly in the debugger — it’s the best way to learn!