summaryrefslogtreecommitdiff
path: root/lib/testtools/testtools/tests/test_with_with.py
blob: e06adeb1816fec362b6e446299afa15253266f37 (plain)
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
# Copyright (c) 2011 testtools developers. See LICENSE for details.

from __future__ import with_statement

import sys

from testtools import (
    ExpectedException,
    TestCase,
    )
from testtools.matchers import (
    AfterPreprocessing,
    Equals,
    )


class TestExpectedException(TestCase):
    """Test the ExpectedException context manager."""

    def test_pass_on_raise(self):
        with ExpectedException(ValueError, 'tes.'):
            raise ValueError('test')

    def test_pass_on_raise_matcher(self):
        with ExpectedException(
            ValueError, AfterPreprocessing(str, Equals('test'))):
            raise ValueError('test')

    def test_raise_on_text_mismatch(self):
        try:
            with ExpectedException(ValueError, 'tes.'):
                raise ValueError('mismatch')
        except AssertionError:
            e = sys.exc_info()[1]
            self.assertEqual("'mismatch' does not match /tes./", str(e))
        else:
            self.fail('AssertionError not raised.')

    def test_raise_on_general_mismatch(self):
        matcher = AfterPreprocessing(str, Equals('test'))
        value_error = ValueError('mismatch')
        try:
            with ExpectedException(ValueError, matcher):
                raise value_error
        except AssertionError:
            e = sys.exc_info()[1]
            self.assertEqual(matcher.match(value_error).describe(), str(e))
        else:
            self.fail('AssertionError not raised.')

    def test_raise_on_error_mismatch(self):
        try:
            with ExpectedException(TypeError, 'tes.'):
                raise ValueError('mismatch')
        except ValueError:
            e = sys.exc_info()[1]
            self.assertEqual('mismatch', str(e))
        else:
            self.fail('ValueError not raised.')

    def test_raise_if_no_exception(self):
        try:
            with ExpectedException(TypeError, 'tes.'):
                pass
        except AssertionError:
            e = sys.exc_info()[1]
            self.assertEqual('TypeError not raised.', str(e))
        else:
            self.fail('AssertionError not raised.')

    def test_pass_on_raise_any_message(self):
        with ExpectedException(ValueError):
            raise ValueError('whatever')