~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
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
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
17
from cStringIO import StringIO
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
18
import errno
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
19
from SimpleHTTPServer import SimpleHTTPRequestHandler
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
20
import socket
2213.1.1 by v.ladeuil+lp at free
Workaround SimpleHTTPRequestHandler.translate_path limitation in
21
import urlparse
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
22
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
23
from bzrlib.tests import TestCaseWithTransport
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
24
from bzrlib.tests.HttpServer import (
25
    HttpServer,
26
    TestingHTTPRequestHandler,
27
    )
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
28
from bzrlib.transport import (
29
    get_transport,
30
    smart,
31
    )
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
32
33
34
class WallRequestHandler(TestingHTTPRequestHandler):
35
    """Whatever request comes in, close the connection"""
36
37
    def handle_one_request(self):
38
        """Handle a single HTTP request, by abruptly closing the connection"""
39
        self.close_connection = 1
40
41
42
class BadStatusRequestHandler(TestingHTTPRequestHandler):
43
    """Whatever request comes in, returns a bad status"""
44
45
    def parse_request(self):
46
        """Fakes handling a single HTTP request, returns a bad status"""
47
        ignored = TestingHTTPRequestHandler.parse_request(self)
48
        try:
49
            self.send_response(0, "Bad status")
50
            self.end_headers()
51
        except socket.error, e:
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
52
            # We don't want to pollute the test results with
53
            # spurious server errors while test succeed. In our
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
54
            # case, it may occur that the test has already read
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
55
            # the 'Bad Status' and closed the socket while we are
56
            # still trying to send some headers... So the test is
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
57
            # ok, but if we raise the exception, the output is
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
58
            # dirty. So we don't raise, but we close the
59
            # connection, just to be safe :)
60
            spurious = [errno.EPIPE,
61
                        errno.ECONNRESET,
62
                        errno.ECONNABORTED,
63
                        ]
64
            if (len(e.args) > 0) and (e.args[0] in spurious):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
65
                self.close_connection = 1
66
                pass
67
            else:
68
                raise
69
        return False
70
71
72
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
73
    """Whatever request comes in, returns am invalid status"""
74
75
    def parse_request(self):
76
        """Fakes handling a single HTTP request, returns a bad status"""
77
        ignored = TestingHTTPRequestHandler.parse_request(self)
78
        self.wfile.write("Invalid status line\r\n")
79
        return False
80
81
82
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
83
    """Whatever request comes in, returns a bad protocol version"""
84
85
    def parse_request(self):
86
        """Fakes handling a single HTTP request, returns a bad status"""
87
        ignored = TestingHTTPRequestHandler.parse_request(self)
88
        # Returns an invalid protocol version, but curl just
89
        # ignores it and those cannot be tested.
90
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
91
                                           404,
92
                                           'Look at my protocol version'))
93
        return False
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
94
95
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
96
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
97
    """Whatever request comes in, returns a 403 code"""
98
99
    def parse_request(self):
100
        """Handle a single HTTP request, by replying we cannot handle it"""
101
        ignored = TestingHTTPRequestHandler.parse_request(self)
102
        self.send_error(403)
103
        return False
104
105
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
106
class HTTPServerWithSmarts(HttpServer):
107
    """HTTPServerWithSmarts extends the HttpServer with POST methods that will
108
    trigger a smart server to execute with a transport rooted at the rootdir of
109
    the HTTP server.
110
    """
111
112
    def __init__(self):
113
        HttpServer.__init__(self, SmartRequestHandler)
114
115
116
class SmartRequestHandler(TestingHTTPRequestHandler):
117
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
118
119
    def do_POST(self):
120
        """Hand the request off to a smart server instance."""
121
        self.send_response(200)
122
        self.send_header("Content-type", "application/octet-stream")
123
        transport = get_transport(self.server.test_case._home_dir)
124
        # TODO: We might like to support streaming responses.  1.0 allows no
125
        # Content-length in this case, so for integrity we should perform our
126
        # own chunking within the stream.
127
        # 1.1 allows chunked responses, and in this case we could chunk using
128
        # the HTTP chunking as this will allow HTTP persistence safely, even if
129
        # we have to stop early due to error, but we would also have to use the
130
        # HTTP trailer facility which may not be widely available.
131
        out_buffer = StringIO()
132
        smart_protocol_request = smart.SmartServerRequestProtocolOne(
133
                transport, out_buffer.write)
134
        # if this fails, we should return 400 bad request, but failure is
135
        # failure for now - RBC 20060919
136
        data_length = int(self.headers['Content-Length'])
137
        # Perhaps there should be a SmartServerHTTPMedium that takes care of
138
        # feeding the bytes in the http request to the smart_protocol_request,
139
        # but for now it's simpler to just feed the bytes directly.
140
        smart_protocol_request.accept_bytes(self.rfile.read(data_length))
141
        assert smart_protocol_request.next_read_size() == 0, (
142
            "not finished reading, but all data sent to protocol.")
143
        self.send_header("Content-Length", str(len(out_buffer.getvalue())))
144
        self.end_headers()
145
        self.wfile.write(out_buffer.getvalue())
146
147
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
148
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
149
    """Always reply to range request as if they were single.
150
151
    Don't be explicit about it, just to annoy the clients.
152
    """
153
154
    def get_multiple_ranges(self, file, file_size, ranges):
155
        """Answer as if it was a single range request and ignores the rest"""
156
        (start, end) = ranges[0]
157
        return self.get_single_range(file, file_size, start, end)
158
159
160
class NoRangeRequestHandler(TestingHTTPRequestHandler):
161
    """Ignore range requests without notice"""
162
163
    # Just bypass the range handling done by TestingHTTPRequestHandler
164
    do_GET = SimpleHTTPRequestHandler.do_GET
165
166
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
167
class TestCaseWithWebserver(TestCaseWithTransport):
168
    """A support class that provides readonly urls that are http://.
169
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
170
    This is done by forcing the readonly server to be an http
171
    one. This will currently fail if the primary transport is not
172
    backed by regular disk files.
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
173
    """
174
    def setUp(self):
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
175
        super(TestCaseWithWebserver, self).setUp()
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
176
        self.transport_readonly_server = HttpServer
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
177
178
179
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
180
    """A support class providinf readonly urls (on two servers) that are http://.
181
182
    We setup two webservers to allows various tests involving
183
    proxies or redirections from one server to the other.
184
    """
185
    def setUp(self):
186
        super(TestCaseWithTwoWebservers, self).setUp()
187
        self.transport_secondary_server = HttpServer
188
        self.__secondary_server = None
189
190
    def create_transport_secondary_server(self):
191
        """Create a transport server from class defined at init.
192
193
        This is mostly a hook for daughter classes.
194
        """
195
        return self.transport_secondary_server()
196
197
    def get_secondary_server(self):
198
        """Get the server instance for the secondary transport."""
199
        if self.__secondary_server is None:
200
            self.__secondary_server = self.create_transport_secondary_server()
201
            self.__secondary_server.setUp()
202
            self.addCleanup(self.__secondary_server.tearDown)
203
        return self.__secondary_server
204
205
206
class FakeProxyRequestHandler(TestingHTTPRequestHandler):
207
    """Append a '-proxied' suffix to file served"""
208
209
    def translate_path(self, path):
2213.1.1 by v.ladeuil+lp at free
Workaround SimpleHTTPRequestHandler.translate_path limitation in
210
        # We need to act as a proxy and accept absolute urls,
211
        # which SimpleHTTPRequestHandler (grand parent) is not
212
        # ready for. So we just drop the protocol://host:port
213
        # part in front of the request-url (because we know we
214
        # would not forward the request to *another* proxy).
215
216
        # So we do what SimpleHTTPRequestHandler.translate_path
217
        # do beginning with python 2.4.3: abandon query
218
        # parameters, scheme, host port, etc (which ensure we
219
        # provide the right behaviour on all python versions).
220
        path = urlparse.urlparse(path)[2]
221
        # And now, we can apply *our* trick to proxy files
222
        self.path += '-proxied'
223
        # An finally we leave our mother class do whatever it
224
        # wants with the path
225
        return TestingHTTPRequestHandler.translate_path(self, path)
226
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
227
228