Python lesson 29 of 50 · Intermediate · About 29 minutes
Write quick tests for actions that might quietly break when you improve the game.

Mission Use unittest to check blocked routes, repeated pickups, repair conditions, save boundaries and seeds.
Get ready
Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.
Save the complete checkpoint below as moonbase_29.py in a project folder and run python moonbase_29.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Understand the Python in this lesson
Read the explanations, then follow the worked example before changing the code.
Collect the checks in a test class
class MissionTests(unittest.TestCase): makes a group of related tests. The name inside the parentheses means the class inherits checking tools from unittest.TestCase. The indented functions with names beginning test_ are the checks that the test loader discovers.
Use self to reach the checking tools
In a test method, self is the current test object. self.assertEqual(actual, expected) compares two values and reports a failure if they differ. self.assertTrue(...) checks for a truthy answer, and self.assertFalse(...) checks for a falsey one. The repair rule supplies a boolean for those last two checks.
Make a fresh mission inside each test
state = new_mission(17) starts a separate dictionary for the test. One test saves the starting energy, tries the blocked west move, checks its message, then checks the energy again. Another test moves east and calls collect twice. Its expected list is ["Coil"].
Test for a deliberately rejected value
with self.assertRaises(ValueError): sets an expectation for the indented block. Calling validate_save(state) with boolean energy should raise that exception. The test passes when the expected exception happens. If the function simply accepts the invalid value, the test fails.
Run a suite instead of switching on the radio
action="store_true" makes --test a switch. The loader collects the methods, and TextTestRunner runs them and makes a result. stream=sys.stdout sends the report to the output you see. The inline 0 if ... else 1 chooses a status code, and raise SystemExit(...) ends the test run before the command loop can start.
How the pieces fit These tests call the same functions that play uses. They can check one rule at a time without simulating a keyboard or reading the radio output. Lesson 30 adds a test that connects several of those rules in a winning route.
-
Launch the checkpoint with --test.
options.test is True. Why The switch uses action="store_true". -
Follow the blocked-move test.
It compares the reply with That route is blocked. and compares charge before and after. Why Checking state as well as text catches a movement bug that the message alone could miss. -
Read the report when the tests finish.
Ran 5 tests and OK. Why All the discovered test methods passed.
Predict before you run If validate_save returns normally when given True for energy, does the assertRaises check pass?
Reveal the explanation
The check fails because the expected ValueError never happened. That points you to the type check in validate_save.
Build the checkpoint
Python skills unittest, assertions, test isolation, regressions.
1. Give each test its own mission
Make a fresh state at the beginning of a test. Store the starting charge, try an impossible move and compare the charge afterwards. A fresh state means your result cannot be affected by an earlier test. Use assertEqual to compare values and get a clear explanation if they differ.
def test_failed_move_costs_nothing(self):
state = new_mission(17)
energy = state["energy"]
self.assertEqual(move(state, "west"), "That route is blocked.")
self.assertEqual(state["energy"], energy)
2. Write an expected failure test
The file validator must raise ValueError for boolean energy, even though booleans can behave like the numbers 0 and 1. Use assertRaises to describe this expected exception. Other tests check that collecting twice leaves one Coil and that both parts are required for a repair at the Beacon.
def test_invalid_save_rejects_boolean_energy(self):
state = new_mission(17)
state["energy"] = True
with self.assertRaises(ValueError):
validate_save(state)
3. Create a switch to run tests instead of the game
Run python moonbase.py --test from the project folder. The program uses the test loader to find methods named test and reports them without opening the radio prompt. The same script still runs the usual mission when you leave off the switch. At this stage, you can make a harmless temporary mistake, watch the right test fail, and fix it before continuing.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(MissionTests)
result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)
raise SystemExit(0 if result.wasSuccessful() else 1)
run(options.seed)
4. Read a failure as evidence
When a test fails, read its name, expected value and actual value before editing. The test name points to one rule, and its setup tells you exactly how to reproduce the mistake. Make a single change, rerun the suite, and confirm the other already-passing rules still pass.
Complete Python checkpoint · moonbase_29.py
import argparse
import random
import json
from pathlib import Path
import sys
import unittest
WORLD = {
"Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None},
"Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"},
"Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"},
"Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None},
}
REQUIRED = {"Coil", "Cell"}
SAVE_FILE = Path("moonbase-save.json")
def new_mission(seed=0):
generator = random.Random(seed)
charge = generator.choice([7, 8, 9])
return {"room": "Habitat", "energy": charge, "parts": [], "rescued": False}
def can_repair(room, parts):
return room == "Beacon" and REQUIRED.issubset(parts)
def describe(state):
room, energy, cargo, _ = mission_snapshot(state)
exits = ", ".join(WORLD[room]["exits"])
parts = ", ".join(cargo) or "none"
return f"{room} | energy {energy} | parts {parts} | exits {exits}"
def collect(state):
item = WORLD[state["room"]]["part"]
if item is None:
return "There is no repair part here."
if item in state["parts"]:
return f"You already have the {item}."
state["parts"].append(item)
return f"Collected the {item}."
def repair(state):
if can_repair(state["room"], state["parts"]):
state["rescued"] = True
return "Beacon restored! Pip has sent the rescue signal."
return "Bring the Coil and the Cell to the Beacon."
def move(state, direction):
destination = WORLD[state["room"]]["exits"].get(direction)
if destination is None:
return "That route is blocked."
if state["energy"] == 0:
return "Pip is out of energy."
state["room"] = destination
state["energy"] -= 1
return f"Moved to {destination}."
def parse_command(text):
words = text.lower().split()
if len(words) == 1 and words[0] in {"north", "south", "east", "west"}:
return "go", words[0]
if len(words) == 2 and words[0] == "go":
return "go", words[1]
if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}:
return words[0], ""
return "", ""
def save_game(state):
temporary = SAVE_FILE.with_suffix(".tmp")
try:
temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
temporary.replace(SAVE_FILE)
except OSError:
return "Could not save progress. Check that this folder is writable."
return "Progress saved to moonbase-save.json."
def validate_save(data):
if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}:
raise ValueError("expected four state fields")
if type(data["room"]) is not str or data["room"] not in WORLD:
raise ValueError("unknown room")
if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9:
raise ValueError("bad energy")
parts = data["parts"]
if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts):
raise ValueError("unknown part")
if len(parts) != len(set(parts)):
raise ValueError("duplicate part")
if type(data["rescued"]) is not bool:
raise ValueError("bad rescue flag")
if data["rescued"] and not can_repair(data["room"], parts):
raise ValueError("inconsistent rescue")
return data
def load_game(current):
try:
data = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
return validate_save(data), "Saved progress loaded."
except FileNotFoundError:
return current, "No save yet; current progress kept."
except (UnicodeError, json.JSONDecodeError):
return current, "Save is unreadable; current progress kept."
except ValueError:
return current, "Save has invalid data; current progress kept."
except OSError:
return current, "Could not open save; current progress kept."
def mission_snapshot(state):
return state["room"], state["energy"], tuple(state["parts"]), state["rescued"]
def apply(state, verb, argument):
if verb == "look":
return describe(state)
if verb == "go":
return move(state, argument)
if verb == "take":
return collect(state)
if verb == "repair":
return repair(state)
return "Unknown command."
def run(seed=0):
state = new_mission(seed)
print("Moonbase Rescue | Pip on duty")
print(f"Mission seed: {seed}")
print(describe(state))
print("Try look, go, take, repair or quit.")
while not state["rescued"]:
try:
raw = input("Pip> ")
except EOFError:
print("Radio closed.")
break
verb, argument = parse_command(raw)
if verb == "quit":
print("Pip is on standby.")
break
if verb == "save":
print(save_game(state))
continue
if verb == "load":
state, message = load_game(state)
print(message)
continue
print(apply(state, verb, argument))
class MissionTests(unittest.TestCase):
def test_failed_move_costs_nothing(self):
state = new_mission(17)
energy = state["energy"]
self.assertEqual(move(state, "west"), "That route is blocked.")
self.assertEqual(state["energy"], energy)
def test_part_cannot_be_taken_twice(self):
state = new_mission(17)
move(state, "east")
collect(state)
collect(state)
self.assertEqual(state["parts"], ["Coil"])
def test_repair_needs_both_parts(self):
self.assertFalse(can_repair("Beacon", ["Coil"]))
self.assertTrue(can_repair("Beacon", ["Coil", "Cell"]))
def test_invalid_save_rejects_boolean_energy(self):
state = new_mission(17)
state["energy"] = True
with self.assertRaises(ValueError):
validate_save(state)
def test_seed_repeats(self):
self.assertEqual(new_mission(17), new_mission(17))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Moonbase Rescue")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--test", action="store_true")
options = parser.parse_args()
if options.test:
suite = unittest.defaultTestLoader.loadTestsFromTestCase(MissionTests)
result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)
raise SystemExit(0 if result.wasSuccessful() else 1)
run(options.seed)Read the complete checkpoint line by line
Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.
Lines 1–22
-
Line 1
import argparse - Bring in argparse. Its module name gives you access to the tools it contains.
-
Line 2
import random - Bring in random. Its module name gives you access to the tools it contains.
-
Line 3
import json - Bring in json. Its module name gives you access to the tools it contains.
-
Line 4
from pathlib import Path - Bring Path into this file from pathlib. These names can now be used directly.
-
Line 5
import sys - Bring in sys. Its module name gives you access to the tools it contains.
-
Line 6
import unittest - Bring in unittest. Its module name gives you access to the tools it contains.
-
Lines 9–14
WORLD = { "Habitat": {"exits": {"east": "Workshop", "north": "Greenhouse"}, "part": None}, "Workshop": {"exits": {"west": "Habitat", "north": "Beacon"}, "part": "Coil"}, "Greenhouse": {"exits": {"south": "Habitat", "east": "Beacon"}, "part": "Cell"}, "Beacon": {"exits": {"south": "Workshop", "west": "Greenhouse"}, "part": None}, } - Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
-
Line 15
REQUIRED = {"Coil", "Cell"} - Work out the value on the right, then store it in REQUIRED.
-
Line 16
SAVE_FILE = Path("moonbase-save.json") - Work out the value on the right, then store it in SAVE_FILE. Represent a file location so the program can work with it.
-
Line 19
def new_mission(seed=0): - Define new_mission, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
-
Line 20
generator = random.Random(seed) - Work out the value on the right, then store it in generator. Make an independent random generator. Reusing its seed repeats the sequence.
-
Line 21
charge = generator.choice([7, 8, 9]) - Work out the value on the right, then store it in charge. Pick one entry from the sequence using this random generator.
-
Line 22
return {"room": "Habitat", "energy": charge, "parts": [], "rescued": False} - Leave this function now and hand the result back to the line that called it. Each colon pairs a key with its value.
Lines 25–41
-
Line 25
def can_repair(room, parts): - Define can_repair, a reusable piece of the program. Its input names are room, parts. The indented body runs when something calls it.
-
Line 26
return room == "Beacon" and REQUIRED.issubset(parts) - Leave this function now and hand the result back to the line that called it. With and, every check must be true. Check whether every item in this set appears in the other collection.
-
Line 29
def describe(state): - Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Line 30
room, energy, cargo, _ = mission_snapshot(state) - Give each returned value to the matching name, from left to right. Run mission_snapshot with the supplied inputs and come back here when it returns.
-
Line 31
exits = ", ".join(WORLD[room]["exits"]) - Work out the value on the right, then store it in exits. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
-
Line 32
parts = ", ".join(cargo) or "none" - Work out the value on the right, then store it in parts. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
-
Line 33
return f"{room} | energy {energy} | parts {parts} | exits {exits}" - Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
-
Line 36
def collect(state): - Define collect, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Line 37
item = WORLD[state["room"]]["part"] - Work out the value on the right, then store it in item. The brackets look up a dictionary key or a position that starts at zero.
-
Line 38
if item is None: - Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
-
Line 39
return "There is no repair part here." - Leave this function now and hand the result back to the line that called it.
-
Line 40
if item in state["parts"]: - Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection. The brackets look up a dictionary key or a position that starts at zero.
-
Line 41
return f"You already have the {item}." - Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Lines 42–58
-
Line 42
state["parts"].append(item) - Add the value to the end without replacing the earlier entries.
-
Line 43
return f"Collected the {item}." - Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
-
Line 46
def repair(state): - Define repair, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Line 47
if can_repair(state["room"], state["parts"]): - Run the indented block only if this check is true. Run can_repair with the supplied inputs and come back here when it returns. The brackets look up a dictionary key or a position that starts at zero.
-
Line 48
state["rescued"] = True - Work out the value on the right, then store it in state["rescued"].
-
Line 49
return "Beacon restored! Pip has sent the rescue signal." - Leave this function now and hand the result back to the line that called it.
-
Line 50
return "Bring the Coil and the Cell to the Beacon." - Leave this function now and hand the result back to the line that called it.
-
Line 53
def move(state, direction): - Define move, a reusable piece of the program. Its input names are state, direction. The indented body runs when something calls it.
-
Line 54
destination = WORLD[state["room"]]["exits"].get(direction) - Work out the value on the right, then store it in destination. Look up a key. Use the given fallback, or None, if the key is missing.
-
Line 55
if destination is None: - Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
-
Line 56
return "That route is blocked." - Leave this function now and hand the result back to the line that called it.
-
Line 57
if state["energy"] == 0: - Run the indented block only if this check is true. The brackets look up a dictionary key or a position that starts at zero.
-
Line 58
return "Pip is out of energy." - Leave this function now and hand the result back to the line that called it.
Lines 59–75
-
Line 59
state["room"] = destination - Work out the value on the right, then store it in state["room"].
-
Line 60
state["energy"] -= 1 - Update state["energy"] in place in the program’s flow: subtract using the value on the right.
-
Line 61
return f"Moved to {destination}." - Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
-
Line 64
def parse_command(text): - Define parse_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
-
Line 65
words = text.lower().split() - Work out the value on the right, then store it in words. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
-
Line 66
if len(words) == 1 and words[0] in {"north", "south", "east", "west"}: - Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
-
Line 67
return "go", words[0] - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
-
Line 68
if len(words) == 2 and words[0] == "go": - Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
-
Line 69
return "go", words[1] - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
-
Line 70
if len(words) == 1 and words[0] in {"look", "take", "repair", "quit", "save", "load"}: - Run the indented block only if this check is true. With and, every check must be true. Count the characters or items. Membership checks ask whether an item or key is in a collection.
-
Line 71
return words[0], "" - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero.
-
Line 72
return "", "" - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 75
def save_game(state): - Define save_game, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 76–90
-
Line 76
temporary = SAVE_FILE.with_suffix(".tmp") - Work out the value on the right, then store it in temporary. Build a path with a different ending. This does not rename any file yet.
-
Line 77
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 78
temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") - Write text to the file using the chosen encoding. Turn Python data into JSON text. This step does not write a file.
-
Line 79
temporary.replace(SAVE_FILE) - Move the temporary file into the final save location.
-
Line 80
except OSError: - Run this part only when the try block raises OSError.
-
Line 81
return "Could not save progress. Check that this folder is writable." - Leave this function now and hand the result back to the line that called it.
-
Line 82
return "Progress saved to moonbase-save.json." - Leave this function now and hand the result back to the line that called it.
-
Line 85
def validate_save(data): - Define validate_save, a reusable piece of the program. Its input names are data. The indented body runs when something calls it.
-
Line 86
if type(data) is not dict or set(data) != {"room", "energy", "parts", "rescued"}: - Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
-
Line 87
raise ValueError("expected four state fields") - Stop this path and report ValueError("expected four state fields") to whoever called this code.
-
Line 88
if type(data["room"]) is not str or data["room"] not in WORLD: - Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
-
Line 89
raise ValueError("unknown room") - Stop this path and report ValueError("unknown room") to whoever called this code.
-
Line 90
if type(data["energy"]) is not int or not 0 <= data["energy"] <= 9: - Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
Lines 91–105
-
Line 91
raise ValueError("bad energy") - Stop this path and report ValueError("bad energy") to whoever called this code.
-
Line 92
parts = data["parts"] - Work out the value on the right, then store it in parts. The brackets look up a dictionary key or a position that starts at zero.
-
Line 93
if type(parts) is not list or any(type(p) is not str or p not in REQUIRED for p in parts): - Run the indented block only if this check is true. With or, the first true result can settle the check. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value.
-
Line 94
raise ValueError("unknown part") - Stop this path and report ValueError("unknown part") to whoever called this code.
-
Line 95
if len(parts) != len(set(parts)): - Run the indented block only if this check is true. Count the characters or items. Collect distinct values, with no duplicate entries.
-
Line 96
raise ValueError("duplicate part") - Stop this path and report ValueError("duplicate part") to whoever called this code.
-
Line 97
if type(data["rescued"]) is not bool: - Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None. Find the exact type of this value. The brackets look up a dictionary key or a position that starts at zero.
-
Line 98
raise ValueError("bad rescue flag") - Stop this path and report ValueError("bad rescue flag") to whoever called this code.
-
Line 99
if data["rescued"] and not can_repair(data["room"], parts): - Run the indented block only if this check is true. With and, every check must be true. The brackets look up a dictionary key or a position that starts at zero. The word not reverses which result counts as true.
-
Line 100
raise ValueError("inconsistent rescue") - Stop this path and report ValueError("inconsistent rescue") to whoever called this code.
-
Line 101
return data - Leave this function now and hand the result back to the line that called it.
-
Line 104
def load_game(current): - Define load_game, a reusable piece of the program. Its input names are current. The indented body runs when something calls it.
-
Line 105
try: - Attempt the indented instructions. A matching except below can deal with a problem.
Lines 106–122
-
Line 106
data = json.loads(SAVE_FILE.read_text(encoding="utf-8")) - Work out the value on the right, then store it in data. Read JSON text or bytes and turn it back into Python data. Read a file and decode its contents into text.
-
Line 107
return validate_save(data), "Saved progress loaded." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run validate_save with the supplied inputs and come back here when it returns.
-
Line 108
except FileNotFoundError: - Run this part only when the try block raises FileNotFoundError.
-
Line 109
return current, "No save yet; current progress kept." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 110
except (UnicodeError, json.JSONDecodeError): - Run this part only when the try block raises (UnicodeError, json.JSONDecodeError).
-
Line 111
return current, "Save is unreadable; current progress kept." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 112
except ValueError: - Run this part only when the try block raises ValueError.
-
Line 113
return current, "Save has invalid data; current progress kept." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 114
except OSError: - Run this part only when the try block raises OSError.
-
Line 115
return current, "Could not open save; current progress kept." - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
-
Line 118
def mission_snapshot(state): - Define mission_snapshot, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
-
Line 119
return state["room"], state["energy"], tuple(state["parts"]), state["rescued"] - Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. The brackets look up a dictionary key or a position that starts at zero. Collect ordered items in a tuple, whose entries cannot be reassigned.
-
Line 122
def apply(state, verb, argument): - Define apply, a reusable piece of the program. Its input names are state, verb, argument. The indented body runs when something calls it.
Lines 123–137
-
Line 123
if verb == "look": - Run the indented block only if this check is true.
-
Line 124
return describe(state) - Leave this function now and hand the result back to the line that called it. Run describe with the supplied inputs and come back here when it returns.
-
Line 125
if verb == "go": - Run the indented block only if this check is true.
-
Line 126
return move(state, argument) - Leave this function now and hand the result back to the line that called it. Run move with the supplied inputs and come back here when it returns.
-
Line 127
if verb == "take": - Run the indented block only if this check is true.
-
Line 128
return collect(state) - Leave this function now and hand the result back to the line that called it. Run collect with the supplied inputs and come back here when it returns.
-
Line 129
if verb == "repair": - Run the indented block only if this check is true.
-
Line 130
return repair(state) - Leave this function now and hand the result back to the line that called it. Run repair with the supplied inputs and come back here when it returns.
-
Line 131
return "Unknown command." - Leave this function now and hand the result back to the line that called it.
-
Line 134
def run(seed=0): - Define run, a reusable piece of the program. Its input names are seed. The indented body runs when something calls it.
-
Line 135
state = new_mission(seed) - Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
-
Line 136
print("Moonbase Rescue | Pip on duty") - Show the message or value in the output.
-
Line 137
print(f"Mission seed: {seed}") - Show the message or value in the output. Python fills the braces with values before it uses the text.
Lines 138–150
-
Line 138
print(describe(state)) - Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
-
Line 139
print("Try look, go, take, repair or quit.") - Show the message or value in the output.
-
Line 140
while not state["rescued"]: - Check not state["rescued"] before each pass. Repeat the indented work while it is true.
-
Line 141
try: - Attempt the indented instructions. A matching except below can deal with a problem.
-
Line 142
raw = input("Pip> ") - Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
-
Line 143
except EOFError: - Run this part only when the try block raises EOFError.
-
Line 144
print("Radio closed.") - Show the message or value in the output.
-
Line 145
break - Leave the nearest loop immediately and continue after it.
-
Line 146
verb, argument = parse_command(raw) - Give each returned value to the matching name, from left to right. Run parse_command with the supplied inputs and come back here when it returns.
-
Line 147
if verb == "quit": - Run the indented block only if this check is true.
-
Line 148
print("Pip is on standby.") - Show the message or value in the output.
-
Line 149
break - Leave the nearest loop immediately and continue after it.
-
Line 150
if verb == "save": - Run the indented block only if this check is true.
Lines 151–165
-
Line 151
print(save_game(state)) - Show the message or value in the output. Run save_game with the supplied inputs and come back here when it returns.
-
Line 152
continue - Skip the rest of this pass and start the next loop check.
-
Line 153
if verb == "load": - Run the indented block only if this check is true.
-
Line 154
state, message = load_game(state) - Give each returned value to the matching name, from left to right. Run load_game with the supplied inputs and come back here when it returns.
-
Line 155
print(message) - Show the message or value in the output.
-
Line 156
continue - Skip the rest of this pass and start the next loop check.
-
Line 157
print(apply(state, verb, argument)) - Show the message or value in the output. Run apply with the supplied inputs and come back here when it returns.
-
Line 160
class MissionTests(unittest.TestCase): - Define MissionTests, a class that groups related data or behaviour. It starts with the behaviour from unittest.TestCase.
-
Line 161
def test_failed_move_costs_nothing(self): - Define test_failed_move_costs_nothing, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
-
Line 162
state = new_mission(17) - Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
-
Line 163
energy = state["energy"] - Work out the value on the right, then store it in energy. The brackets look up a dictionary key or a position that starts at zero.
-
Line 164
self.assertEqual(move(state, "west"), "That route is blocked.") - Fail the test if the actual and expected values differ. Run move with the supplied inputs and come back here when it returns.
-
Line 165
self.assertEqual(state["energy"], energy) - Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero.
Lines 167–181
-
Line 167
def test_part_cannot_be_taken_twice(self): - Define test_part_cannot_be_taken_twice, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
-
Line 168
state = new_mission(17) - Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
-
Line 169
move(state, "east") - Run move with the supplied inputs and come back here when it returns.
-
Line 170
collect(state) - Run collect with the supplied inputs and come back here when it returns.
-
Line 171
collect(state) - Run collect with the supplied inputs and come back here when it returns.
-
Line 172
self.assertEqual(state["parts"], ["Coil"]) - Fail the test if the actual and expected values differ. The brackets look up a dictionary key or a position that starts at zero.
-
Line 174
def test_repair_needs_both_parts(self): - Define test_repair_needs_both_parts, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
-
Line 175
self.assertFalse(can_repair("Beacon", ["Coil"])) - Fail the test if this value behaves as true. Run can_repair with the supplied inputs and come back here when it returns.
-
Line 176
self.assertTrue(can_repair("Beacon", ["Coil", "Cell"])) - Fail the test if this value behaves as false. Run can_repair with the supplied inputs and come back here when it returns.
-
Line 178
def test_invalid_save_rejects_boolean_energy(self): - Define test_invalid_save_rejects_boolean_energy, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
-
Line 179
state = new_mission(17) - Work out the value on the right, then store it in state. Run new_mission with the supplied inputs and come back here when it returns.
-
Line 180
state["energy"] = True - Work out the value on the right, then store it in state["energy"].
-
Line 181
with self.assertRaises(ValueError): - Check that the indented operation raises the expected error. The test fails if a different error appears or the indented operation succeeds.
Lines 182–197
-
Line 182
validate_save(state) - Run validate_save with the supplied inputs and come back here when it returns.
-
Line 184
def test_seed_repeats(self): - Define test_seed_repeats, a reusable piece of the program. Its input names are self. The indented body runs when something calls it.
-
Line 185
self.assertEqual(new_mission(17), new_mission(17)) - Fail the test if the actual and expected values differ. Run new_mission with the supplied inputs and come back here when it returns.
-
Line 188
if __name__ == "__main__": - Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
-
Line 189
parser = argparse.ArgumentParser(description="Moonbase Rescue") - Work out the value on the right, then store it in parser. Create the object that reads launch options and explains how to use them.
-
Line 190
parser.add_argument("--seed", type=int, default=0) - Register an option that someone can use when starting the program.
-
Line 191
parser.add_argument("--test", action="store_true") - Register an option that someone can use when starting the program.
-
Line 192
options = parser.parse_args() - Work out the value on the right, then store it in options. Read the launch options and put the chosen values into an object.
-
Line 193
if options.test: - Run the indented block only if this check is true.
-
Line 194
suite = unittest.defaultTestLoader.loadTestsFromTestCase(MissionTests) - Work out the value on the right, then store it in suite. Collect the test methods from this test class.
-
Line 195
result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) - Work out the value on the right, then store it in result. Create a runner that reports test results as text. Run the selected operation or collection of tests.
-
Line 196
raise SystemExit(0 if result.wasSuccessful() else 1) - Stop this path and report SystemExit(0 if result.wasSuccessful() else 1) to whoever called this code.
-
Line 197
run(options.seed) - Run run with the supplied inputs and come back here when it returns.
Test the mission
- Run python moonbase.py --test and check there are 5 passing tests.
- Temporarily put the energy subtraction above the blocked-exit guard. Rerun the tests and read the first failure.
- Undo the change. Rerun the tests and then play one route normally.
If something goes wrong
- Tests appear to hang at the radio prompt.
- Include --test, and keep the exit after the test runner so play does not start.
Mission extension
Add a test that builds a state with the same part name twice and expects validation to reject it.