~launchpad-pqm/launchpad/devel

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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# Copyright 2006 Canonical Ltd.  All rights reserved.

"""Alter the standard functional testing environment for Launchpad."""

from cStringIO import StringIO
import doctest
import httplib
import logging
import sys
import unittest
import xmlrpclib

import zope.app.testing.functional
from zope.app.testing.functional import (
    FunctionalTestSetup, HTTPCaller, ZopePublication, SimpleCookie)
from zope.security.management import endInteraction, queryInteraction

from zope.testing.loggingsupport import Handler
from zope.testbrowser.testing import Browser

from canonical.config import config
from canonical.chunkydiff import elided_source
from canonical.launchpad.scripts import execute_zcml_for_scripts
from canonical.launchpad.webapp.interaction import (
    get_current_principal, setupInteraction)
from canonical.testing import reset_logging, FunctionalLayer

class NewFunctionalTestSetup(FunctionalTestSetup):
    """Wrap standard FunctionalTestSetup to ensure it is only called
       from tests specifying a valid Layer.
    """
    def __init__(self, *args, **kw):
        from canonical.testing import FunctionalLayer, ZopelessLayer
        assert FunctionalLayer.isSetUp or ZopelessLayer.isSetUp, """
                FunctionalTestSetup invoked at an inappropriate time.
                May only be invoked in the FunctionalLayer or ZopelessLayer
                """
        super(NewFunctionalTestSetup, self).__init__(*args, **kw)
FunctionalTestSetup = NewFunctionalTestSetup

class FunctionalTestCase(unittest.TestCase):
    """Functional test case.
    
    This functionality should be moved into canonical.testing.
    """
    layer = FunctionalLayer
    def setUp(self):
        """Prepares for a functional test case."""
        super(FunctionalTestCase, self).setUp()

    def tearDown(self):
        """Cleans up after a functional test case."""
        super(FunctionalTestCase, self).tearDown()

    def getRootFolder(self):
        """Returns the Zope root folder."""
        raise NotImplementedError('getRootFolder')
        #return FunctionalTestSetup().getRootFolder()

    def commit(self):
        commit()

    def abort(self):
        abort()


class StdoutWrapper:
    """A wrapper for sys.stdout.  Writes to this file like object will
    write to whatever sys.stdout is pointing to at the time.

    The purpose of this class is to allow doctest to capture log
    messages.  Since doctest replaces sys.stdout, configuring the
    logging module to send messages to sys.stdout before running the
    tests will not result in the output being captured.  Using an
    instance of this class solves the problem.
    """
    def __getattr__(self, attr):
        return getattr(sys.stdout, attr)


class StdoutHandler(Handler):
    def emit(self, record):
        Handler.emit(self, record)
        print >> StdoutWrapper(), '%s:%s:%s' % (
                    record.levelname, record.name, self.format(record)
                    )


class MockRootFolder:
    """Implement the minimum functionality required by Z3 ZODB dependancies

    Installed as part of the FunctionalDocFileSuite to allow the http()
    method (zope.app.testing.functional.HTTPCaller) to work.
    """
    @property
    def _p_jar(self):
        return self
    def sync(self):
        pass


class UnstickyCookieHTTPCaller(HTTPCaller):
    """HTTPCaller propogates cookies between subsequent requests.
    This is a nice feature, except it triggers a bug in Launchpad where
    sending both Basic Auth and cookie credentials raises an exception
    (Bug 39881).
    """
    def __init__(self, *args, **kw):
        if kw.get('debug'):
            self._debug = True
            del kw['debug']
        else:
            self._debug = False
        HTTPCaller.__init__(self, *args, **kw)
    def __call__(self, *args, **kw):
        if self._debug:
            import pdb; pdb.set_trace()
        try:
            return HTTPCaller.__call__(self, *args, **kw)
        finally:
            self.resetCookies()

    def resetCookies(self):
        self.cookies = SimpleCookie()


def FunctionalDocFileSuite(*paths, **kw):
    kwsetUp = kw.get('setUp')

    # Set stdout_logging keyword argument to True to make
    # logging output be sent to stdout, forcing doctests to deal with it.
    if kw.has_key('stdout_logging'):
        stdout_logging = kw.get('stdout_logging')
        del kw['stdout_logging']
    else:
        stdout_logging = True

    if kw.has_key('stdout_logging_level'):
        stdout_logging_level = kw.get('stdout_logging_level')
        del kw['stdout_logging_level']
    else:
        stdout_logging_level = logging.INFO

    if kw.has_key('layer'):
        layer = kw.pop('layer')
    else:
        layer = FunctionalLayer

    def setUp(test):
        if kwsetUp is not None:
            kwsetUp(test)
        # Fake a root folder to keep Z3 ZODB dependancies happy
        fs = FunctionalTestSetup()
        if not fs.connection:
            fs.connection = fs.db.open()
        root = fs.connection.root()
        root[ZopePublication.root_name] = MockRootFolder()
        # Out tests report being on a different port
        test.globs['http'] = UnstickyCookieHTTPCaller(port=9000)
        test.globs['debug_http'] = UnstickyCookieHTTPCaller(
                port=9000,debug=True
                )
        # Set up our Browser objects with handleErrors set to False, since
        # that gives a tracebacks instead of unhelpful error messages.
        def setupBrowser(auth=None):
            browser = Browser()
            browser.handleErrors = False
            if auth is not None:
                browser.addHeader("Authorization", auth)
            return browser

        test.globs['browser'] = setupBrowser()
        test.globs['anon_browser'] = setupBrowser()
        test.globs['user_browser'] = setupBrowser(
            auth="Basic test@canonical.com:test")
        test.globs['admin_browser'] = setupBrowser(
            auth="Basic foo.bar@canonical.com:test")
        
        if stdout_logging:
            log = StdoutHandler('')
            log.setLoggerLevel(stdout_logging_level)
            log.install()
            test.globs['log'] = log
            # Store here as well in case test overwrites 'log' global
            test.globs['_functional_log'] = log
    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        if kwtearDown is not None:
            kwtearDown(test)
        if stdout_logging:
            test.globs['_functional_log'].uninstall()
    kw['tearDown'] = tearDown

    suite = zope.app.testing.functional.FunctionalDocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite


def PageTestDocFileSuite(*paths, **kw):
    if not kw.get('stdout_logging'):
        kw['stdout_logging'] = False
    suite = FunctionalDocFileSuite(*paths, **kw)
    return suite


class SpecialOutputChecker(doctest.OutputChecker):
    def output_difference(self, example, got, optionflags):
        if config.chunkydiff is False:
            return doctest.OutputChecker.output_difference(
                self, example, got, optionflags)

        if optionflags & doctest.ELLIPSIS:
            normalize_whitespace = optionflags & doctest.NORMALIZE_WHITESPACE
            newgot = elided_source(example.want, got,
                                   normalize_whitespace=normalize_whitespace)
            if newgot == example.want:
                # There was no difference.  May be an error in elided_source().
                # In any case, return the whole thing.
                newgot = got
        else:
            newgot = got
        return doctest.OutputChecker.output_difference(
            self, example, newgot, optionflags)


class HTTPCallerHTTPConnection(httplib.HTTPConnection):
    """A HTTPConnection which talks to HTTPCaller instead of a real server.

    Only the methods called by xmlrpclib are overridden.
    """

    _data_to_send = ''
    _response = None

    def __init__(self, host):
        httplib.HTTPConnection.__init__(self, host)
        self.caller = HTTPCaller()

    def connect(self):
        """No need to connect."""
        pass

    def send(self, data):
        """Send the request to HTTPCaller."""
        # We don't send it to HTTPCaller yet, we store the data and sends
        # everything at once when the client requests a response.
        self._data_to_send += data

    def getresponse(self):
        """Get the response."""
        current_principal = None
        # End and save the current interaction, since HTTPCaller creates
        # its own interaction.
        if queryInteraction():
            current_principal = get_current_principal()
            endInteraction()
        if self._response is None:
            self._response = self.caller(self._data_to_send)
        # Restore the interaction to what it was before.
        setupInteraction(current_principal)
        return self._response

    def getreply(self):
        """Return a tuple of status code, reason string, and headers."""
        response = self.getresponse()
        return (
            response.getStatus(),
            response.getStatusString(),
            response.getHeaders())

    def getfile(self):
        """Get the response body as a file like object."""
        response = self.getresponse()
        return StringIO(response.consumeBody())


class XMLRPCTestTransport(xmlrpclib.Transport):
    """An XMLRPC Transport which sends the requests to HTTPCaller."""

    def make_connection(self, host):
        """Return our custom HTTPCaller HTTPConnection."""
        host, extra_headers, x509 = self.get_host_info(host)
        return HTTPCallerHTTPConnection(host)


if __name__ == '__main__':
    unittest.main()