TactivergeLite

Lite / Intelligent Robotic Systems / Week 1

Tests that catch you before the robot does

Your planner returned a path for six weeks. Then someone added a wall at the map edge and it crashed. Which test would have caught it on day one?

About 35 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Every module you write is a promise to the rest of the program. Tests are how you check that promise automatically, every time anything changes. They are cheapest to write while you still remember what the function is meant to do.

Predict

You test mean(values) with [2, 4, 6] and it returns 4. Which extra test is MOST likely to find a bug?

  1. [1, 2, 3]
  2. [10, 20, 30]
  3. An empty list []
  4. [2, 4, 6] again
Guess first, then reveal

The empty list. Ordinary inputs mostly test the same path through the code. Edges such as empty, zero, one item or a negative value are where divide-by-zero and off-by-one errors hide.

Discover

In the Code Lab, write clamp(value, low, high) and five assert tests: inside the range, below, above, exactly on each limit. Then deliberately break clamp (swap low and high) and run the tests again. How many fail, and do their messages tell you why?

What the interactive shows (text version)

The Code Lab activity can be done on paper: write clamp(value, low, high) and work out by hand the expected result for 50, −5, 130, 0 and 100 with limits 0 and 100. Then imagine low and high swapped inside the function and predict which of the five checks fail.

You can also open the interactive on the full site when you have a faster connection.

Understand

A test is a hand-worked answer

assert clamp(150, 0, 100) == 100 states an answer you worked out without the code. If the code disagrees, Python raises AssertionError. A good test is small, names what it checks and has a known right answer.

Hunt the edges

Bugs cluster at boundaries: the first and last item, exactly on a limit, empty input, zero, negative numbers, a goal surrounded by walls. For each function, list the edges before you write tests; most of your tests should live there.

Importable modules

Code at the top level runs when a module is imported. Put demos and quick checks under if __name__ == "__main__":. That block runs when you execute the file directly, but not when a test or another module imports it.

Explain it another way

Intuitive

A test is like a pre-flight checklist: a list of things that must be true before you trust the aircraft, checked the same way every time.

Technical

Tools such as pytest collect functions named test_* and report each assert that fails along with the values involved. For floating-point results compare with a tolerance: abs(got - want) < 1e-9 or math.isclose(got, want), never ==.

Applied

Safety-critical teams often run thousands of automated tests on every change; a change that breaks one is rejected before it reaches hardware. Your five-line test file is the first step of the same habit.

Worked example 1

Test a clamp function, including both limits, and keep the demo out of imports.

# file: limits.py
def clamp(value, low, high):
    """Return value limited to the range [low, high]. Requires low <= high."""
    if low > high:
        raise ValueError("low must not exceed high")
    return max(low, min(value, high))


if __name__ == "__main__":
    print(clamp(130, 0, 100))   # only runs when limits.py is run directly
from limits import clamp


def test_clamp():
    assert clamp(50, 0, 100) == 50      # inside
    assert clamp(-5, 0, 100) == 0       # below
    assert clamp(130, 0, 100) == 100    # above
    assert clamp(0, 0, 100) == 0        # on the low limit
    assert clamp(100, 0, 100) == 100    # on the high limit


test_clamp()
print("all clamp tests passed")

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

Practice 1. Which input is the best edge case for a function that returns the last reading of a sensor log?
Practice 2. Which test is safest for mean([0.1, 0.2]) (true answer 0.15)?
Practice 3. Why put demo code under if __name__ == "__main__":?
Practice 4. assert clamp(-5, 0, 100) == 0 fails with clamp returning 100. What is the most likely bug?
Practice 5. Which set of tests gives the most confidence for clamp(value, low, high)?

Apply it

For your wheel_rpm or battery_runtime_h function, write a test function with at least five asserts: two normal values worked by hand, one boundary and two that check a ValueError is raised (use try/except and assert inside it). Guard any demo code with if __name__ == "__main__":.

Reflect

Which edge case surprised you most, either because it broke your code or because you hadn't thought of it?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Functions that keep their promisesOne blueprint, many sensors →