Skip to content
PythonAlgorithms and Capstone Practicebeginner35 min read

Capstone: Test, Refactor, and Document

Finish your command-line task tracker by testing its behavior, refactoring for readability, and documenting how another developer can run and maintain it.

In this lesson, you will learn

  • ✓Explain why testing, refactoring, and documentation are essential parts of completing a software project.
  • ✓Write unit tests with Python's unittest framework.
  • ✓Use assertions to verify return values, state changes, and expected exceptions.
  • ✓Refactor repetitive code into small, descriptive functions without changing its behavior.
  • ✓Write a README containing project purpose, requirements, setup, usage, and testing instructions.
  • ✓Evaluate a small capstone project using functional and edge-case tests.

1. The three parts of a finished project

Testing checks whether a program behaves as intended. A test supplies a known input or starting state and verifies the result. For example, adding a task should increase the task count, and completing a task should change its completed status.

Refactoring means improving the internal structure of existing code while preserving its externally observable behavior. Renaming unclear variables, extracting a repeated operation into a function, and removing unnecessary duplication are common examples. Refactoring is not the same as adding a new feature.

Documentation explains what a project does and how another person can install, run, use, and test it. A README file is usually the first place a developer looks for these instructions.

These activities support one another. Tests give you evidence that behavior has not changed unexpectedly during refactoring. Clear function names make both code and tests easier to understand. Documentation tells users what behavior they should expect.

Recognizing the three activities

Recognizing the three activities
python
def add_task(tasks, title):
tasks.append({"title": title, "completed": False})
 
# Testing: check the function's behavior.
tasks = []
add_task(tasks, "Study Python")
assert len(tasks) == 1
assert tasks[0]["completed"] is False
 
# Refactoring: use a clearer function name or structure
# while preserving the same behavior.
 
# Documentation: explain how to run and test the project.
print("Task behavior verified")
Output
Task behavior verified

The function adds a dictionary representing one incomplete task. The assertions verify both the number of tasks and the initial completion status. The example demonstrates testing. Refactoring and documentation are separate activities, not operations performed by these assertions.

Note

A passing test is evidence for the specific behavior it checks. It does not prove that every possible input or every part of the application is correct.

2. Write your first unit test with unittest

A unit test checks a small, identifiable part of a program, such as one function. Python includes the unittest module, so you can begin testing without installing an external testing package.

A test file commonly imports unittest and the function or class being tested. Test methods are placed inside a class that inherits from unittest.TestCase. Their names should begin with test so the test runner can discover them.

Use self.assertEqual(actual, expected) to compare values, self.assertTrue(condition) to check a true condition, self.assertFalse(condition) to check a false condition, and self.assertRaises(ExceptionType) to check that an expected exception occurs.

Save test code in a separate file from the application's main implementation. This separation helps keep the application organized and lets you run tests without manually exercising every feature.

A complete unit test

A complete unit test
python
# task_tracker.py
def calculate_total(price, quantity):
return price * quantity
 
# test_task_tracker.py
import unittest
from task_tracker import calculate_total
 
class TestCalculateTotal(unittest.TestCase):
def test_multiplies_price_by_quantity(self):
self.assertEqual(calculate_total(12, 3), 36)
 
def test_zero_quantity(self):
self.assertEqual(calculate_total(12, 0), 0)
 
if __name__ == "__main__":
unittest.main()
Output
Result Table
..
Ran 2 tests
1 row returned1 column

OK

The application function is stored in task_tracker.py, while its tests are stored in test_task_tracker.py. The first test checks an ordinary calculation. The second checks a boundary case where the quantity is zero. The dots represent passing tests. The exact elapsed time and some formatting may differ between Python environments. Run the tests from the directory containing both files with python -m unittest -v test_task_tracker.py. The -v option displays individual test names.

Note

The displayed test output is representative. Test-runner formatting can vary by Python version and invocation.

3. Test task-tracker behavior and edge cases

The task tracker from Lesson 62 stores tasks in a list of dictionaries. Each task has an ID, a title, and a completed flag. You should test the behavior that matters to users instead of merely checking whether a function can be called.

For adding a task, verify that the list grows, the title is preserved, and the completed flag starts as False. For completing a task, verify that the matching task becomes completed. For deleting a task, verify that the task is removed and that unrelated tasks remain unchanged.

Edge cases are inputs or states that deserve special attention. For this tracker, useful examples include an empty list, a task ID that does not exist, a title containing only spaces, and an ID that is not a valid positive integer.

The following example tests small task-management functions. It uses a list passed into each function so the behavior can be tested independently of the interactive menu.

A useful test should fail when the behavior it is meant to protect is broken. For example, if add_task accidentally sets completed to True, the test for the initial completion state should fail. This ability to expose a regression is one reason tests are valuable during later changes.

Test adding, completing, and deleting tasks

Test adding, completing, and deleting tasks
python
import unittest
 
def add_task(tasks, task_id, title):
if not title.strip():
raise ValueError("Task title cannot be empty")
task = {
"id": task_id,
"title": title.strip(),
"completed": False,
}
tasks.append(task)
return task
 
def complete_task(tasks, task_id):
for task in tasks:
if task["id"] == task_id:
task["completed"] = True
return True
return False
 
def delete_task(tasks, task_id):
for index, task in enumerate(tasks):
if task["id"] == task_id:
del tasks[index]
return True
return False
 
class TestTaskOperations(unittest.TestCase):
def setUp(self):
self.tasks = []
 
def test_adds_incomplete_task(self):
task = add_task(self.tasks, 1, "Study Python")
self.assertEqual(task["title"], "Study Python")
self.assertFalse(task["completed"])
self.assertEqual(len(self.tasks), 1)
 
def test_rejects_blank_title(self):
with self.assertRaises(ValueError):
add_task(self.tasks, 1, " ")
self.assertEqual(self.tasks, [])
 
def test_completes_existing_task(self):
add_task(self.tasks, 1, "Study Python")
self.assertTrue(complete_task(self.tasks, 1))
self.assertTrue(self.tasks[0]["completed"])
 
def test_missing_task_is_not_completed(self):
self.assertFalse(complete_task(self.tasks, 99))
 
def test_deletes_only_matching_task(self):
add_task(self.tasks, 1, "Read")
add_task(self.tasks, 2, "Practice")
self.assertTrue(delete_task(self.tasks, 1))
self.assertEqual([task["id"] for task in self.tasks], [2])
 
if __name__ == "__main__":
unittest.main()
Output
Result Table
.....
Ran 5 tests
1 row returned1 column

OK

setUp runs before each test method. Each test therefore starts with a fresh empty list. The tests check normal behavior, a blank title, an existing task, a nonexistent task, and deletion of a particular task. The functions return True or False to make their outcomes easy to test. Your actual Lesson 62 functions may have different return values or signatures, so adapt the tests to the implementation you use. These are illustrative tests for the functions shown here, not a claim that the complete interactive Lesson 62 program has already been tested.

Caution

Do not write tests that merely repeat the implementation's assumptions. Decide the expected behavior first, then assert that the code satisfies it. For a task ID that does not exist, explicitly choose whether the function should return False, display a message, or raise an exception.

4. Refactor without changing behavior

Refactoring improves the design of existing code while preserving the behavior that users and other code rely on. The safest small refactors are easy to explain and make one improvement at a time.

Start with names. A name such as x, temp, or do_it usually communicates less than task_title, remaining_tasks, or find_task_by_id. Next, look for repeated logic. If several parts of the program perform the same lookup, a helper function can give that operation one clear definition.

Small functions are easier to test because they have a focused responsibility. For example, a function that finds a task by ID should locate a task; it should not also print the menu, read user input, and save unrelated information.

Do not confuse refactoring with changing the requirements. If you change how missing tasks are handled or introduce persistent file storage, you are changing behavior or adding a feature. Make such changes deliberately and update the tests and documentation.

Replace repeated search logic with a helper

Replace repeated search logic with a helper
python
# Before: the same search is repeated in multiple functions.
def complete_task_before(tasks, task_id):
for task in tasks:
if task["id"] == task_id:
task["completed"] = True
return True
return False
 
# After: give the search one clear definition.
def find_task_by_id(tasks, task_id):
for task in tasks:
if task["id"] == task_id:
return task
return None
 
def complete_task(tasks, task_id):
task = find_task_by_id(tasks, task_id)
if task is None:
return False
task["completed"] = True
return True
 
tasks = [
{"id": 1, "title": "Study", "completed": False}
]
print(complete_task(tasks, 1))
print(tasks[0]["completed"])
print(find_task_by_id(tasks, 99))
Output
True True None

find_task_by_id returns the matching task dictionary or None when no match exists. complete_task delegates the search to that helper and handles the missing-task case explicitly. The helper can also be reused by deletion or display-related logic, avoiding multiple implementations of the same lookup. The refactored function still marks the matching task complete and reports whether it found the task.

Note

A refactor is safer when existing tests pass before and after the change. Passing tests do not guarantee perfect equivalence, but they help catch unintended changes in the behaviors they cover.

5. Document the project with a README

A README is a practical entry point for your project. It should help a new developer answer four questions: What does this program do? What do I need to run it? How do I run it? How can I check that it works?

For a small Python command-line project, include the project name, purpose, Python requirement, setup and run commands, usage instructions, testing command, and important limitations. If tasks exist only in memory, say so explicitly; users should not be led to believe their tasks persist after the program exits.

Use Markdown headings and fenced code blocks so instructions are easy to scan and commands are easy to copy. Documentation should describe the actual project rather than planned features that have not been implemented.

Do not include passwords, API keys, personal information, or other secrets in a README or source-control repository. A README is commonly public or shared with other developers.

Example README for the task tracker

Example README for the task tracker
markdown
# Command-Line Task Tracker
 
## Overview
A small Python command-line application for adding, listing,
completing, and deleting tasks.
 
## Requirements
- Python 3
 
## Run the application
From the project directory, run:
 
```bash
python main.py
```
 
If your entry-point file has a different name, use that file
instead of `main.py`.
 
## Usage
Follow the displayed menu to add, list, complete, or delete
tasks. Enter the requested task ID when prompted.
 
## Run tests
If tests are stored in `test_task_tracker.py`, run:
 
```bash
python -m unittest -v test_task_tracker.py
```
 
## Data storage
Tasks are kept in memory. They are not saved between runs.
 
## Limitations
This is a learning project. It does not provide persistent
storage or multi-user synchronization.
Output
A Markdown README describing the project's purpose, requirements, commands, usage, and limitations.

README content is documentation, not Python code. The fenced commands are examples of commands a user can run in a terminal. The run command assumes the entry-point file is named main.py. Change it to match your actual project structure. The test command assumes the test file and import structure match the example. Update it if your tests are organized differently. The data-storage section communicates a real limitation of the in-memory tracker.

Note

Documentation must match the current implementation. If you later add JSON persistence, revise the storage description and add instructions or tests for that behavior.

6. Run the final capstone review

Before calling the task tracker complete, review it from the perspective of someone who has never seen the code. Can that person identify the entry point, understand the menu, and learn how to run the tests from the README?

A small project does not need a large testing framework or an elaborate documentation site. A few focused tests, descriptive function names, sensible separation of responsibilities, and accurate setup instructions are a strong starting point.

Review both successful operations and failures. Confirm that a task can be added and listed, completion changes the intended task, deletion removes only the intended task, and a missing ID does not accidentally modify another task. If the application accepts keyboard input, check that invalid input is handled according to the behavior you intended.

Finally, rerun the tests after each meaningful refactor. If a test fails, inspect the failure before changing the test. The correct response is not automatically to make the test pass; first determine whether the code or the expected behavior is wrong.

A compact final verification checklist

A compact final verification checklist
text
Behavior
[ ] Adding a valid task works.
[ ] Listing tasks shows the expected details.
[ ] Completing a task updates its status.
[ ] Deleting a task removes only the intended task.
[ ] Empty lists and missing IDs are handled deliberately.
 
Code quality
[ ] Functions have clear names and focused responsibilities.
[ ] Repeated logic has been reviewed for safe reuse.
[ ] Tests cover important normal and edge cases.
 
Documentation
[ ] README describes the actual features and limitations.
[ ] Run and test commands match the project structure.
[ ] No secrets are committed.
Output
A review checklist to complete against the actual project.

The checklist is a review aid, not an automated test report. Check an item only after verifying it in your own project. The final result should be understandable, testable, and documented—not merely capable of running once.

Caution

The checklist does not itself verify your files. Run the application and test suite in the real project, and update the README to reflect the code that actually exists.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Testing only one successful input.

Why it happens: A single successful input cannot demonstrate correct handling of invalid data, missing IDs, empty state, or boundary conditions.

Incorrect Approach
script.py
python
Testing only one successful input.
Correct Solution
script.py
python
Add tests for important boundaries and failure cases, such as an empty task list, a blank title, or a task ID that does not exist.

Key takeaway: Add tests for important boundaries and failure cases, such as an empty task list, a blank title, or a task ID that does not exist.

#2 Assuming that a program is correct because it runs without crashing.

Why it happens: A program can run without crashing and still produce the wrong result, so assert expected behavior rather than only checking for exceptions.

Incorrect Approach
script.py
python
Assuming that a program is correct because it runs without crashing.
Correct Solution
script.py
python
Assert the expected return values and state changes. A program can run successfully while producing the wrong result.

Key takeaway: Assert the expected return values and state changes. A program can run successfully while producing the wrong result.

#3 Changing the intended behavior while claiming to refactor.

Why it happens: Refactoring should improve internal structure while preserving externally observable behavior; tests help verify that contract.

Incorrect Approach
script.py
python
Changing the intended behavior while claiming to refactor.
Correct Solution
script.py
python
Keep behavior-preserving changes separate from new features. Use existing tests to detect unexpected changes.

Key takeaway: Keep behavior-preserving changes separate from new features. Use existing tests to detect unexpected changes.

#4 Testing only the printed menu instead of the underlying task operations.

Why it happens: Testing only menu text does not verify the operations behind it; test the functions that add, update, remove, and summarize tasks.

Incorrect Approach
script.py
python
Testing only the printed menu instead of the underlying task operations.
Correct Solution
script.py
python
Test the task-management functions independently where practical, then manually or automatically check important user interactions.

Key takeaway: Test the task-management functions independently where practical, then manually or automatically check important user interactions.

#5 Using unclear names or creating one very large function.

Why it happens: Unclear names and oversized functions hide responsibilities and make changes risky; prefer descriptive names and small focused functions.

Incorrect Approach
script.py
python
Using unclear names or creating one very large function.
Correct Solution
script.py
python
Use descriptive names and extract focused helpers when doing so makes responsibilities easier to understand.

Key takeaway: Use descriptive names and extract focused helpers when doing so makes responsibilities easier to understand.

#6 Writing a README that describes features that do not exist.

Why it happens: Documentation should match actual behavior and commands in the repository; stale or invented instructions mislead users.

Incorrect Approach
script.py
python
Writing a README that describes features that do not exist.
Correct Solution
script.py
python
Document the current implementation, including limitations such as in-memory-only storage.

Key takeaway: Document the current implementation, including limitations such as in-memory-only storage.

#7 Assuming that assert statements are a complete replacement for a test suite.

Why it happens: Assertions are useful checks, but a test suite should also organize cases, run them repeatedly, and report failures clearly.

Incorrect Approach
script.py
python
Assuming that assert statements are a complete replacement for a test suite.
Correct Solution
script.py
python
Use assertions for simple checks when useful, and organize repeatable project tests with unittest or another suitable test framework.

Key takeaway: Use assertions for simple checks when useful, and organize repeatable project tests with unittest or another suitable test framework.

#8 Ignoring a failed test by changing the expected value immediately.

Why it happens: A failing test is evidence to investigate, not a reason to weaken the expected result without confirming the requirement.

Incorrect Approach
script.py
python
Ignoring a failed test by changing the expected value immediately.
Correct Solution
script.py
python
Determine whether the implementation is incorrect or the test expectation is wrong before changing either one.

Key takeaway: Determine whether the implementation is incorrect or the test expectation is wrong before changing either one.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is unit testing?
Answer:
Unit testing checks a small part of a program, such as an individual function, in isolation where practical. It verifies that the function's behavior matches specified expectations.
Q2:What is the difference between testing and debugging?
Answer:
Testing checks whether behavior meets expectations and can reveal failures. Debugging investigates a problem to identify its cause and correct it. Testing can expose a defect; debugging helps explain and fix it.
Q3:What is refactoring?
Answer:
Refactoring improves the internal structure of code without intentionally changing its externally observable behavior. Examples include improving names, extracting helper functions, and removing duplicated logic.
Q4:Why are descriptive function names important?
Answer:
Descriptive names communicate a function's purpose, reduce the effort required to understand the code, and make the program easier to review and maintain.
Q5:What is an edge case?
Answer:
An edge case is a condition near a boundary or an unusual input that may expose a defect. In a task tracker, examples include an empty task list, a blank title, and a nonexistent task ID.
Q6:What is the purpose of unittest.TestCase.setUp()?
Answer:
setUp() runs before each test method. It is useful for preparing a known initial state, such as creating a fresh task list for every test.
Q7:Why use assertRaises() in a test?
Answer:
assertRaises() verifies that a particular exception is raised by the tested operation. It is useful when invalid input is expected to be rejected.
Q8:Why should tests be rerun after refactoring?
Answer:
A structural change can accidentally alter behavior. Rerunning tests helps reveal regressions in the behaviors those tests cover.
Q9:What should a README contain?
Answer:
A useful README describes the project's purpose, requirements, setup, run commands, basic usage, testing instructions, and relevant limitations.
Q10:Do passing unit tests guarantee that an application is correct?
Answer:
No. Passing tests show that the checked cases met their expectations. The program can still fail on untested inputs, integration paths, environment differences, or requirements that the tests do not cover.

Key takeaways

  • Testing verifies specific behaviors against expected results.
  • Python's unittest framework provides test cases and assertions for repeatable checks.
  • Test normal inputs, boundary cases, and invalid inputs where relevant.
  • Refactoring improves readability and structure while preserving intended behavior.
  • Small, descriptive functions are easier to understand and test.
  • A README should explain the real setup, usage, testing process, and limitations of the project.
  • Rerun tests after refactoring and investigate failures rather than changing expectations blindly.
  • The capstone is complete when its behavior has been checked, its code is understandable, and its documentation accurately describes the application.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: