16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Running this test script will, of course, simply give us an exception about the module<br />

my_math not existing. Methods such as failUnless check a condition <strong>to</strong> determine whether the<br />

given test succeeds or fails. (There are many others, such as failIf, failUnlessEqual, failIfEqual,<br />

and others. See the Table 16-1 for a brief overview, or the <strong>Python</strong> Library Reference, http://<br />

python.org/doc/lib/testcase-objects.html, for more information.)<br />

Table 16-1. Some Useful TestCase Methods<br />

Method<br />

assert_(expr[, msg])<br />

failUnless(expr[, msg])<br />

assertEqual(x, y[, msg])<br />

failUnlessEqual(x, y[, msg])<br />

assertNotEqual(x, y[, msg])<br />

failIfEqual(x, y[, msg])<br />

assertAlmostEqual(x, y[, places[, msg]])<br />

failUnlessAlmostEqual(x, y[, places[, msg]])<br />

assertNotAlmostEqual(x, y[, places[, msg]])<br />

failIfAlmostEqual(x, y[, msg])<br />

assertRaises(exc, callable, ...)<br />

failUnlessRaises(exc, callable, ...)<br />

failIf(expr[, msg])<br />

fail([msg])<br />

Description<br />

Fail if the expression is false, optionally<br />

giving a message.<br />

Same as assert_.<br />

Fail if two values are different, printing<br />

both values in traceback.<br />

Same as assertEqual.<br />

The opposite of assertEqual.<br />

The same as assertNotEqual.<br />

Similar <strong>to</strong> assertEqual, but with some<br />

leeway for floats.<br />

The same as assertAlmostEqual.<br />

The opposite of assertAlmostEqual.<br />

The same as assertNotAlmostEqual.<br />

Fail unless the callable raises exc when<br />

called (with optional args).<br />

Same as assertRaises.<br />

Opposite of assert_.<br />

Unconditional failure—with an optional<br />

message, as other methods.<br />

The unittest module distinguishes between errors, where an exception is raised, and failures,<br />

which results from calls <strong>to</strong> failUnless and the like; the next step is <strong>to</strong> write skele<strong>to</strong>n code,<br />

so we don’t get errors—only failures. This simply means <strong>to</strong> create a module called my_math (that<br />

is, a file called my_math.py) containing the following:<br />

def product(x, y):<br />

pass<br />

All filler, no fun. If you run the test now, you should get two FAIL messages, like this:

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

Saved successfully!

Ooh no, something went wrong!