This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Debugging and testing

Exercise - writing a test case

face Josiah Wang

As your final exercise for this lesson, let’s get you to practice writing an automated test as part of a ‘test-first’ style of development!

Now, the task is to implement a function to compute the Manhattan distance between two 2D points (x_1, y_1) and (x_2, y_2):

D((x_1, y_1), (x_2, y_2)) = \left|x_1-x_2\right| + \left|y_1-y_2\right|

where \left|x\right| is the absolute value of x.

Manhattan distance

Before you implement manhattan_distance(), first complete the test case test_manhattan_distance() below. It should call manhattan_distance() with some values that you decide, and then use the assert statement to check that the output is as expected (you can manually work out the expected output).

def manhattan_distance(x1, y1, x2, y2):
    pass

def test_manhattan_distance():
    # Complete this first!
    pass

test_manhattan_distance()

Run the test program, and your program should fail! I would be completely shocked if it passes! 😱😱😱

Now, implement manhattan_distance(). Also practice writing your docstring while you are at it! You can actually write this while writing your test!

Then run your test program to make sure the function works correctly! If you do not get any error messages, then your test has passed! Congratulations! 🎊🎊🎊