Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 230 lines (171 sloc) 7.733 kB
3da92b4 initial import; last touched January 2004
darius authored
1 """
2 This is like the unittest module, except that test methods may take
3 arguments. You must declare each argument with a default value which
4 names a test-data generator. The peckcheck module will then peck at
5 your test methods with a bunch of generated values.
6
7 Sample usage:
8
9 from peckcheck import TestCase, an_int, main
10
11 class TestArithmetic(TestCase):
12 def testAddCommutes(self, x=an_int, y=an_int):
13 assert x + y == y + x
14 def testAddAssociates(self, x=an_int, y=an_int, z=an_int):
15 assert x + (y + z) == (x + y) + z
16
17 if __name__ == '__main__':
18 main()
19
20 You can create a test-data generator of your own by defining a
21 function with one parameter, the size bound. For example:
22
23 def a_weekday(size):
24 import random
25 return random.choice(['Sun','Mon','Tue','Wed','Thu','Fri','Sat'])
26
151c747 update email address
darius authored
27 Send bug reports to the author, Darius Bacon <darius@wry.me>.
3da92b4 initial import; last touched January 2004
darius authored
28
29 See http://www.math.chalmers.se/~rjmh/QuickCheck/ for the original
30 automatic specification-based testing tool.
31
32 See http://pyunit.sourceforge.net/ for the unittest module this module
33 is derived from.
34
35 Copyright (c) 1999, 2000, 2001 Steve Purcell
36 Copyright (c) 2004 Darius Bacon
37 This module is free software, and you may redistribute it and/or modify
38 it under the same terms as Python itself, so long as this copyright message
39 and disclaimer are retained in their original form.
40
41 IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
42 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
43 THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
44 DAMAGE.
45
46 THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
47 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
48 PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
49 AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
50 SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
51 """
52
53
54 import random
55 import sys
56 import unittest
57
58
59 # Some random data generators to start with.
60
61 def a_boolean(size):
62 return random.choice([False, True])
63
64 def an_index(size):
65 return random.randint(0, size - 1)
66
67 def an_int(size):
68 return random.randint(-size, size - 1)
69
70 def a_float(size):
71 return (random.random() - 0.5) * (2*size)
72
73 def a_char(size):
74 return chr(random.randint(0, 255))
75
76 def a_printable_char(size):
77 return chr(32 + random.randint(0, 126-32))
78
79 def a_string(size):
80 return string.join(a_list(a_char)(size), '')
81
82 def a_list(generator):
83 return lambda size: [generator(size) for _ in range(size)]
84
85 def a_tuple(generator):
86 return lambda size: tuple(a_list(generator)(size))
87
88 def a_choice(*generators):
89 return lambda size: random.choice(generators)(size)
90
91 def a_tuple_with(*generators):
92 return lambda size: tuple([g(size) for g in generators])
93
94 size = 20 # Default random test case size (with a type-dependent meaning)
95
96
97 # Help functions for writing generators.
98
99 def weighted_choice(choices):
100 total = sum([weight for (weight, _) in choices])
101 i = random.randint(0, total - 1)
102 for weight, choice in choices:
103 i -= weight
104 if i < 0:
105 return choice()
106 raise 'Bug'
107
108
109 # The rest of the code in this module depends on unittest internals.
110
111 class TestCase(unittest.TestCase):
112
113 """A kind of test case that can bind parameters with random values."""
114
115 # It sucks to replicate this entire method from unittest.py just
116 # to hook in the arguments to the testMethod, but this actually
117 # seems like the simplest way to do it without modifying unittest.py.
118
119 def __call__(self, result=None):
120 if result is None: result = self.defaultTestResult()
121 result.startTest(self)
122 testMethod = getattr(self, self.__testMethodName)
123 try:
124 try:
125 self.setUp()
126 except KeyboardInterrupt:
127 raise
128 except:
129 result.addError(self, self.__exc_info())
130 return
131
132 arguments = _generateArguments(testMethod) # Added code
133
134 ok = 0
135 try:
136 testMethod(*arguments) # Changed code
137 ok = 1
138 except self.failureException:
139 result.addFailure(self, self.__exc_info())
140 except KeyboardInterrupt:
141 raise
142 except:
143 result.addError(self, self.__exc_info())
144
145 try:
146 self.tearDown()
147 except KeyboardInterrupt:
148 raise
149 except:
150 result.addError(self, self.__exc_info())
151 ok = 0
152 if ok: result.addSuccess(self)
153 finally:
154 result.stopTest(self)
155
156 def _generateArguments(method):
157 generators = method.im_func.func_defaults or ()
158 return [g(size) for g in generators]
159
160
161 # Misc extra folderol to get the framework to deal with our new test case
162 # type approximately as we'd want.
163
164 num_trials = 100
165
166 class TestLoader(unittest.TestLoader):
167
168 def loadTestsFromTestCase(self, testCaseClass):
169 """Return a suite of all tests cases contained in testCaseClass"""
170 tests = []
171 for name in self.getTestCaseNames(testCaseClass):
172 test = testCaseClass(name)
173 if _expectsArguments(test, name):
174 # Here is what's different from the superclass:
175 # test cases that expect random arguments get repeated
176 # a bunch of times.
177 tests.extend([testCaseClass(name) for _ in range(num_trials)])
178 else:
179 tests.append(test)
180 return self.suiteClass(tests)
181
182 def _expectsArguments(test, name):
183 return not not getattr(test, name).im_func.func_defaults
184
185 class _TextTestResult(unittest._TextTestResult):
186 """A result that prints each failure case only once. With random
187 testing we can get lots of repeats and we don't need all that noise."""
188
189 def printErrorList(self, flavour, errors):
190 seen = {}
191 for test, err in errors:
192 descr = self.getDescription(test)
193 if descr not in seen:
194 seen[descr] = True
195 self.stream.writeln(self.separator1)
196 self.stream.writeln('%s: %s' % (flavour, descr))
197 self.stream.writeln(self.separator2)
198 self.stream.writeln('%s' % err)
199
200 class TextTestRunner(unittest.TextTestRunner):
201
202 def _makeResult(self):
203 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
204
205 defaultTestLoader = TestLoader()
206
207 class TestProgram(unittest.TestProgram):
208
209 # Overridden to stick in our own defaultTestLoader.
210 def __init__(self, module='__main__', defaultTest=None,
211 argv=None, testRunner=None, testLoader=defaultTestLoader):
212 unittest.TestProgram.__init__(self, module, defaultTest, argv,
213 testRunner, testLoader)
214
215 # Overridden to stick in our own TextTestRunner.
216 def runTests(self):
217 if self.testRunner is None:
218 self.testRunner = TextTestRunner(verbosity=self.verbosity)
219 result = self.testRunner.run(self.test)
220 sys.exit(not result.wasSuccessful())
221
222 main = TestProgram
223
224 # We import these remaining names so peckcheck can serve as a drop-in
225 # replacement for the unittest module.
226 from unittest import TestResult, TestSuite, FunctionTestCase
227
228 if __name__ == '__main__':
229 main(module=None)
Something went wrong with that request. Please try again.