Testing for file existence

Finally, we can see one more very useful type of assertion by writing a test to verify that analyze_text() doesn't delete the file — a reasonable requirement for the function!:

# text_analyzer.py

class TextAnalysisTests(unittest.TestCase):
. . .
def test_no_deletion(self):
"Check that the function doesn't delete the input file."
analyze_text(self.filename)
self.assertTrue(os.path.exists(self.filename))

The TestCase.assertTrue() function simply checks that the value passed to it evaluates to True. There is an equivalent assertFalse() which does the same test for
false values.

As you probably expect, this test passes already as well:

% python text_analyzer.py
.....
----------------------------------------------------------------------
Ran 5 tests in 0.002s

OK

So now we've got a useful, passing set of tests! This example is small, but it demonstrates many of the important parts of the unittest module. There are many more parts to the unittest module, but you can get quite far using just the techniques we've seen here.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset