File: UnitTest.py

package info (click to toggle)
pyjamas 0.7~%2Bpre2-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 10,656 kB
  • ctags: 12,331
  • sloc: python: 74,493; php: 805; sh: 291; makefile: 59; xml: 9
file content (210 lines) | stat: -rw-r--r-- 7,078 bytes parent folder | download
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
from write import write, writebr
import sys

IN_BROWSER = sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']
IN_JS = sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz',
                         'safari', 'spidermonkey', 'pyv8']

if IN_BROWSER:
    from pyjamas.Timer import Timer

class UnitTest:

    def __init__(self):
        self.tests_completed=0
        self.tests_failed=0
        self.tests_passed=0
        self.test_methods=[]
        self.test_idx = None

        # Synonyms for assertion methods
        self.assertEqual = self.assertEquals = self.failUnlessEqual
        self.assertNotEqual = self.assertNotEquals = self.failIfEqual
        self.assertAlmostEqual = self.assertAlmostEquals = self.failUnlessAlmostEqual
        self.assertNotAlmostEqual = self.assertNotAlmostEquals = self.failIfAlmostEqual
        self.assertRaises = self.failUnlessRaises
        self.assert_ = self.assertTrue = self.failUnless
        self.assertFalse = self.failIf

    def _run_test(self, test_method_name):
        self.getTestMethods()

        test_method=getattr(self, test_method_name)
        self.current_test_name = test_method_name
        self.setUp()
        test_method()
        self.tearDown()
        self.current_test_name = None

    def run(self):
        self.getTestMethods()
        if not IN_BROWSER:
            for test_method_name in self.test_methods:
                self._run_test(test_method_name)
            self.displayStats()
            if hasattr(self, "start_next_test"):
                self.start_next_test()
            return
        self.test_idx = 0
        Timer(1, self)

    def onTimer(self, tid):
        for i in range(10):
            if self.test_idx >= len(self.test_methods):
                self.displayStats()
                self.test_idx = 'DONE'
                self.start_next_test()
                return

            self._run_test(self.test_methods[self.test_idx])
            self.test_idx += 1
        Timer(1, self)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def getName(self):
        return self.__class__.__name__

    def getNameFmt(self, msg=""):
        if self.getName():
            if msg:
                msg=" " + str(msg)
            if self.current_test_name:
                msg += " (%s) " % self.current_test_name
            return self.getName() + msg + ": "
        return ""

    def getTestMethods(self):
        self.test_methods=[]
        for m in dir(self):
            if self.isTestMethod(m):
                self.test_methods.append(m)

    def isTestMethod(self, method):
        if callable(getattr(self, method)):
            if method.find("test") == 0:
                return True
        return False

    def fail(self, msg=None):
        self.startTest()
        self.tests_failed+=1

        if not msg:
            msg="assertion failed"
        else:
            msg = str(msg)

        title="<b>" + self.getNameFmt("Test failed") + "</b>"
        writebr(title + msg)
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            from __pyjamas__ import JS
            JS("""if (typeof console != 'undefined') {
                if (typeof console.error == 'function') console.error(msg);
                if (typeof console.trace == 'function') console.trace();
            }""")
        return False

    def startTest(self):
        self.tests_completed+=1

    def failIf(self, expr, msg=None):
        self.startTest()
        if expr:
            return self.fail(msg)

    def failUnless(self, expr, msg=None):
        self.startTest()
        if not expr:
            return self.fail(msg)

    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        try:
            callableObj(*args, **kwargs)
        except excClass:
            return
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
            #raise self.failureException, "%s not raised" % excName
            self.fail("%s not raised" % excName)

    def failUnlessEqual(self, first, second, msg=None):
        self.startTest()
        if not first == second:
            if not msg:
                msg=repr(first) + " != " + repr(second)
            return self.fail(msg)

    def failIfEqual(self, first, second, msg=None):
        self.startTest()
        if first == second:
            if not msg:
                msg=repr(first) + " == " + repr(second)
            return self.fail(msg)

    def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
        self.startTest()
        if round(second-first, places) != 0:
            if not msg:
                msg=repr(first) + " != " + repr(second) + " within " + repr(places) + " places"
            return self.fail(msg)

    def failIfAlmostEqual(self, first, second, places=7, msg=None):
        self.startTest()
        if round(second-first, places)  is  0:
            if not msg:
                msg=repr(first) + " == " + repr(second) + " within " + repr(places) + " places"
            return self.fail(msg)

    # based on the Python standard library
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
        """
        Fail unless an exception of class excClass is thrown
        by callableObj when invoked with arguments args and keyword
        arguments kwargs. If a different type of exception is
        thrown, it will not be caught, and the test case will be
        deemed to have suffered an error, exactly as for an
        unexpected exception.
        """
        self.startTest()
        try:
            callableObj(*args, **kwargs)
        except excClass, exc:
            return
        else:
            if hasattr(excClass, '__name__'):
                excName = excClass.__name__
            else:
                excName = str(excClass)
            self.fail("%s not raised" % excName)

    def displayStats(self):
        if self.tests_failed:
            bg_colour="#ff0000"
            fg_colour="#ffffff"
        else:
            bg_colour="#00ff00"
            fg_colour="#000000"

        tests_passed=self.tests_completed - self.tests_failed
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output="<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
        else:
            output = ""
        output+=self.getNameFmt() + "Passed %d " % tests_passed + "/ %d" % self.tests_completed + " tests"

        if self.tests_failed:
            output+=" (%d failed)" % self.tests_failed

        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output+="</b></font></td></tr></table>"
        else:
            output+= "\n"

        write(output)