~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
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
21
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.
22
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 :)
23
from bzrlib.tests.HttpServer import (
24
    HttpServer,
25
    TestingHTTPRequestHandler,
26
    )
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
27
from bzrlib.transport import (
28
    get_transport,
29
    smart,
30
    )
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
31
32
33
class WallRequestHandler(TestingHTTPRequestHandler):
34
    """Whatever request comes in, close the connection"""
35
36
    def handle_one_request(self):
37
        """Handle a single HTTP request, by abruptly closing the connection"""
38
        self.close_connection = 1
39
40
41
class BadStatusRequestHandler(TestingHTTPRequestHandler):
42
    """Whatever request comes in, returns a bad status"""
43
44
    def parse_request(self):
45
        """Fakes handling a single HTTP request, returns a bad status"""
46
        ignored = TestingHTTPRequestHandler.parse_request(self)
47
        try:
48
            self.send_response(0, "Bad status")
49
            self.end_headers()
50
        except socket.error, e:
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
51
            # We don't want to pollute the test results with
52
            # spurious server errors while test succeed. In our
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
53
            # case, it may occur that the test has already read
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
54
            # the 'Bad Status' and closed the socket while we are
55
            # still trying to send some headers... So the test is
2188.1.1 by Aaron Bentley
Windows tests cleanup. (Vincent Ladeuil)
56
            # ok, but if we raise the exception, the output is
2158.2.1 by v.ladeuil+lp at free
Windows tests cleanup.
57
            # dirty. So we don't raise, but we close the
58
            # connection, just to be safe :)
59
            spurious = [errno.EPIPE,
60
                        errno.ECONNRESET,
61
                        errno.ECONNABORTED,
62
                        ]
63
            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 :)
64
                self.close_connection = 1
65
                pass
66
            else:
67
                raise
68
        return False
69
70
71
class InvalidStatusRequestHandler(TestingHTTPRequestHandler):
72
    """Whatever request comes in, returns am invalid status"""
73
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")
78
        return False
79
80
81
class BadProtocolRequestHandler(TestingHTTPRequestHandler):
82
    """Whatever request comes in, returns a bad protocol version"""
83
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',
90
                                           404,
91
                                           'Look at my protocol version'))
92
        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.
93
94
2004.1.27 by v.ladeuil+lp at free
Fix bug #57644 by issuing an explicit error message.
95
class ForbiddenRequestHandler(TestingHTTPRequestHandler):
96
    """Whatever request comes in, returns a 403 code"""
97
98
    def parse_request(self):
99
        """Handle a single HTTP request, by replying we cannot handle it"""
100
        ignored = TestingHTTPRequestHandler.parse_request(self)
101
        self.send_error(403)
102
        return False
103
104
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
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
108
    the HTTP server.
109
    """
110
111
    def __init__(self):
112
        HttpServer.__init__(self, SmartRequestHandler)
113
114
115
class SmartRequestHandler(TestingHTTPRequestHandler):
116
    """Extend TestingHTTPRequestHandler to support smart client POSTs."""
117
118
    def do_POST(self):
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())))
143
        self.end_headers()
144
        self.wfile.write(out_buffer.getvalue())
145
146
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
147
class SingleRangeRequestHandler(TestingHTTPRequestHandler):
148
    """Always reply to range request as if they were single.
149
150
    Don't be explicit about it, just to annoy the clients.
151
    """
152
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)
157
158
159
class NoRangeRequestHandler(TestingHTTPRequestHandler):
160
    """Ignore range requests without notice"""
161
162
    # Just bypass the range handling done by TestingHTTPRequestHandler
163
    do_GET = SimpleHTTPRequestHandler.do_GET
164
165
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.
166
class TestCaseWithWebserver(TestCaseWithTransport):
167
    """A support class that provides readonly urls that are http://.
168
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
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.
1185.1.18 by Robert Collins
Lalo Martins remotebranch patch
172
    """
173
    def setUp(self):
1530.1.14 by Robert Collins
Remove duplicate web server from HTTPTestUtil.
174
        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 :)
175
        self.transport_readonly_server = HttpServer
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
176
177
178
class TestCaseWithTwoWebservers(TestCaseWithWebserver):
179
    """A support class providinf readonly urls (on two servers) that are http://.
180
181
    We setup two webservers to allows various tests involving
182
    proxies or redirections from one server to the other.
183
    """
184
    def setUp(self):
185
        super(TestCaseWithTwoWebservers, self).setUp()
186
        self.transport_secondary_server = HttpServer
187
        self.__secondary_server = None
188
189
    def create_transport_secondary_server(self):
190
        """Create a transport server from class defined at init.
191
192
        This is mostly a hook for daughter classes.
193
        """
194
        return self.transport_secondary_server()
195
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
203
204
205
class FakeProxyRequestHandler(TestingHTTPRequestHandler):
206
    """Append a '-proxied' suffix to file served"""
207
208
    def translate_path(self, path):
209
        return TestingHTTPRequestHandler.translate_path(self,
210
                                                        path + '-proxied')
211
212