I have a number of cases where an unmatched closing delimiter causes the function to raise an IndexError:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/tmp/delimiters.py", line 10, in check_match
if working_set[-1] != delimiters_map[v]:
IndexError: list index out of range
In particular, it crashes whenever there’s no opening delimiter but there is at least one closing delimiter. Trying to look up the previous opening delimiter will fail, and we get the crash.
This diff fixes the bug, and after that I’m unable to find any other crashes:
- if working_set[-1] != delimiters_map[v]:
+ if (not working_set) or (working_set[-1] != delimiters_map[v]):
How did I find this bug? (Hint: I’m not just lucky)
I used the Hypothesis testing library (mild disclaimer: I’m friends with the library author, and I’ve done bits of work on it).
Your function should always return either
False, whatever text we give it as input. We can write a test with Hypothesis that asserts this is the case:
from hypothesis import given, strategies as st
"""`check_match()` returns a boolean for any given text input."""
assert check_match(xs) in (True, False)
When you run this with py.test, it tries 200 different, randomly-generated strings and quickly discovers the bug.
Once I patched the bug, I ran this test a bunch more times, and was unable to find any other crashes. That suggests any remaining crashers are at least rare, if even extant.
(Writing a test with Hypothesis that asserts a stronger form of correctness than “doesn’t crash” is left as an exercise for the reader.)