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
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
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
| .. |
|---|
| Ran 2 tests |
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
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
| ..... |
|---|
| Ran 5 tests |
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is unit testing?
Q2:What is the difference between testing and debugging?
Q3:What is refactoring?
Q4:Why are descriptive function names important?
Q5:What is an edge case?
Q6:What is the purpose of unittest.TestCase.setUp()?
Q7:Why use assertRaises() in a test?
Q8:Why should tests be rerun after refactoring?
Q9:What should a README contain?
Q10:Do passing unit tests guarantee that an application is correct?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: