This project simulates a digital coffee machine. More importantly, it serves as a laboratory for learning how to ensure software is reliable and "bug-free" using professional testing tools.
Before running the code, we create a Virtual Environment. Think of this as a dedicated toolbox just for this project. It ensures that the tools we install here don't interfere with other projects on your computer.
- Open your terminal in VS Code.
- Create the environment:
python -m venv venv
- Activate the environment:
- Mac/Linux:
source venv/bin/activate - Windows:
.\venv\Scripts\activate
- Mac/Linux:
You will know it worked if you see (venv) appear at the start of your command line.
Now we need to install the specific libraries (like coverage and mutmut) required for this project.
Run this command:
pip install -r requirements.txtTo see the machine in action and interact with it, run the main program:
python coffee_machine.pyWe have a file called test_coffee_machine.py. This is a "robot" that runs a series of checks to make sure the coffee machine behaves correctly (e.g., it shouldn't make coffee if there isn't enough water).
To run these checks:
python -m unittest test_coffee_machine.py- OK: All tests passed!
- FAIL: The robot found a mistake in the logic.
"Coverage" tells us which lines of our code were actually tested by our robot. If our code is 100 lines long and our tests only check 80 lines, we have 80% coverage.
- Run the tests with the coverage tool:
coverage run -m unittest test_coffee_machine.py
- View the report:
coverage report
Look at the Stmts (Statements) and Miss (Lines missed) columns to see which parts of the machine were ignored.
Coverage only tells us if a line was executed. It doesn't tell us if our test was actually smart enough to catch a mistake.
Mutation Testing (using a tool called mutmut) intentionally "breaks" your code—for example, changing a > to a <—and then runs your tests. If your tests still pass despite the code being broken, your tests "failed" to catch the bug.
- Run the mutation cycle:
mutmut run
- See the summary:
mutmut results
If you see "Survived" mutants, it means mutmut broke your code, but your tests were too weak to notice!
To see exactly what mutmut changed to trick your tests, pick a number from the results list (e.g., 5) and type:
mutmut show 5This will show a "Diff" (a comparison). The lines with - are your original code, and the lines with + are the "mutant" (broken) code that your tests missed.
| Action | Command |
|---|---|
| Run Program | python coffee_machine.py |
| Run Tests | python -m unittest test_coffee_machine.py |
| Check Coverage | coverage report |
| Mutation Test | mutmut run |
| View Mistakes | mutmut show <number> |