1
# Copyright (C) 2005 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
from cStringIO import StringIO
 
 
19
from SimpleHTTPServer import SimpleHTTPRequestHandler
 
 
22
from bzrlib.tests import TestCaseWithTransport
 
 
23
from bzrlib.tests.HttpServer import (
 
 
25
    TestingHTTPRequestHandler,
 
 
27
from bzrlib.transport import (
 
 
33
class WallRequestHandler(TestingHTTPRequestHandler):
 
 
34
    """Whatever request comes in, close the connection"""
 
 
36
    def handle_one_request(self):
 
 
37
        """Handle a single HTTP request, by abruptly closing the connection"""
 
 
38
        self.close_connection = 1
 
 
41
class BadStatusRequestHandler(TestingHTTPRequestHandler):
 
 
42
    """Whatever request comes in, returns a bad status"""
 
 
44
    def parse_request(self):
 
 
45
        """Fakes handling a single HTTP request, returns a bad status"""
 
 
46
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
 
48
            self.send_response(0, "Bad status")
 
 
50
        except socket.error, e:
 
 
51
            # We don't want to pollute the test results with
 
 
52
            # spurious server errors while test succeed. In our
 
 
53
            # case, it may occur that the test has already read
 
 
54
            # the 'Bad Status' and closed the socket while we are
 
 
55
            # still trying to send some headers... So the test is
 
 
56
            # ok, but if we raise the exception, the output is
 
 
57
            # dirty. So we don't raise, but we close the
 
 
58
            # connection, just to be safe :)
 
 
59
            spurious = [errno.EPIPE,
 
 
63
            if (len(e.args) > 0) and (e.args[0] in spurious):
 
 
64
                self.close_connection = 1
 
 
71
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
 
 
72
    """Whatever request comes in, returns am invalid status"""
 
 
74
    def parse_request(self):
 
 
75
        """Fakes handling a single HTTP request, returns a bad status"""
 
 
76
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
 
77
        self.wfile.write("Invalid status line\r\n")
 
 
81
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
 
 
82
    """Whatever request comes in, returns a bad protocol version"""
 
 
84
    def parse_request(self):
 
 
85
        """Fakes handling a single HTTP request, returns a bad status"""
 
 
86
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
 
87
        # Returns an invalid protocol version, but curl just
 
 
88
        # ignores it and those cannot be tested.
 
 
89
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
 
 
91
                                           'Look at my protocol version'))
 
 
95
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
 
 
96
    """Whatever request comes in, returns a 403 code"""
 
 
98
    def parse_request(self):
 
 
99
        """Handle a single HTTP request, by replying we cannot handle it"""
 
 
100
        ignored = TestingHTTPRequestHandler.parse_request(self)
 
 
105
class HTTPServerWithSmarts(HttpServer):
 
 
106
    """HTTPServerWithSmarts extends the HttpServer with POST methods that will
 
 
107
    trigger a smart server to execute with a transport rooted at the rootdir of
 
 
112
        HttpServer.__init__(self, SmartRequestHandler)
 
 
115
class SmartRequestHandler(TestingHTTPRequestHandler):
 
 
116
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
 
 
119
        """Hand the request off to a smart server instance."""
 
 
120
        self.send_response(200)
 
 
121
        self.send_header("Content-type", "application/octet-stream")
 
 
122
        transport = get_transport(self.server.test_case._home_dir)
 
 
123
        # TODO: We might like to support streaming responses.  1.0 allows no
 
 
124
        # Content-length in this case, so for integrity we should perform our
 
 
125
        # own chunking within the stream.
 
 
126
        # 1.1 allows chunked responses, and in this case we could chunk using
 
 
127
        # the HTTP chunking as this will allow HTTP persistence safely, even if
 
 
128
        # we have to stop early due to error, but we would also have to use the
 
 
129
        # HTTP trailer facility which may not be widely available.
 
 
130
        out_buffer = StringIO()
 
 
131
        smart_protocol_request = smart.SmartServerRequestProtocolOne(
 
 
132
                transport, out_buffer.write)
 
 
133
        # if this fails, we should return 400 bad request, but failure is
 
 
134
        # failure for now - RBC 20060919
 
 
135
        data_length = int(self.headers['Content-Length'])
 
 
136
        # Perhaps there should be a SmartServerHTTPMedium that takes care of
 
 
137
        # feeding the bytes in the http request to the smart_protocol_request,
 
 
138
        # but for now it's simpler to just feed the bytes directly.
 
 
139
        smart_protocol_request.accept_bytes(self.rfile.read(data_length))
 
 
140
        assert smart_protocol_request.next_read_size() == 0, (
 
 
141
            "not finished reading, but all data sent to protocol.")
 
 
142
        self.send_header("Content-Length", str(len(out_buffer.getvalue())))
 
 
144
        self.wfile.write(out_buffer.getvalue())
 
 
147
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
 
 
148
    """Always reply to range request as if they were single.
 
 
150
    Don't be explicit about it, just to annoy the clients.
 
 
153
    def get_multiple_ranges(self, file, file_size, ranges):
 
 
154
        """Answer as if it was a single range request and ignores the rest"""
 
 
155
        (start, end) = ranges[0]
 
 
156
        return self.get_single_range(file, file_size, start, end)
 
 
159
class NoRangeRequestHandler(TestingHTTPRequestHandler):
 
 
160
    """Ignore range requests without notice"""
 
 
162
    # Just bypass the range handling done by TestingHTTPRequestHandler
 
 
163
    do_GET = SimpleHTTPRequestHandler.do_GET
 
 
166
class TestCaseWithWebserver(TestCaseWithTransport):
 
 
167
    """A support class that provides readonly urls that are http://.
 
 
169
    This is done by forcing the readonly server to be an http
 
 
170
    one. This will currently fail if the primary transport is not
 
 
171
    backed by regular disk files.
 
 
174
        super(TestCaseWithWebserver, self).setUp()
 
 
175
        self.transport_readonly_server = HttpServer
 
 
178
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
 
 
179
    """A support class providinf readonly urls (on two servers) that are http://.
 
 
181
    We setup two webservers to allows various tests involving
 
 
182
    proxies or redirections from one server to the other.
 
 
185
        super(TestCaseWithTwoWebservers, self).setUp()
 
 
186
        self.transport_secondary_server = HttpServer
 
 
187
        self.__secondary_server = None
 
 
189
    def create_transport_secondary_server(self):
 
 
190
        """Create a transport server from class defined at init.
 
 
192
        This is mostly a hook for daughter classes.
 
 
194
        return self.transport_secondary_server()
 
 
196
    def get_secondary_server(self):
 
 
197
        """Get the server instance for the secondary transport."""
 
 
198
        if self.__secondary_server is None:
 
 
199
            self.__secondary_server = self.create_transport_secondary_server()
 
 
200
            self.__secondary_server.setUp()
 
 
201
            self.addCleanup(self.__secondary_server.tearDown)
 
 
202
        return self.__secondary_server
 
 
205
class FakeProxyRequestHandler(TestingHTTPRequestHandler):
 
 
206
    """Append a '-proxied' suffix to file served"""
 
 
208
    def translate_path(self, path):
 
 
209
        return TestingHTTPRequestHandler.translate_path(self,