Final Capstone Project
55 min read
Testing Core Features
Testing Core Features
Your application is working and now properly structured.
The next step is to verify that your core logic behaves correctly.
You will write tests for:
- user authentication
- task management
- expense calculations
Goal of This Lesson
By the end of this lesson, you will:
- set up testing
- write basic tests
- validate your application logic
- detect errors early
Step 1: Install pytest
In your terminal:
pip install pytest
Step 2: Create Test File
Create:
tests/test_app.py
Step 3: Import Functions to Test
import time
from app.services.database import create_tables
from app.services.user_service import register_user, login_user
from app.services.task_service import add_task, get_tasks
from app.services.expense_service import add_expense, get_total_expenses
# Make sure tables exist before any test runs.
create_tables()
def _unique(prefix):
"""Return a username unique to this test run."""
return f"{prefix}_{int(time.time() * 1000)}"
The _unique helper prevents tests from failing on repeat runs because of duplicate usernames.
Step 4: Test User Registration
def test_register_user():
username = _unique("test_user")
result = register_user(username, "123")
assert result is True
Step 5: Test Login
def test_login_user():
username = _unique("test_login")
register_user(username, "123")
user_id = login_user(username, "123")
assert user_id is not None
Step 6: Test Task Creation
def test_add_task():
username = _unique("task_user")
register_user(username, "123")
user_id = login_user(username, "123")
add_task(user_id, "Test Task")
tasks = get_tasks(user_id)
assert len(tasks) > 0
Step 7: Test Expense Calculation
def test_expense_total():
username = _unique("expense_user")
register_user(username, "123")
user_id = login_user(username, "123")
add_expense(user_id, 10, "Food")
add_expense(user_id, 20, "Transport")
total = get_total_expenses(user_id)
assert total >= 30
Step 8: Run Tests
In terminal:
pytest
Expected Output
4 passed
Important Notes
- Tests should not depend on GUI
- Only test service logic
- Use simple assertions
- Use
_uniqueto keep tests isolated when run repeatedly
Common Issues
Duplicate Users
If tests fail due to duplicate usernames, the _unique helper should prevent this — make sure you are using it.
Database State
Tests use the same database file.
In advanced setups, you would use a separate test database.
Why This Step Matters
Testing ensures your application:
- works correctly
- handles edge cases
- stays stable as you add features
What You Are Testing
Input → Function → Output
Summary
You added automated tests to verify your application logic, ensuring your system behaves correctly and reliably.