Tiny Shelf 40 · Test the shelf before opening

Tiny Shelf Studio · Lesson 40 of 50 · Intermediate to advanced · About 35 min

A new rule can break a shelf that worked yesterday. Design a little suite that reports the exact case that went wrong.

Miniature packaging workshop with coloured paper models, tools and a teal cutting mat.
What you’ll make Run named validation tests, introduce a deliberate error, then confirm the same tests catch it.

Download the projects from the course page. In Godot’s Project Manager, choose Import, select project.godot, and use Run Project (F5). Start from checkpoints/39 when the lesson builds on prior work, or copy the checkpoints/40 folder to try this lesson on its own. Read the file names in the steps before editing.

Prepare shelf fixtures. Include empty and occupied cases. → Try the rule. Check valid and invalid positions. → Report named results. Point out the failed case. → Fix and repeat. Use exactly the same checks.
Prepare shelf fixtures → Try the rule → Report named results → Fix and repeat
Godot checkpoint window for Test the shelf before opening
From the running Godot checkpoint.

Build it step by step

Language and tools in this lesson Array[bool], test fixture, range, String.join, ternary expression, pure function.

  1. Open the design bench

    Import this checkpoint's project.godot into Godot 4.7.2. Open main.gd from FileSystem. Press F5 for the starting view and F8 to stop it. Keep a copy to undo experiments.

    Why it works The checkpoint scene attaches main.gd to a Control. Each test starts from that known version, so compare one change with the original.

  2. Write a rule with a clear answer

    Read can_place with an empty shelf and a slot of 2. Trace the two guards and the final comparison before running.

    return shelf[slot] == ""

    Why it works The rule receives its data as parameters. A true or false result makes the behavior easy to test.

  3. Check the edges before reading a slot

    Find the negative and beyond-shelf guard. Explain why a direct lookup with slot 4 would be unsafe in the practice array.

    if slot < 0 or slot >= shelf.size():

    Why it works The array has four entries and the final valid index is 3. The guard returns before any indexing.

  4. Build a fixture with one occupied cell

    In run_suite, compare empty to partly_filled. Trace the third case and predict the expected result.

    not can_place(partly_filled, 1, broken),

    Why it works The called rule should return false. not flips false to true, meaning the test passed.

  5. Use one output line for each case

    Change Slot 0 is allowed to First slot is allowed. Run and find the revised line without changing case order.

    list.append(icon + WORDS[i])

    Why it works The same loop index reads the Boolean and its caption. This lets the screen describe exactly which case failed.

  6. Prove the tests spot a broken rule

    Tap Insert a fault. Confirm the occupied case fails and other checks still pass. Turn the fault off and rerun.

    var broken := bug_mode.button_pressed

    Why it works This intentional fault returns true after the bounds checks. The occupied test catches it even though valid edge cases still pass.

Watch the values change

  1. Start broken is false.
    What you see. The screen lists six checks passed.
  2. Insert fault The occupied cell incorrectly returns true.
    What you see. Five checks pass and the occupied-slot case prints a cross.
  3. Remove fault The ordinary occupancy check runs again.
    What you see. All six checks pass again.

Predict before you run Should the occupied test expect true because the slot exists?

Reveal the answer

No. The slot may be within bounds while still occupied. A successful refusal is shown as a passed test.

Complete checkpoint

A six-case test bench that goes from 6/6 to 5/6 and back when the intentional occupancy fault is toggled.

main.gd

extends Control

const SLOTS := 4
const WORDS := ["Slot 0 is allowed", "Last slot is allowed", "Occupied slot is refused", "Negative slot is refused", "Beyond shelf is refused", "Wrong shelf size is refused"]
var bug_mode: Button
var status: Label
var lines: Label

func _ready() -> void:
	title_page("RELEASE CHECKS", "Test the shelf before opening", "Introduce a fault and replay the same six test cases.")
	status = label("", Vector2(62, 195), 28, GOLD)
	lines = label("", Vector2(63, 244), 18, PAPER)
	place_button("Run tests", Vector2(647, 242), run_suite)
	bug_mode = place_button("Insert a fault", Vector2(647, 305), run_suite, 205)
	bug_mode.toggle_mode = true
	run_suite()

func can_place(shelf: Array, slot: int, broken: bool = false) -> bool:
	if shelf.size() != SLOTS:
		return false
	if slot < 0 or slot >= shelf.size():
		return false
	if broken:
		return true
	return shelf[slot] == ""

func run_suite() -> void:
	var broken := bug_mode.button_pressed
	var empty := ["", "", "", ""]
	var partly_filled := ["", "moon_milk", "", ""]
	var checks: Array[bool] = [
		can_place(empty, 0, broken),
		can_place(empty, 3, broken),
		not can_place(partly_filled, 1, broken),
		not can_place(empty, -1, broken),
		not can_place(empty, 4, broken),
		not can_place([], 0, broken),
	]
	var list := PackedStringArray()
	var passed := 0
	for i in range(checks.size()):
		if checks[i]:
			passed += 1
		var icon := "✓  " if checks[i] else "×  "
		list.append(icon + WORDS[i])
	status.text = "%d of %d checks passed" % [passed, checks.size()]
	lines.text = "
".join(list)
	bug_mode.text = "Fault: ON" if broken else "Insert a fault"

func _draw() -> void:
	backdrop()
	panel(Rect2(44, 166, 875, 306), Color("#244457"), EDGE)

const PAPER := Color("#fff4de")
const GOLD := Color("#f5bd79")
const SEA := Color("#9ddcd0")
const INK := Color("#172c3c")
const EDGE := Color("#54817f")

func title_page(unit: String, heading: String, subtitle: String) -> void:
	label("TINY SHELF STUDIO  /  " + unit, Vector2(44, 36), 14, GOLD)
	label(heading, Vector2(44, 65), 33)
	label(subtitle, Vector2(46, 119), 16, SEA)

func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:
	var item := Label.new()
	item.text = words
	item.position = at
	item.add_theme_font_size_override("font_size", pixels)
	item.add_theme_color_override("font_color", ink)
	add_child(item)
	return item

func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:
	var control := Button.new()
	control.text = words
	control.position = at
	control.custom_minimum_size = Vector2(width, 48)
	control.add_theme_font_size_override("font_size", 17)
	control.add_theme_color_override("font_color", PAPER)
	control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))
	control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))
	control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))
	control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))
	control.pressed.connect(action)
	add_child(control)
	return control

func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:
	var block := StyleBoxFlat.new()
	block.bg_color = fill
	block.border_color = edge
	block.set_border_width_all(line)
	block.set_corner_radius_all(8)
	return block

func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:
	draw_style_box(style(fill, edge), rect)

func backdrop() -> void:
	draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))
	panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))

func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:
	draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)

GDScript line by line

Follow the line numbers, including the indent at the start of each line. Find the code the game will run first, then look for the function that reacts when you tap or change something.

Read main.gd line by line
  1. extends ControlStarts with Godot's Control type. This script gets the abilities of that type and adds the game's own rules.
  2. const SLOTS := 4The small fixture has four slots. Wrong-size practice arrays should never reach a lookup.
  3. const WORDS := ["Slot 0 is allowed", "Last slot is allowed", "Occupied slot is refused", "Negative slot is refused", "Beyond shelf is refused", "Wrong shelf size is refused"]Creates a constant named WORDS. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  4. var bug_mode: ButtonDeclares bug_mode for later use. A colon followed by a type says which kind of value belongs here.
  5. var status: LabelDeclares status for later use. A colon followed by a type says which kind of value belongs here.
  6. var lines: LabelDeclares lines for later use. A colon followed by a type says which kind of value belongs here.
  7. func _ready() -> void:Godot calls this once after the scene and its children are ready. Use it to set up the room and connect controls.
  8. title_page("RELEASE CHECKS", "Test the shelf before opening", "Introduce a fault and replay the same six test cases.")Calls title_page with the values in its parentheses.
  9. status = label("", Vector2(62, 195), 28, GOLD)Stores the new value in status. The expression calls label with the values in its parentheses.
  10. lines = label("", Vector2(63, 244), 18, PAPER)Stores the new value in lines. The expression calls label with the values in its parentheses.
  11. place_button("Run tests", Vector2(647, 242), run_suite)Calls place_button with the values in its parentheses.
  12. bug_mode = place_button("Insert a fault", Vector2(647, 305), run_suite, 205)Stores the new value in bug_mode. The expression calls place_button with the values in its parentheses.
  13. bug_mode.toggle_mode = trueStores the new value in bug_mode.toggle_mode. The expression uses the yes-or-no value true.
  14. run_suite()Calls run_suite with the values in its parentheses.
  15. func can_place(shelf: Array, slot: int, broken: bool = false) -> bool:Defines can place, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  16. if shelf.size() != SLOTS:Reject a board with an incompatible shape first.
  17. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  18. if slot < 0 or slot >= shelf.size():Refuse negative and too-large slot numbers before indexing into the array.
  19. return falseFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value false.
  20. if broken:Deliberately skip the last rule when fault mode is on, so you can see if the tests catch the omission.
  21. return trueFinishes the function and hands its result back to the caller. The expression uses the yes-or-no value true.
  22. return shelf[slot] == ""A valid shelf address is available only if the stored product ID is empty.
  23. func run_suite() -> void:Defines run suite, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  24. var broken := bug_mode.button_pressedCreates a variable named broken. The expression reads bug_mode.button_pressed. Godot infers the type from the first value.
  25. var empty := ["", "", "", ""]Creates a variable named empty. The expression makes a list whose items keep their order. Godot infers the type from the first value.
  26. var partly_filled := ["", "moon_milk", "", ""]Keep one occupied slot in a separate fixture to catch an overwrite.
  27. var checks: Array[bool] = [Store one true or false test result for every name in WORDS.
  28. can_place(empty, 0, broken),Calls can_place with the values in its parentheses.
  29. can_place(empty, 3, broken),Calls can_place with the values in its parentheses.
  30. not can_place(partly_filled, 1, broken),An occupied cell should be refused. not converts that expected refusal into a passing test.
  31. not can_place(empty, -1, broken),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  32. not can_place(empty, 4, broken),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  33. not can_place([], 0, broken),Continues the same instruction on a new line. This is one of the arguments, data entries or expressions started above.
  34. ]Closes the parentheses, list or dictionary opened above. Any trailing comma separates this item from the next.
  35. var list := PackedStringArray()Collect readable lines so they can appear inside a single label.
  36. var passed := 0Creates a variable named passed. The expression uses the whole number 0. Godot infers the type from the first value.
  37. for i in range(checks.size()):Repeats the indented instructions for each value in range(checks.size()).
  38. if checks[i]:Checks checks[i]. The indented instructions below run only if this test passes.
  39. passed += 1Add one for every true test. Failed cases leave the count unchanged.
  40. var icon := "✓ " if checks[i] else "× "Creates a variable named icon. The expression chooses one of two values by checking the condition in the middle. Godot infers the type from the first value.
  41. list.append(icon + WORDS[i])Join the result mark with the case's name using the same index for both.
  42. status.text = "%d of %d checks passed" % [passed, checks.size()]Updates status.text, which controls the words a player sees. The expression uses the text inside the quotes.
  43. lines.text = "Put one result on each line by joining the list with a newline marker.
  44. ".join(list)Continues this part of the script. Read the expression on this line in the context of the nearby declaration or function.
  45. bug_mode.text = "Fault: ON" if broken else "Insert a fault"Updates bug_mode.text, which controls the words a player sees. The expression chooses one of two values by checking the condition in the middle.
  46. func _draw() -> void:Godot calls this when the node needs drawing. The instructions inside paint the current state.
  47. backdrop()Calls backdrop with the values in its parentheses.
  48. panel(Rect2(44, 166, 875, 306), Color("#244457"), EDGE)Calls panel with the values in its parentheses.
  49. const PAPER := Color("#fff4de")Creates a constant named PAPER. The expression builds a colour from these values. Godot infers the type from the first value.
  50. const GOLD := Color("#f5bd79")Creates a constant named GOLD. The expression builds a colour from these values. Godot infers the type from the first value.
  51. const SEA := Color("#9ddcd0")Creates a constant named SEA. The expression builds a colour from these values. Godot infers the type from the first value.
  52. const INK := Color("#172c3c")Creates a constant named INK. The expression builds a colour from these values. Godot infers the type from the first value.
  53. const EDGE := Color("#54817f")Creates a constant named EDGE. The expression builds a colour from these values. Godot infers the type from the first value.
  54. func title_page(unit: String, heading: String, subtitle: String) -> void:Defines title page, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  55. label("TINY SHELF STUDIO / " + unit, Vector2(44, 36), 14, GOLD)Make a small line above the main heading so you can tell which checkpoint is open.
  56. label(heading, Vector2(44, 65), 33)Calls label with the values in its parentheses.
  57. label(subtitle, Vector2(46, 119), 16, SEA)Calls label with the values in its parentheses.
  58. func label(words: String, at: Vector2, pixels: int = 20, ink: Color = PAPER) -> Label:Defines label, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  59. var item := Label.new()Creates a variable named item. The expression creates a new Label object. Godot infers the type from the first value.
  60. item.text = wordsUpdates item.text, which controls the words a player sees. The expression reads words.
  61. item.position = atUpdates item.position, which controls the node's local x and y location. The expression reads at.
  62. item.add_theme_font_size_override("font_size", pixels)This Label has its own readable type size. Changing that value leaves the other labels alone.
  63. item.add_theme_color_override("font_color", ink)This label keeps the chosen text ink even when the default theme changes.
  64. add_child(item)Adds the new node to the scene tree so that Godot can run and draw it.
  65. return itemFinishes the function and hands its result back to the caller. The expression reads item.
  66. func place_button(words: String, at: Vector2, action: Callable, width: float = 170.0) -> Button:Defines place button, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  67. var control := Button.new()Creates a variable named control. The expression creates a new Button object. Godot infers the type from the first value.
  68. control.text = wordsUpdates control.text, which controls the words a player sees. The expression reads words.
  69. control.position = atUpdates control.position, which controls the node's local x and y location. The expression reads at.
  70. control.custom_minimum_size = Vector2(width, 48)Give the button room for its label and an easy target for taps. Containers and layouts can allocate more space.
  71. control.add_theme_font_size_override("font_size", 17)Calls control.add_theme_font_size_override with the values in its parentheses.
  72. control.add_theme_color_override("font_color", PAPER)Calls control.add_theme_color_override with the values in its parentheses.
  73. control.add_theme_stylebox_override("normal", style(Color("#244557"), EDGE))Calls control.add_theme_stylebox_override with the values in its parentheses.
  74. control.add_theme_stylebox_override("hover", style(Color("#365a62"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  75. control.add_theme_stylebox_override("pressed", style(Color("#315b56"), SEA))Calls control.add_theme_stylebox_override with the values in its parentheses.
  76. control.add_theme_stylebox_override("focus", style(Color.TRANSPARENT, GOLD, 3))Draw a gold outline around keyboard focus. Other button styles can still indicate hover and press independently.
  77. control.pressed.connect(action)pressed fires on a successful control activation. Godot calls the function passed in without running it at setup time.
  78. add_child(control)Adds the new node to the scene tree so that Godot can run and draw it.
  79. return controlFinishes the function and hands its result back to the caller. The expression reads control.
  80. func style(fill: Color, edge: Color, line: int = 1) -> StyleBoxFlat:Defines style, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  81. var block := StyleBoxFlat.new()Creates a variable named block. The expression creates a new StyleBoxFlat object. Godot infers the type from the first value.
  82. block.bg_color = fillStores the new value in block.bg_color. The expression reads fill.
  83. block.border_color = edgeStores the new value in block.border_color. The expression reads edge.
  84. block.set_border_width_all(line)Apply one border line width to all four edges of the card.
  85. block.set_corner_radius_all(8)Round each corner of this reusable style by eight pixels.
  86. return blockFinishes the function and hands its result back to the caller. The expression reads block.
  87. func panel(rect: Rect2, fill: Color, edge: Color = EDGE) -> void:Defines panel, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  88. draw_style_box(style(fill, edge), rect)Calls draw_style_box with the values in its parentheses.
  89. func backdrop() -> void:Defines backdrop, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  90. draw_rect(Rect2(Vector2.ZERO, size), Color("#102333"))Paints a rectangle at the given position and size.
  91. panel(Rect2(22, 19, size.x - 44, size.y - 38), Color("#183344"), Color("#325665"))Subtract space on both sides of the canvas. As the window changes, the outer frame fits within it.
  92. func paint_words(words: String, at: Vector2, pixels: int = 16, ink: Color = PAPER) -> void:Defines paint words, a reusable set of instructions. Parameters between the parentheses receive inputs. A return type after the arrow tells you which kind of result to expect.
  93. draw_string(ThemeDB.fallback_font, at, words, HORIZONTAL_ALIGNMENT_LEFT, -1, pixels, ink)Godot draws the words from the baseline at the supplied pixel position using its fallback typeface.

Find and fix a bug

If several test labels do not match their results after editing, compare the order and length of WORDS and checks. The shared index must identify the same case in both.

Try a change

Write a helper that checks whether all four spots are filled. Give it an empty, partly filled and full fixture, and report each result by name.