~lifeless/debian/sid/python-testtools/packaging

« back to all changes in this revision

Viewing changes to testtools/tests/test_testtools.py

  • Committer: Robert Collins
  • Date: 2009-12-15 23:06:25 UTC
  • mfrom: (16.2.34 0.9.2)
  • mto: This revision was merged to the branch mainline in revision 20.
  • Revision ID: robertc@robertcollins.net-20091215230625-pirbmqe3siih6ome
Tags: upstream-0.9.2
ImportĀ upstreamĀ versionĀ 0.9.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
    skipUnless,
15
15
    testcase,
16
16
    )
 
17
from testtools.matchers import (
 
18
    Equals,
 
19
    )
17
20
from testtools.tests.helpers import (
 
21
    an_exc_info,
18
22
    LoggingResult,
19
23
    Python26TestResult,
20
24
    Python27TestResult,
66
70
        ret = ('orange', 42)
67
71
        try:
68
72
            self.assertRaises(RuntimeError, lambda: ret)
69
 
        except self.failureException, e:
 
73
        except self.failureException:
70
74
            # We expected assertRaises to raise this exception.
 
75
            e = sys.exc_info()[1]
71
76
            self.assertEqual(
72
77
                '%s not raised, %r returned instead.'
73
78
                % (self._formatTypes(RuntimeError), ret), str(e))
91
96
        def raiseError():
92
97
            try:
93
98
                raise RuntimeError('Deliberate error')
94
 
            except RuntimeError, e:
95
 
                raisedExceptions.append(e)
 
99
            except RuntimeError:
 
100
                raisedExceptions.append(sys.exc_info()[1])
96
101
                raise
97
102
 
98
103
        exception = self.assertRaises(RuntimeError, raiseError)
235
240
 
236
241
    def test_assertThat_matches_clean(self):
237
242
        class Matcher:
238
 
            def matches(self, foo):
239
 
                return True
 
243
            def match(self, foo):
 
244
                return None
240
245
        self.assertThat("foo", Matcher())
241
246
 
242
247
    def test_assertThat_mismatch_raises_description(self):
243
248
        calls = []
 
249
        class Mismatch:
 
250
            def __init__(self, thing):
 
251
                self.thing = thing
 
252
            def describe(self):
 
253
                calls.append(('describe_diff', self.thing))
 
254
                return "object is not a thing"
244
255
        class Matcher:
245
 
            def matches(self, thing):
 
256
            def match(self, thing):
246
257
                calls.append(('match', thing))
247
 
                return False
 
258
                return Mismatch(thing)
248
259
            def __str__(self):
249
260
                calls.append(('__str__',))
250
261
                return "a description"
251
 
            def describe_difference(self, thing):
252
 
                calls.append(('describe_diff', thing))
253
 
                return "object is not a thing"
254
262
        class Test(TestCase):
255
263
            def test(self):
256
264
                self.assertThat("foo", Matcher())
296
304
 
297
305
    def assertTestLogEqual(self, messages):
298
306
        """Assert that the call log equals `messages`."""
299
 
        self.assertEqual(messages, self.test._calls)
 
307
        case = self._result_calls[0][1]
 
308
        self.assertEqual(messages, case._calls)
300
309
 
301
310
    def logAppender(self, message):
302
 
        """Return a cleanup that appends `message` to the tests log.
 
311
        """A cleanup that appends `message` to the tests log.
303
312
 
304
313
        Cleanups are callables that are added to a test by addCleanup. To
305
314
        verify that our cleanups run in the right order, we add strings to a
320
329
        # runs.
321
330
        self.test.addCleanup(self.logAppender, 'cleanup')
322
331
        self.test.run(self.logging_result)
323
 
        self.assertTestLogEqual(['setUp', 'runTest', 'cleanup', 'tearDown'])
 
332
        self.assertTestLogEqual(['setUp', 'runTest', 'tearDown', 'cleanup'])
324
333
 
325
334
    def test_add_cleanup_called_if_setUp_fails(self):
326
335
        # Cleanup functions added with 'addCleanup' are called even if setUp
347
356
        self.test.addCleanup(self.logAppender, 'second')
348
357
        self.test.run(self.logging_result)
349
358
        self.assertTestLogEqual(
350
 
            ['setUp', 'runTest', 'second', 'first', 'tearDown'])
 
359
            ['setUp', 'runTest', 'tearDown', 'second', 'first'])
351
360
 
352
361
    def test_tearDown_runs_after_cleanup_failure(self):
353
362
        # tearDown runs even if a cleanup function fails.
362
371
        self.test.addCleanup(self.logAppender, 'second')
363
372
        self.test.run(self.logging_result)
364
373
        self.assertTestLogEqual(
365
 
            ['setUp', 'runTest', 'second', 'first', 'tearDown'])
 
374
            ['setUp', 'runTest', 'tearDown', 'second', 'first'])
366
375
 
367
376
    def test_error_in_cleanups_are_captured(self):
368
377
        # If a cleanup raises an error, we want to record it and fail the the
399
408
        """
400
409
        result = ExtendedTestResult()
401
410
        case.run(result)
 
411
        case = result._events[0][1]
402
412
        expected = [
403
413
            ('startTest', case),
404
414
            (expected_outcome, case),
415
425
 
416
426
    def get_content(self):
417
427
        return content.Content(
418
 
            content.ContentType("text", "foo"), lambda:['foo'])
 
428
            content.ContentType("text", "foo"), lambda: ['foo'])
419
429
 
420
430
 
421
431
class TestExpectedFailure(TestWithDetails):
432
442
        case = self.make_unexpected_case()
433
443
        result = Python27TestResult()
434
444
        case.run(result)
 
445
        case = result._events[0][1]
435
446
        self.assertEqual([
436
447
            ('startTest', case),
437
448
            ('addUnexpectedSuccess', case),
442
453
        case = self.make_unexpected_case()
443
454
        result = ExtendedTestResult()
444
455
        case.run(result)
 
456
        case = result._events[0][1]
445
457
        self.assertEqual([
446
458
            ('startTest', case),
447
459
            ('addUnexpectedSuccess', case, {}),
491
503
        self.assertEqual(2, two)
492
504
 
493
505
    def test_getUniqueString(self):
494
 
        # getUniqueString returns the current test name followed by a unique
 
506
        # getUniqueString returns the current test id followed by a unique
495
507
        # integer.
496
508
        name_one = self.getUniqueString()
497
 
        self.assertEqual('%s-%d' % (self._testMethodName, 1), name_one)
 
509
        self.assertEqual('%s-%d' % (self.id(), 1), name_one)
498
510
        name_two = self.getUniqueString()
499
 
        self.assertEqual('%s-%d' % (self._testMethodName, 2), name_two)
 
511
        self.assertEqual('%s-%d' % (self.id(), 2), name_two)
500
512
 
501
513
 
502
514
class TestCloneTestWithNewId(TestCase):
592
604
    def test_skip_causes_skipException(self):
593
605
        self.assertRaises(self.skipException, self.skip, "Skip this test")
594
606
 
 
607
    def test_skip_without_reason_works(self):
 
608
        class Test(TestCase):
 
609
            def test(self):
 
610
                raise self.skipException()
 
611
        case = Test("test")
 
612
        result = ExtendedTestResult()
 
613
        case.run(result)
 
614
        self.assertEqual('addSkip', result._events[1][0])
 
615
        self.assertEqual('no reason given.',
 
616
            ''.join(result._events[1][2]['reason'].iter_text()))
 
617
 
595
618
    def test_skipException_in_setup_calls_result_addSkip(self):
596
619
        class TestThatRaisesInSetUp(TestCase):
597
620
            def setUp(self):
603
626
        result = LoggingResult(calls)
604
627
        test = TestThatRaisesInSetUp("test_that_passes")
605
628
        test.run(result)
606
 
        self.assertEqual([('startTest', test),
607
 
            ('addSkip', test, "Text attachment: reason\n------------\n"
608
 
             "skipping this test\n------------\n"), ('stopTest', test)],
 
629
        case = result._events[0][1]
 
630
        self.assertEqual([('startTest', case),
 
631
            ('addSkip', case, "Text attachment: reason\n------------\n"
 
632
             "skipping this test\n------------\n"), ('stopTest', case)],
609
633
            calls)
610
634
 
611
635
    def test_skipException_in_test_method_calls_result_addSkip(self):
615
639
        result = Python27TestResult()
616
640
        test = SkippingTest("test_that_raises_skipException")
617
641
        test.run(result)
618
 
        self.assertEqual([('startTest', test),
619
 
            ('addSkip', test, "Text attachment: reason\n------------\n"
620
 
             "skipping this test\n------------\n"), ('stopTest', test)],
 
642
        case = result._events[0][1]
 
643
        self.assertEqual([('startTest', case),
 
644
            ('addSkip', case, "Text attachment: reason\n------------\n"
 
645
             "skipping this test\n------------\n"), ('stopTest', case)],
621
646
            result._events)
622
647
 
623
648
    def test_skip__in_setup_with_old_result_object_calls_addSuccess(self):
672
697
        self.assertEqual('addSuccess', result._events[1][0])
673
698
 
674
699
 
 
700
class TestOnException(TestCase):
 
701
 
 
702
    def test_default_works(self):
 
703
        events = []
 
704
        class Case(TestCase):
 
705
            def method(self):
 
706
                self.onException(an_exc_info)
 
707
                events.append(True)
 
708
        case = Case("method")
 
709
        case.run()
 
710
        self.assertThat(events, Equals([True]))
 
711
 
 
712
    def test_added_handler_works(self):
 
713
        events = []
 
714
        class Case(TestCase):
 
715
            def method(self):
 
716
                self.addOnException(events.append)
 
717
                self.onException(an_exc_info)
 
718
        case = Case("method")
 
719
        case.run()
 
720
        self.assertThat(events, Equals([an_exc_info]))
 
721
 
 
722
    def test_handler_that_raises_is_not_caught(self):
 
723
        events = []
 
724
        class Case(TestCase):
 
725
            def method(self):
 
726
                self.addOnException(events.index)
 
727
                self.assertRaises(ValueError, self.onException, an_exc_info)
 
728
        case = Case("method")
 
729
        case.run()
 
730
        self.assertThat(events, Equals([]))
 
731
 
 
732
 
675
733
def test_suite():
676
734
    from unittest import TestLoader
677
735
    return TestLoader().loadTestsFromName(__name__)