Statistics
| Revision:

gvsig-scripting / org.gvsig.scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.app / org.gvsig.scripting.app.mainplugin / src / main / resources-plugin / scripting / lib / cssutils / tests / basetest.py @ 475

History | View | Annotate | Download (5.9 KB)

1
"""Base class for all tests"""
2

    
3
import logging
4
import os
5
import sys
6
import StringIO
7
import unittest
8
import urllib2
9
from email import message_from_string, message_from_file
10

    
11
# add src to PYTHONPATH
12
sys.path.append(os.path.join(os.path.abspath('.'), '..'))
13

    
14
import cssutils
15

    
16

    
17
PY2x = sys.version_info < (3,0)
18

    
19
def msg3x(msg):
20
    """msg might contain unicode repr `u'...'` which in py3 is `u'...`
21
    needed by tests using ``assertRaisesMsg``"""
22
    if not PY2x and msg.find("u'"):
23
        msg = msg.replace("u'", "'")
24
    return msg
25

    
26

    
27
class BaseTestCase(unittest.TestCase):
28

    
29
    def _tempSer(self):
30
        "Replace default ser with temp ser."
31
        self._ser = cssutils.ser
32
        cssutils.ser = cssutils.serialize.CSSSerializer()
33

    
34
    def _restoreSer(self):
35
        "Restore the default ser."
36
        cssutils.ser = self._ser
37

    
38
    def setUp(self):
39
        # a raising parser!!!
40
        cssutils.log.raiseExceptions = True
41
        cssutils.log.setLevel(logging.FATAL)
42
        self.p = cssutils.CSSParser(raiseExceptions=True)
43

    
44
    def tearDown(self):
45
        if hasattr(self, '_ser'):
46
            self._restoreSer()
47

    
48
    def assertRaisesEx(self, exception, callable, *args, **kwargs):
49
        """
50
        from
51
        http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970
52
        """
53
        if "exc_args" in kwargs:
54
            exc_args = kwargs["exc_args"]
55
            del kwargs["exc_args"]
56
        else:
57
            exc_args = None
58
        if "exc_pattern" in kwargs:
59
            exc_pattern = kwargs["exc_pattern"]
60
            del kwargs["exc_pattern"]
61
        else:
62
            exc_pattern = None
63

    
64
        argv = [repr(a) for a in args]\
65
               + ["%s=%r" % (k,v)  for k,v in kwargs.items()]
66
        callsig = "%s(%s)" % (callable.__name__, ", ".join(argv))
67

    
68
        try:
69
            callable(*args, **kwargs)
70
        except exception, exc:
71
            if exc_args is not None:
72
                self.failIf(exc.args != exc_args,
73
                            "%s raised %s with unexpected args: "\
74
                            "expected=%r, actual=%r"\
75
                            % (callsig, exc.__class__, exc_args, exc.args))
76
            if exc_pattern is not None:
77
                self.assertTrue(exc_pattern.search(str(exc)),
78
                                "%s raised %s, but the exception "\
79
                                "does not match '%s': %r"\
80
                                % (callsig, exc.__class__, exc_pattern.pattern,
81
                                   str(exc)))
82
        except:
83
            exc_info = sys.exc_info()
84
            print exc_info
85
            self.fail("%s raised an unexpected exception type: "\
86
                      "expected=%s, actual=%s"\
87
                      % (callsig, exception, exc_info[0]))
88
        else:
89
            self.fail("%s did not raise %s" % (callsig, exception))
90

    
91
    def assertRaisesMsg(self, excClass, msg, callableObj, *args, **kwargs):
92
        """
93
        Just like unittest.TestCase.assertRaises,
94
        but checks that the message is right too.
95

96
        Usage::
97

98
            self.assertRaisesMsg(
99
                MyException, "Exception message",
100
                my_function, (arg1, arg2)
101
                )
102

103
        from
104
        http://www.nedbatchelder.com/blog/200609.html#e20060905T064418
105
        """
106
        try:
107
            callableObj(*args, **kwargs)
108
        except excClass, exc:
109
            excMsg = unicode(exc)
110
            if not msg:
111
                # No message provided: any message is fine.
112
                return
113
            elif excMsg == msg:
114
                # Message provided, and we got the right message: passes.
115
                return
116
            else:
117
                # Message provided, and it didn't match: fail!
118
                raise self.failureException(
119
                    u"Right exception, wrong message: got '%s' instead of '%s'" %
120
                    (excMsg, msg))
121
        else:
122
            if hasattr(excClass, '__name__'):
123
                excName = excClass.__name__
124
            else:
125
                excName = str(excClass)
126
            raise self.failureException(
127
                "Expected to raise %s, didn't get an exception at all" %
128
                excName
129
                )
130

    
131
    def do_equal_p(self, tests, att='cssText', debug=False, raising=True):
132
        """
133
        if raising self.p is used for parsing, else self.pf
134
        """
135
        p = cssutils.CSSParser(raiseExceptions=raising)
136
        # parses with self.p and checks att of result
137
        for test, expected in tests.items():
138
            if debug:
139
                print '"%s"' % test
140
            s = p.parseString(test)
141
            if expected is None:
142
                expected = test
143
            self.assertEqual(expected, unicode(s.__getattribute__(att), 'utf-8'))
144

    
145
    def do_raise_p(self, tests, debug=False, raising=True):
146
        # parses with self.p and expects raise
147
        p = cssutils.CSSParser(raiseExceptions=raising)
148
        for test, expected in tests.items():
149
            if debug:
150
                print '"%s"' % test
151
            self.assertRaises(expected, p.parseString, test)
152

    
153
    def do_equal_r(self, tests, att='cssText', debug=False):
154
        # sets attribute att of self.r and asserts Equal
155
        for test, expected in tests.items():
156
            if debug:
157
                print '"%s"' % test
158
            self.r.__setattr__(att, test)
159
            if expected is None:
160
                expected = test
161
            self.assertEqual(expected, self.r.__getattribute__(att))
162

    
163
    def do_raise_r(self, tests, att='_setCssText', debug=False):
164
        # sets self.r and asserts raise
165
        for test, expected in tests.items():
166
            if debug:
167
                print '"%s"' % test
168
            self.assertRaises(expected, self.r.__getattribute__(att), test)
169

    
170
    def do_raise_r_list(self, tests, err, att='_setCssText', debug=False):
171
        # sets self.r and asserts raise
172
        for test in tests:
173
            if debug:
174
                print '"%s"' % test
175
            self.assertRaises(err, self.r.__getattribute__(att), test)