forked from SeattleTestbed/seattlelib_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repyunit.r2py
914 lines (648 loc) · 18.4 KB
/
repyunit.r2py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
"""
<Program Name>
$Id: repyunit.r2py 7356 2014-05-08 09:01:57Z albert $
<Started>
May 23, 2009
<Author>
Michael Phan-Ba <[email protected]>
<Purpose>
Unit testing framework based on JUnit and the Python unittest module.
<Changes>
2009-05-23 Michael Phan-Ba <[email protected]> (#431)
* Initial release
2009-05-24 Michael Phan-Ba <[email protected]>
* Updated documentation per request from Justin Cappos
"""
class repyunit_TestResult(object):
"""
<Purpose>
Hold test result statistics and process test outcomes. Subclasses may extend
this class to provide additional functionality, like printing output.
The test_count instance member holds the number of tests executed;
success_count holds the number of tests executed that were successful,
failure_count holds the number of tests executed that have failed,
error_count holds the number of tests executed that resulted in an error.
<Side Effects>
None.
<Example Use>
test = FoobarTestSuite()
test.run(repyunit_TestResult())
"""
def __init__(self):
"""
<Purpose>
Initialize the statistics variables. Subclasses must call the parent
constructor for proper function.
<Arguments>
None.
<Exceptions>
None.
"""
self.test_count = 0
self.success_count = 0
self.failure_count = 0
self.error_count = 0
def start_test(self, test_case):
"""
<Purpose>
Indicate that a test has been started; called before each test run. This
is a useful method to print test header information.
<Arguments>
test_case:
The repyunit_TestCase instance about to be executed.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
pass
def stop_test(self, test_case):
"""
<Purpose>
Indicate that the test has finished; called after each test run. This is
a useful method to print post-test information.
<Arguments>
test_case:
The repyunit_TestCase instance just finished executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
pass
def add_success(self, test_case):
"""
<Purpose>
Add a successful statistic to the results; called whenever a test exists
successfully. Subclasses must call the parent method for proper function.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
self.test_count += 1
self.success_count += 1
def add_failure(self, test_case, error=None):
"""
<Purpose>
Add a failure statistic to the results; called whenever a test exists with
a failure. Subclasses must call the parent method for proper function.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
self.test_count += 1
self.failure_count += 1
def add_error(self, test_case, error):
"""
<Purpose>
Add an error statistic to the results; called whenever a test exists with
an error. Subclasses must call the parent method for proper function.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
self.test_count += 1
self.error_count += 1
class repyunit_TestCase(object):
"""
<Purpose>
Encapsulate a test case. This class is the workhorse of the module. It
defines the methods required to run tests by extending the class.
Under regular Python, the class name would be extracted automatically, but
this is not possible in Repy. Thus, subclasses must override the
get_class_name method. For the same reasons, subclasses must also override
the get_test_method_names method if run_test is not overwritten or when
additional tests are defined.
<Side Effects>
None.
<Example Use>
class FooTestCase(repyunit_TestCase):
def get_class_name(self):
return "FooTestCase"
def run_test(self):
self.assert_true(True)
test = FooTestCase()
test.run()
"""
def __init__(self, test_method_name="run_test"):
"""
<Purpose>
Initiate a new test case running a particular test.
<Arguments>
test_method_name:
The name of the method to call when running the test.
<Exceptions>
None.
"""
try:
self.run_method = getattr(self, test_method_name)
self.run_method_name = test_method_name
except AttributeError:
raise ValueError, "Invalid test method %s.%s" % \
(self.get_class_name(), test_method_name)
def id(self):
"""
<Purpose>
Return the string class_name.method_name where class_name is the name of
the class of this instance and method_name is the name of the test
function passed to the constructor.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
A unique identifier for this test.
"""
return "%s.%s" % (self.get_class_name(), test_method_name)
def run(self, result=None):
"""
<Purpose>
Run this instance of the test case using the test method name given in the
constructor.
<Arguments>
result:
Optional repyunit_TestResult object to use to collect test statistics.
<Exceptions>
None.
<Side Effects>
The instance is modified by the test method and should not be used to run
another test.
<Returns>
None.
"""
if result is None:
result = repyunit_TestResult()
# notify that the test has started
result.start_test(self)
# set up the test environment
try:
self.set_up()
# fail with an error; consider this an unrecoverable error and abort
except Exception, inst:
result.add_error(self, inst, "unrecoverable error: set_up failed")
return
# run the test
try:
self.run_method()
# fail with a failure if there are any assertion errors
except AssertionError, inst:
result.add_failure(self, inst)
# fail with an error if any other exceptions are raised
except Exception, inst:
result.add_error(self, inst)
return
# end with a success
else:
result.add_success(self)
# clean up the test environment
try:
self.tear_down()
# fail with an error; consider this an unrecoverable error and abort
except Exception, inst:
result.add_error(self, inst, "unrecoverable error: tear_down failed")
return
# notify that the test has ended
result.stop_test(self)
def set_up(self):
"""
<Purpose>
Set up the instance variables used by all tests in this test case. This
method is called before each test run.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
pass
def run_test(self):
"""
<Purpose>
Run a test. This is the default test method. Subclasses must override this
method if it is used, otherwise this test will always fail with an error.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
raise NotImplementedError("run_test is not implemented")
def tear_down(self):
"""
<Purpose>
Clean up resources set up by set_up. If there are persistent resources
that have been allocated for the test, clean up here. This method is
called after each test run.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
pass
def get_test_method_names(self):
"""
<Purpose>
Return a list of method names that implement tests. This list is used to
determine which methods to run as tests. Under regular Python, this
information would be extracted automatically, but access is restricted in
Repy. Thus, subclasses must override this method if methods other than
run_test are used.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
A list of test method names.
"""
return ("run_test",)
def get_class_name(self):
"""
<Purpose>
Return the name of this class. Under regular Python, this information
would be extracted automatically, but access is restricted in Repy. Thus,
subclasses must override this for proper function.
<Arguments>
None.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
The name of this class.
"""
raise NotImplementedError("get_class_name method is not implemented")
def assert_equals(self, expected, actual, msg=None):
"""
<Purpose>
Assert that the actual value is the same as the expected value. Use this
method to assert equality rather than assert(a == b) to print more useful
information on a failure.
<Arguments>
expected:
The expected value.
actual:
The actual value.
msg:
An optional message describing the failure.
<Exceptions>
AssertionError when the values do not match.
<Side Effects>
None.
<Returns>
None.
"""
if expected != actual:
# raise an AssertionError with the given message or the default message
if not msg is None:
msg = "expected %s, but got '%s' instead" % (expected, actual)
raise AssertionError(msg)
def assert_false(self, expr, msg=None):
"""
<Purpose>
Assert that the actual value is false. Use this method to assert equality
rather than assert(!a) to print more useful information on a failure.
<Arguments>
expr:
The expression to consider for assertion.
msg:
An optional message describing the failure.
<Exceptions>
AssertionError when the expression is not false.
<Side Effects>
None.
<Returns>
None.
"""
if expr:
# raise an AssertionError with the given message or the default message
if not msg is None:
msg = "expected false, but got '%s' instead" % expr
raise AssertionError(msg)
def assert_true(self, expr, msg=None):
"""
<Purpose>
Assert that the actual value is true. Use this method to assert equality
rather than assert(a) to print more useful information on a failure.
<Arguments>
expr:
The expression to consider for assertion.
msg:
An optional message describing the failure.
<Exceptions>
AssertionError when the expression is not true.
<Side Effects>
None.
<Returns>
None.
"""
if not expr:
# raise an AssertionError with the given message or the default message
if not msg is None:
msg = "expected true, but got '%s' instead" % expr
raise AssertionError(msg)
def assert_error(self, except_class, func, msg=None, *args, **kwargs):
"""
<Purpose>
Assert that the callable object func raises an exception of type
except_class.
<Arguments>
except_class:
The exception class expected to be raised.
func:
The callable object to execute and test for the appropriate exception.
*args:
Additional arguments to pass to func.
*kwargs:
Additional keyword arguments to pass to func.
msg:
An optional message describing the error.
<Exceptions>
AssertionError when func does not raise the appropriate exception.
Exception when any other exception is raised.
<Side Effects>
None.
<Returns>
None.
"""
try:
func(*args, **kwargs)
except except_class:
return
else:
# raise an AssertionError with the given message or the default message
if not msg is None:
msg = "expected exception %s not raised" % except_class
raise AssertionError(msg)
def fail(self, msg=None):
"""
<Purpose>
Unconditionally fail the test with an optional message.
<Arguments>
msg:
An optional message describing the failure.
<Exceptions>
AssertionError always raised.
<Side Effects>
None.
<Returns>
None.
"""
raise AssertionError(msg)
class repyunit_TestSuite(object):
"""
<Purpose>
Encapsulate a collection of unit tests. This class is used to group together
repyunit_TestCase instances for execution.
<Side Effects>
None.
<Example Use>
suite = repyunit_TestSuite().
suite.add_test(FoobarTest())
suite.add_test(FoobarTest("test_baz"))
suite.run(CustomTestResult())
"""
def __init__(self):
"""
<Purpose>
Initialize the test suite with zero tests. Subclasses must call the parent
constructor for proper function.
<Arguments>
None.
<Exceptions>
None.
"""
self.tests = []
def add_test(self, test_case):
"""
<Purpose>
Add test to the test suite. These tests are run together using the run
method.
<Arguments>
None.
<Exceptions>
TypeError when test is not a repyunit_TestCase or repyunit_TestSuite.
<Side Effects>
None.
<Returns>
None.
"""
# if test_case is a class and subclasses repyunit_TestCase, the test cases
# will need to be loaded
try:
load_tests = issubclass(test_case, repyunit_TestCase)
except TypeError:
load_tests = False
# if test_case is a class and subclasses repyunit_TestCase, it needs to be
# instantiated
try:
instantiate = issubclass(test_case, repyunit_TestSuite)
except TypeError:
instantiate = False
# load test cases from the class if necessary
if load_tests:
test_case = repyunit_load_tests_from_test_case(test_case)
# instantiate the class if necessary
elif instantiate:
test_case = test_case()
# otherwise, check that test_case is either a repyunit_TestCase or
# repyunit_TestSuite
elif not isinstance(test_case,
(repyunit_TestCase, repyunit_TestSuite)):
raise TypeError("%s must be of type %s or %s" % \
(test_case, "repyunit_TestCase",
"repyunit_TestSuite"))
# add this test case
self.tests.append(test_case)
def add_tests(self, test_cases):
"""
<Purpose>
Add many tests to the test suite. These tests are run together using the
run method.
<Arguments>
None.
<Exceptions>
TypeError when test is not a repyunit_TestCase or repyunit_TestSuite.
<Side Effects>
None.
<Returns>
None.
"""
for test_case in test_cases:
self.add_test(test_case)
def run(self, result):
"""
<Purpose>
Run the tests in the suite.
<Arguments>
result:
The repyunit_TestResult object to use to collect test statistics.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
for test in self.tests:
test.run(result)
class _repyunit_TextTestResult(repyunit_TestResult):
"""
<Purpose>
Extend repyunit_TestResult to provide text output facilities.
<Side Effects>
None.
<Example Use>
See repyunit_TestResult.
"""
def start_test(self, test_case):
"""
<Purpose>
Override the parent method to print the test name.
<Arguments>
test_case:
The repyunit_TestCase instance about to be executed.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
print "%s (%s)" % (test_case.run_method_name,
test_case.get_class_name()),
def add_success(self, test_case):
"""
<Purpose>
Extend the parent method to print a success status.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
repyunit_TestResult.add_success(self, test_case)
print "... success"
def add_failure(self, test_case, error=None):
"""
<Purpose>
Extend the parent method to print a failure status.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
repyunit_TestResult.add_failure(self, test_case, error)
print "... failed"
print "\t", error.message
def add_error(self, test_case, error):
"""
<Purpose>
Extend the parent method to print an error status.
<Arguments>
test_case:
The repyunit_TestCase instance executing.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
repyunit_TestResult.add_error(self, test_case, error)
print "... error"
print "\t", error.message
def repyunit_load_tests_from_test_case(test_case):
"""
<Purpose>
Populate a repyunit_TestSuite with all tests from a repyunit_TestCase to run
all the tests automatically.
<Arguments>
test_case:
The repyunit_TestCase from which to populate the repyunit_TestSuite.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
A repyunit_TestSuite loaded with all the tests from the given test case.
"""
# prepare a new test suite to add test cases
suite = repyunit_TestSuite()
# retrieve the test method names
test = test_case()
test_method_names = test.get_test_method_names()
# add the test cases
for test_method_name in test_method_names:
suite.add_test(test_case(test_method_name))
return suite
def repyunit_text_test_run(test_case):
"""
<Purpose>
Run all tests given in test and print statistical information in textual
format.
<Arguments>
test_case:
A repyunit_TestCase or repyunit_TestSuite to run the test(s).
<Exceptions>
None.
<Side Effects>
None.
<Returns>
None.
"""
# use a custom text output result object
result = _repyunit_TextTestResult()
# create a new test suite to populate and run
suite = repyunit_TestSuite()
suite.add_test(test_case)
suite.run(result)
# print test statistics
print "----------------"
print "Ran %d tests: %d successes, %d failures, %d errors" % \
(result.test_count, result.success_count, result.failure_count,
result.error_count)