Defensive programming (2)

We have seen the basic idea that we can insert assert statments into code, to check that the results are what we expect, but how can we test software more fully? Can doing this help us avoid bugs in the first place?

One possible approach is test driven development. Many people think this reduces the number of bugs in software as it is written, but evidence for this in the sciences is somewhat limited as it is not always easy to say what the right answer should be before writing the software. Having said that, the tests involved in test driven development are certanly useful even if some of them are written after the software.

We will look at a new (and quite difficult) problem, finding the overlap between ranges of numbers. For example, these could be the dates that different sensors were running, and you need to find the date ranges where all sensors recorded data before running further analysis.

Start off by imagining you have a working function range_overlap that takes a list of tuples. Write some assert statments that would check if the answer from this function is correct. Put these in a function. Think of different cases and about edge cases (which may show a subtle bug).


In [ ]:
def test_range_overlap():