This worksheet will guide you through the process of applying Test-Driven Development (TDD) to build a simple calculator in Python. You will follow the classic Red-Green-Refactor cycle for each arithmetic operation.
You are asked to build a Calculator
module that supports the following operations:
- Addition (
add
) - Subtraction (
subtract
) - Multiplication (
multiply
) - Division (
divide
)
All operations must be covered by test cases first, before the actual implementation.
Your project should have the following structure:
tdd_calculator/
βββ calculator/
β βββ operations.py
βββ tests/
β βββ test_operations.py
Make sure you can run tests using the following command:
python -m unittest discover -s tests
In tests/test_operations.py
, write a test case for the addition function:
import unittest
from calculator.operations import add
class TestCalculator(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()
Run the test, and confirm it fails because the function does not exist yet.
In calculator/operations.py
, implement the add()
function:
def add(a, b):
return a + b
Run the test again. It should now pass.
Now repeat the Red-Green-Refactor cycle for the following:
subtract(a, b)
β with test case and implementationmultiply(a, b)
β with test case and implementationdivide(a, b)
β make sure to test division by zero (expect an exception)
Write each test first, make sure it fails, then write the implementation.
π‘ Extra Challenge!
If this calculator case feels too easy for you, maybe basic math is already beneath your greatness.
Feel free to level up with the TDD Bus Fare repo β where real-world logic and chaos await.
π Go to the Bus Fare repo