A simple calculator implementation in Python with three different testing approaches.
.
├── calculator.py # Main calculator implementation
├── test_calculator.py # Basic assertion-based tests
├── test_calculator_unittest.py # Unittest-based tests
├── test_calculator_pytest.py # Pytest-based tests
├── requirements.txt # Project dependencies
└── .github
└── workflows
└── test-ci.yml # GitHub Actions workflow
-
Create a Virtual Environment
# Windows python -m venv venv .\venv\Scripts\activate # macOS/Linux python -m venv venv source venv/bin/activate
-
Install Dependencies
pip install -r requirements.txt
-
Install Pytest (if not using requirements.txt)
pip install pytest pytest-cov
When you're done working on the project:
deactivatepython calculator.pyfrom calculator import Calculator
calc = Calculator()
# Basic operations
result1 = calc.add(5, 3) # Returns 8
result2 = calc.subtract(5, 3) # Returns 2
result3 = calc.multiply(5, 3) # Returns 15
result4 = calc.divide(6, 2) # Returns 3
# Advanced operations
result5 = calc.modulo(7, 3) # Returns 1
result6 = calc.power(2, 3) # Returns 8
result7 = calc.square_root(9) # Returns 3.0- Uses Python's built-in assert statements
- Simple and straightforward
- Good for learning basics
Run with:
# From project root directory
python test_calculator.py- Uses Python's built-in unittest framework
- Class-based approach
- Detailed test organization
Run with:
# Regular mode
python -m unittest test_calculator_unittest.py
# Verbose mode
python -m unittest test_calculator_unittest.py -v- Modern testing approach
- More features and cleaner syntax
- Supports fixtures and parameterized testing
Run with:
# Run all pytest tests
pytest
# Verbose mode
pytest -v
# With print statements
pytest -v -s
# With coverage reportven
pytest --cov=calculatorThe Calculator class provides:
- Addition (
add) - Subtraction (
subtract) - Multiplication (
multiply) - Division (
divide) - Modulo (
modulo) - Power (
power) - Square Root (
square_root)
All three test suites cover:
- Basic arithmetic operations
- Edge cases:
- Division by zero
- Negative numbers
- Zero values
- Complex operations:
- Power calculations
- Square root with precision
- Modulo operations
-
Basic Assertions (
test_calculator.py)- Pros: Simple, easy to understand
- Cons: Limited features, basic error reporting
-
Unittest (
test_calculator_unittest.py)- Pros: Built-in, good organization
- Cons: More verbose, less modern features
-
Pytest (
test_calculator_pytest.py)- Pros: Modern features, clean syntax, powerful fixtures
- Cons: Additional dependency, learning curve