-
[[Back To NumPy | Python9-NumPy]] - [[Forward To Home | Home]]
----
If you write your tests comprehensively enough, the expected behaviors that you define in your tests will be the necessary and sufficient set of behaviors your code must perform. Thus, if you write the tests first and program until the tests pass, you will have written exactly enough code to perform the behavior your want and no more. Furthermore, you will have been forced to write your code in a modular enough way to make testing easy now. This will translate into easier testing well into the future.
--------------------------------------------------------------------
+The overlap method takes two rectangles (red and blue) and computes the degree of overlap between them. Save it in overlap.py. A rectangle is defined as a tuple of tuples: ((x_lo,y_lo),(x_hi),(y_hi))
::
- def overlap_broken(red, blue):
+ def overlap(red, blue):
'''Return overlap between two rectangles, or None.'''
((red_lo_x, red_lo_y), (red_hi_x, red_hi_y)) = red
hi_y = min(red_hi_y, blue_hi_y)
return ((lo_x, lo_y), (hi_x, hi_y))
- def overlap_fixed(red, blue):
- '''Return overlap between two rectangles, or None.'''
- ((red_lo_x, red_lo_y), (red_hi_x, red_hi_y)) = red
- ((blue_lo_x, blue_lo_y), (blue_hi_x, blue_hi_y)) = blue
+Now let's create a set of tests for this class. Before we do this, let's think about *how* we might test this method. How should it work?
- if (red_lo_x >= blue_hi_x) or \
- (red_hi_x <= blue_lo_x) or \
- (red_lo_y >= blue_hi_y) or \
- (red_hi_y <= blue_lo_y):
- return None
+This
- lo_x = max(red_lo_x, blue_lo_x)
- lo_y = max(red_lo_y, blue_lo_y)
- hi_x = min(red_hi_x, blue_hi_x)
- hi_y = min(red_hi_y, blue_hi_y)
- return ((lo_x, lo_y), (hi_x, hi_y))
+space
+
+intentionally
+
+left
- overlap = overlap_fixed
+blank
+
+so
+
+you
+
+don't
+
+cheat.
+
+So
+
+don't
+
+look
+
+down
+
+here
+
+until
+
+I
+
+tell
+
+you
+
+to.
::
red = ((0, 3), (2, 5))
blue = ((1, 0), (2, 4))
assert overlap(red, blue) == ((1, 3), (2, 4))
- applebrandi:src guyrt7$
+