~ignas/schooltool/schooltool_js_fixes

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
#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2003,2005 Shuttleworth Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
"""
Checks for the unit tests.
"""

import sys
import logging

name_of_test = str

__metaclass__ = type


def warn(msg):
    print >> sys.stderr, "\n" + msg


def sorted(l):
    l = list(l) # make a copy
    l.sort()
    return l


def difflist(old, new):
    """Show the differences between two lists."""
    import pprint
    import difflib
    old = pprint.pformat(old) + "\n"
    new = pprint.pformat(new) + "\n"
    return ''.join(difflib.unified_diff(old.splitlines(True),
                                        new.splitlines(True)))


class TransactionChecks:

    def startTest(self, test):
        import transaction
        txn = transaction.get()
        self.had_resources = bool(txn._resources)

    def stopTest(self, test):
        if self.had_resources:
            return
        import transaction
        txn = transaction.get()
        if txn._resources:
            warn("%s left an unclean transaction" % name_of_test(test))
            txn.abort()
        if txn.isDoomed():
            warn("%s left a doomed transaction" % name_of_test(test))
            txn.abort()


class StdoutWrapper:

    def __init__(self, stm):
        self._stm = stm
        self.written = False

    def __getattr__(self, attr):
        return getattr(self._stm, attr)

    def write(self, *args):
        self.written = True
        self._stm.write(*args)


class StdoutChecks:

    def __init__(self):
        self.stdout_wrapper = StdoutWrapper(sys.stdout)
        self.stderr_wrapper = StdoutWrapper(sys.stderr)

    def startTest(self, test):
        import sys
        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr
        sys.stdout = self.stdout_wrapper
        sys.stderr = self.stderr_wrapper
        self.stdout_wrapper.written = False
        self.stderr_wrapper.written = False

        # readline is disabled in PDB when our stdout hook is found instead of
        # the real stdout.  This problem is fixed through a monkey patch on
        # pdb.set_trace() and pdb.post_mortem().

        import pdb

        def set_trace_hook():
            sys.stdout = self.old_stdout
            self.old_pdb_set_trace()
            sys.stdout = self.stdout_wrapper

        def post_mortem_hook(tb):
            sys.stdout = self.old_stdout
            self.old_pdb_post_mortem(tb)
            sys.stdout = self.stdout_wrapper

        self.old_pdb_set_trace = pdb.set_trace
        self.old_pdb_post_mortem = pdb.post_mortem
        pdb.set_trace = set_trace_hook
        pdb.post_mortem = post_mortem_hook

    def stopTest(self, test):
        import sys
        warn_stdout_replaced = sys.stdout is not self.stdout_wrapper
        warn_stderr_replaced = sys.stderr is not self.stderr_wrapper
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr
        if warn_stdout_replaced:
            warn("%s replaced sys.stdout" % name_of_test(test))
        if warn_stderr_replaced:
            warn("%s replaced sys.stderr" % name_of_test(test))
        if self.stdout_wrapper.written:
            warn("%s wrote to sys.stdout" % name_of_test(test))
        if self.stderr_wrapper.written:
            warn("%s wrote to sys.stderr" % name_of_test(test))

        import pdb
        pdb.set_trace = self.old_pdb_set_trace
        pdb.post_mortem = self.old_pdb_post_mortem


class LoggingChecks:
    """Detect unit tests that fiddle with the logging package.

    This class looks for the following fiddlings:

      logging.getLogger('foo').disabled = True
      logging.getLogger('foo').propagate = False
      logging.getLogger('foo').setLevel(bar)
      logging.getLogger('foo').addHandler(handler)
      logging.getLogger('foo').removeHandler(handler)
    """

    def __init__(self, verbose=True):
        self.verbose = verbose

    def startTest(self, test):
        self.snapshot = self.makeSnapshot()

    def stopTest(self, test):
        new_snapshot = self.makeSnapshot()
        if new_snapshot != self.snapshot:
            warn("%s changed logging configuration" % name_of_test(test))
            if self.verbose:
                old_loggers = set(self.snapshot.keys())
                new_loggers = set(new_snapshot.keys())
                for name in sorted(old_loggers | new_loggers):
                    if name not in new_loggers:
                        warn("  logger %s disappeared" % name)
                    elif name not in old_loggers:
                        warn("  new logger: %s" % name)
                    else:
                        old = self.snapshot[name]
                        new = new_snapshot[name]
                        if old != new:
                            warn("  logger %s was changed" % name)

    def makeSnapshot(self):
        info = {}
        for name, logger in logging.root.manager.loggerDict.items():
            if isinstance(logger, logging.PlaceHolder):
                continue
            if (logger.level == 0 and logger.propagate and not logger.disabled
                and not logger.handlers):
                continue
            info[name] = {'level': logger.level,
                          'disabled': logger.disabled,
                          'propagate': logger.propagate,
                          'handlers': list(logger.handlers)}
        return info


class CleanUpChecks:
    """Try to detect unit tests that perform placeless setup, but not teardown.

    The check actually counts the number of times CleanUp().cleanUp() is called
    during the setup, test itself, and teardown.  Since both placelessSetUp
    and placelessTearDown call CleanUp().cleanUp(), we expect to see at least
    two cleanups during that time.  If we see only one, something is wrong.
    """

    def __init__(self):
        from zope.testing.cleanup import addCleanUp
        self._testThatCalledCleanUp = {}
        self._current_test = None
        addCleanUp(self.doCleanUp)

    def doCleanUp(self):
        assert self._current_test is not None
        self._testThatCalledCleanUp.setdefault(self._current_test, 0)
        self._testThatCalledCleanUp[self._current_test] += 1

    def startTest(self, test):
        self._current_test = test

    def stopTest(self, test):
        count = self._testThatCalledCleanUp.get(test, 0)
        if count == 1:
            warn("%s called CleanUp only once"
                 " (probably in setUp, but not in tearDown)" % test.id())
        self._current_test = None


def test_hooks():
    return [
        StdoutChecks(),     # should be the first one
        TransactionChecks(),
        LoggingChecks(),
        CleanUpChecks(),
    ]