44.2. WRITING THE UNIT TESTS 3
The smallest unit is obviously the “test”, which is a single method in a TestCase class that
tests the behavior of a small piece of code or a particular aspect of an implementation. The “test
case” is then a collection tests that share the same setup/inputs. On top of all of this sits the “test
suite” which is a collection of test cases and/or other test suites. Test suites combine tests that
should be executed together. With the correct setup (as shown in the example below), you can
then execute test suites. For large projects like Zope 3, it is useful to know that there is also the
concept of a test runner, which manages the test run of all or a set of tests. The runner provides
useful feedback to the application, so that various user interaces can be developed on top of it.
But enough about the theory. In the following example, which you can simply put into the same
file as your code above, you will see a test in common Zope 3 style.
1
import
unittest
2
3
class
SampleTest(unittest.TestCase):
4 """Test the Sample cl ass"""
5
6
def
test_title(
self
):
7 sample = Sample()
8
self
.assertEqual(sample.title, None)
9 sample.title = ’Sample Title’
10
self
.assertEqual(sample.title, ’Sample Title’)
11
12
def
test_getDescription(
self
):
13 sample = Sample()
14
self
.assertEqual(sample.getDescription(), ’’)
15 sample._description = "Description"
16
self
.assertEqual(sample.getDescription(), ’Description’)
17
18
def
test_setDescription(
self
):
19 sample = Sample()
20
self
.assertEqual(sample._description, ’’)
21 sample.setD escriptio n(’Description’)
22
self
.assertEqual(sample._description, ’Description’)
23 sample.setD escriptio n(u’Description2’)
24
self
.assertEqual(sample._description, u’Description2’)
25
self
.assertRaises(AssertionError, sample .setDescription, None)
26
27
28
def
test_sui te() :
29
return
unittest.TestSuite((
30 uni ttest.makeSuite(SampleTest),
31 ))
32
33
if
__name__ == ’__main__’:
34 uni ttest.main(defaultTest=’test_suite’)
. Line 3–4: We usually develop test classes which must inherit from TestCase. While often not
done, it is a good idea to give the class a meaningful docstring that describes the purpose of the
tests it includes.
. Line 6, 12 & 18: When a test case is run, a method called runTests() is executed. While it
is possible to overrride this method to run tests differently, the default option will look for any
method whose name starts with test and execute it as a single test. This way we can create
a “test method” for each aspect, method, function or property of the code to be tested. This
default is very sensible and is used everywhere in Zope 3.