/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/HTTPTestUtil.py

Record merge against split out urlutils work.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
import errno
 
19
from SimpleHTTPServer import SimpleHTTPRequestHandler
 
20
import socket
 
21
import urlparse
 
22
 
 
23
from bzrlib import smart
 
24
import bzrlib.smart.request
 
25
from bzrlib.tests import TestCaseWithTransport
 
26
from bzrlib.tests.HttpServer import (
 
27
    HttpServer,
 
28
    TestingHTTPRequestHandler,
 
29
    )
 
30
from bzrlib.transport import (
 
31
    get_transport,
 
32
    )
 
33
 
 
34
 
 
35
class WallRequestHandler(TestingHTTPRequestHandler):
 
36
    """Whatever request comes in, close the connection"""
 
37
 
 
38
    def handle_one_request(self):
 
39
        """Handle a single HTTP request, by abruptly closing the connection"""
 
40
        self.close_connection = 1
 
41
 
 
42
 
 
43
class BadStatusRequestHandler(TestingHTTPRequestHandler):
 
44
    """Whatever request comes in, returns a bad status"""
 
45
 
 
46
    def parse_request(self):
 
47
        """Fakes handling a single HTTP request, returns a bad status"""
 
48
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
49
        try:
 
50
            self.send_response(0, "Bad status")
 
51
            self.end_headers()
 
52
        except socket.error, e:
 
53
            # We don't want to pollute the test results with
 
54
            # spurious server errors while test succeed. In our
 
55
            # case, it may occur that the test has already read
 
56
            # the 'Bad Status' and closed the socket while we are
 
57
            # still trying to send some headers... So the test is
 
58
            # ok, but if we raise the exception, the output is
 
59
            # dirty. So we don't raise, but we close the
 
60
            # connection, just to be safe :)
 
61
            spurious = [errno.EPIPE,
 
62
                        errno.ECONNRESET,
 
63
                        errno.ECONNABORTED,
 
64
                        ]
 
65
            if (len(e.args) > 0) and (e.args[0] in spurious):
 
66
                self.close_connection = 1
 
67
                pass
 
68
            else:
 
69
                raise
 
70
        return False
 
71
 
 
72
 
 
73
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
 
74
    """Whatever request comes in, returns am invalid status"""
 
75
 
 
76
    def parse_request(self):
 
77
        """Fakes handling a single HTTP request, returns a bad status"""
 
78
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
79
        self.wfile.write("Invalid status line\r\n")
 
80
        return False
 
81
 
 
82
 
 
83
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
 
84
    """Whatever request comes in, returns a bad protocol version"""
 
85
 
 
86
    def parse_request(self):
 
87
        """Fakes handling a single HTTP request, returns a bad status"""
 
88
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
89
        # Returns an invalid protocol version, but curl just
 
90
        # ignores it and those cannot be tested.
 
91
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
 
92
                                           404,
 
93
                                           'Look at my protocol version'))
 
94
        return False
 
95
 
 
96
 
 
97
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
 
98
    """Whatever request comes in, returns a 403 code"""
 
99
 
 
100
    def parse_request(self):
 
101
        """Handle a single HTTP request, by replying we cannot handle it"""
 
102
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
103
        self.send_error(403)
 
104
        return False
 
105
 
 
106
 
 
107
class HTTPServerWithSmarts(HttpServer):
 
108
    """HTTPServerWithSmarts extends the HttpServer with POST methods that will
 
109
    trigger a smart server to execute with a transport rooted at the rootdir of
 
110
    the HTTP server.
 
111
    """
 
112
 
 
113
    def __init__(self):
 
114
        HttpServer.__init__(self, SmartRequestHandler)
 
115
 
 
116
 
 
117
class SmartRequestHandler(TestingHTTPRequestHandler):
 
118
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
 
119
 
 
120
    def do_POST(self):
 
121
        """Hand the request off to a smart server instance."""
 
122
        self.send_response(200)
 
123
        self.send_header("Content-type", "application/octet-stream")
 
124
        transport = get_transport(self.server.test_case._home_dir)
 
125
        # TODO: We might like to support streaming responses.  1.0 allows no
 
126
        # Content-length in this case, so for integrity we should perform our
 
127
        # own chunking within the stream.
 
128
        # 1.1 allows chunked responses, and in this case we could chunk using
 
129
        # the HTTP chunking as this will allow HTTP persistence safely, even if
 
130
        # we have to stop early due to error, but we would also have to use the
 
131
        # HTTP trailer facility which may not be widely available.
 
132
        out_buffer = StringIO()
 
133
        smart_protocol_request = smart.protocol.SmartServerRequestProtocolOne(
 
134
                transport, out_buffer.write)
 
135
        # if this fails, we should return 400 bad request, but failure is
 
136
        # failure for now - RBC 20060919
 
137
        data_length = int(self.headers['Content-Length'])
 
138
        # Perhaps there should be a SmartServerHTTPMedium that takes care of
 
139
        # feeding the bytes in the http request to the smart_protocol_request,
 
140
        # but for now it's simpler to just feed the bytes directly.
 
141
        smart_protocol_request.accept_bytes(self.rfile.read(data_length))
 
142
        assert smart_protocol_request.next_read_size() == 0, (
 
143
            "not finished reading, but all data sent to protocol.")
 
144
        self.send_header("Content-Length", str(len(out_buffer.getvalue())))
 
145
        self.end_headers()
 
146
        self.wfile.write(out_buffer.getvalue())
 
147
 
 
148
 
 
149
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
 
150
    """Always reply to range request as if they were single.
 
151
 
 
152
    Don't be explicit about it, just to annoy the clients.
 
153
    """
 
154
 
 
155
    def get_multiple_ranges(self, file, file_size, ranges):
 
156
        """Answer as if it was a single range request and ignores the rest"""
 
157
        (start, end) = ranges[0]
 
158
        return self.get_single_range(file, file_size, start, end)
 
159
 
 
160
 
 
161
class NoRangeRequestHandler(TestingHTTPRequestHandler):
 
162
    """Ignore range requests without notice"""
 
163
 
 
164
    # Just bypass the range handling done by TestingHTTPRequestHandler
 
165
    do_GET = SimpleHTTPRequestHandler.do_GET
 
166
 
 
167
 
 
168
class TestCaseWithWebserver(TestCaseWithTransport):
 
169
    """A support class that provides readonly urls that are http://.
 
170
 
 
171
    This is done by forcing the readonly server to be an http
 
172
    one. This will currently fail if the primary transport is not
 
173
    backed by regular disk files.
 
174
    """
 
175
    def setUp(self):
 
176
        super(TestCaseWithWebserver, self).setUp()
 
177
        self.transport_readonly_server = HttpServer
 
178
 
 
179
 
 
180
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
 
181
    """A support class providinf readonly urls (on two servers) that are http://.
 
182
 
 
183
    We setup two webservers to allows various tests involving
 
184
    proxies or redirections from one server to the other.
 
185
    """
 
186
    def setUp(self):
 
187
        super(TestCaseWithTwoWebservers, self).setUp()
 
188
        self.transport_secondary_server = HttpServer
 
189
        self.__secondary_server = None
 
190
 
 
191
    def create_transport_secondary_server(self):
 
192
        """Create a transport server from class defined at init.
 
193
 
 
194
        This is mostly a hook for daughter classes.
 
195
        """
 
196
        return self.transport_secondary_server()
 
197
 
 
198
    def get_secondary_server(self):
 
199
        """Get the server instance for the secondary transport."""
 
200
        if self.__secondary_server is None:
 
201
            self.__secondary_server = self.create_transport_secondary_server()
 
202
            self.__secondary_server.setUp()
 
203
            self.addCleanup(self.__secondary_server.tearDown)
 
204
        return self.__secondary_server
 
205
 
 
206
 
 
207
class FakeProxyRequestHandler(TestingHTTPRequestHandler):
 
208
    """Append a '-proxied' suffix to file served"""
 
209
 
 
210
    def translate_path(self, path):
 
211
        # We need to act as a proxy and accept absolute urls,
 
212
        # which SimpleHTTPRequestHandler (grand parent) is not
 
213
        # ready for. So we just drop the protocol://host:port
 
214
        # part in front of the request-url (because we know we
 
215
        # would not forward the request to *another* proxy).
 
216
 
 
217
        # So we do what SimpleHTTPRequestHandler.translate_path
 
218
        # do beginning with python 2.4.3: abandon query
 
219
        # parameters, scheme, host port, etc (which ensure we
 
220
        # provide the right behaviour on all python versions).
 
221
        path = urlparse.urlparse(path)[2]
 
222
        # And now, we can apply *our* trick to proxy files
 
223
        self.path += '-proxied'
 
224
        # An finally we leave our mother class do whatever it
 
225
        # wants with the path
 
226
        return TestingHTTPRequestHandler.translate_path(self, path)
 
227
 
 
228
 
 
229