04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

346 CHAPTER 16 ■ TESTING, 1-2-3<br />

Trying: square(3)<br />

Expecting: 9<br />

ok<br />

0 of 2 examples failed in my_math.square.__doc__<br />

1 items had no tests:<br />

test<br />

1 items passed all tests:<br />

2 tests in my_math.square<br />

2 tests in 2 items.<br />

2 passed and 0 failed.<br />

Test passed.<br />

As you can see, a lot happened behind the scenes. The testmod function checks both the<br />

module docstring (which, as you can see, contains no tests) and the function docstring (which<br />

contains two tests, both of which succeed).<br />

With this in place, you can safely change your code. Let’s say that you want to use the<br />

Python exponentiation operator instead of plain multiplication, and use x**2 instead of x*x.<br />

You edit the code, but accidentally forget to enter the number 2, and end up with x**x. Try it,<br />

and then run the script to test the code. What happens? This is the output you get:<br />

*****************************************************************<br />

Failure in example: square(3)<br />

from line #5 of my_math.square<br />

Expected: 9<br />

Got: 27<br />

*****************************************************************<br />

1 items had failures:<br />

1 of 2 in my_math.square<br />

***Test Failed*** 1 failures.<br />

So the bug was caught, and you get a very clear description of what is wrong. Fixing the<br />

problem shouldn’t be difficult now.<br />

■Caution Don’t trust your tests blindly, and be sure to test enough cases. As you can see, the test using<br />

square(2) does not catch the bug because for x==2, x**2 and x**x are the same thing!<br />

For more information about the doctest module, you should again check out the library<br />

reference (http://python.org/doc/lib/module-doctest.html).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!