Testing
How to Write Test Cases That Catch Bugs
Passing the sample tests proves very little: they're chosen to explain the problem, not to break your solution. Good test cases are the ones that would fail a wrong program. Here's a short method for writing them, used by competitive programmers and in coding interviews alike.
Start with the samples, then go beyond them
Add the problem's sample inputs and outputs first, so you know the basics work. Then add tests in each of the categories below, from cheapest to most thorough.
Edge and boundary cases
- Minimum sizes: an empty list, a single element, n = 1.
- Maximum values: the largest numbers the constraints allow, to catch overflow.
- Identical values: all elements equal, or a string of one repeated character.
- Sorted and reverse-sorted input, which break many greedy and pivot-based solutions.
- Negative numbers and zero, if the constraints allow them.
- The exact boundary of a condition: if the rule is "at least k", test k − 1, k and k + 1.
Tests you work out by hand
Write two or three small inputs whose answers you can work out on paper, especially ones that look like the tricky part of the problem. If your program disagrees with your paper answer, one of them is wrong, and finding out which is the fastest way to understand the problem.
Large tests for speed
Generate an input at the maximum size to check the time limit before the judge does. Only the size matters here, not the answer: you're checking that the program finishes in time.
# Generate a maximum-size input: n = 200000 values up to 10^9
import random
n = 200_000
print(n)
print(" ".join(str(random.randint(1, 10**9)) for _ in range(n)))Stress testing against a brute force
When a solution fails and you can't see why, write the slowest, most obviously correct version (try every possibility), then run both on many small random inputs and stop at the first difference. That input is your bug, and it's small enough to debug by hand.
- Write
brute: simple and correct, however slow. - Write a generator for small random inputs (n up to 6 or so).
- Run both on each input and compare. The first mismatch is a test case worth keeping.
Keep the tests that failed
Every input that once broke your code is a regression test. Keep it with the project so the next change can't quietly bring the bug back.
In omni compiler, tests live with the project: add up to 100 test cases, each an input and an expected output, and run them all at once. Each gets its own verdict, so you can see exactly which case broke.
Not sure what a verdict means? See judge verdicts explained.