how to make all assertions in a unit test execute
Ben Finney
ben+python at benfinney.id.au
Sat Oct 16 18:05:39 EDT 2010
jimgardener <jimgardener at gmail.com> writes:
> class FileNamesTest(unittest.TestCase):
> def setUp(self):
> self.dirname='/home/me/data'
>
> def test_get_filenames(self):
> innerstr='tom'
> matching_names=get_filenames(self.dirname,innerstr)
> self.assertEquals(1,len(matching_names))
>
> innerstr='myself'
> matching_names=get_filenames(self.dirname,innerstr)
> self.assertEquals(0,len(matching_names))
>
> innerstr='jerry'
> matching_names=get_filenames(self.dirname,innerstr)
> self.assertEquals(3,len(matching_names))
A side point unrelated to the question: your code will be easier to read
if you follow PEP 8, specifically its recommendations regarding spaces
around syntax (like ‘=’ and ‘,’).
> when I run the unittest, if the test fails at the first assertion,the
> other assertions are not executed at all.
Yes, that's by design. Each function in a TestCase subclass is a test
case; the function goes about testing *one thing*, and ends as soon as
the test passes or fails.
> How do I organize the test so that all assertions can run?
Every test case should test exactly one true-or-false question. Name
each test case after the assertion it's making, so the unittest output
makes sense.
class get_filenames_TestCase(unittest.TestCase):
def setUp(self):
self.dirname = '/home/me/data'
def test_one_match_returns_one_item(self):
innerstr = 'tom'
matching_names = get_filenames(self.dirname, innerstr)
self.assertEquals(1, len(matching_names))
def test_no_match_returns_empty_sequence(self):
innerstr = 'myself'
matching_names = get_filenames(self.dirname, innerstr)
self.assertEquals(0, len(matching_names))
def test_three_matches_returns_three_items(self):
innerstr = 'jerry'
matching_names = get_filenames(self.dirname, innerstr)
self.assertEquals(3, len(matching_names))
Also, be aware that each test case should be independent of the others:
any common set-up should be in a fixture, created in ‘setUp’ and reset
(if necessary) in ‘tearDown’.
--
\ “I do not believe in forgiveness as it is preached by the |
`\ church. We do not need the forgiveness of God, but of each |
_o__) other and of ourselves.” —Robert G. Ingersoll |
Ben Finney
More information about the Python-list
mailing list