/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.15 by John Arbash Meinel
Merge bzr.dev 5597 to resolve NEWS, aka bzr-2.3.txt
1
# Copyright (C) 2006-2011 Canonical Ltd
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
16
17
import errno
7479.2.1 by Jelmer Vernooij
Drop python2 support.
18
import http.client as http_client
19
import http.server as http_server
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
20
import os
2146.1.1 by Alexander Belchenko
fixes for test suite: forgotten imports in HttpServer.py
21
import posixpath
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
22
import random
23
import re
3111.1.2 by Vincent Ladeuil
Preparatory cleanup.
24
import socket
6973.11.7 by Jelmer Vernooij
Fix more tests.
25
import sys
7479.2.1 by Jelmer Vernooij
Drop python2 support.
26
from urllib.parse import urlparse
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
27
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
28
from .. import (
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
29
    osutils,
30
    urlutils,
31
)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
32
from . import test_server
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
33
34
35
class BadWebserverPath(ValueError):
36
    def __str__(self):
37
        return 'path %s is not in %s' % self.args
38
39
6791.2.3 by Jelmer Vernooij
Fix more imports.
40
class TestingHTTPRequestHandler(http_server.SimpleHTTPRequestHandler):
2420.1.10 by Vincent Ladeuil
Doc fixes.
41
    """Handles one request.
42
3111.1.21 by Vincent Ladeuil
Add some comments.
43
    A TestingHTTPRequestHandler is instantiated for every request received by
44
    the associated server. Note that 'request' here is inherited from the base
45
    TCPServer class, for the HTTP server it is really a connection which itself
46
    will handle one or several HTTP requests.
2420.1.10 by Vincent Ladeuil
Doc fixes.
47
    """
3111.1.24 by Vincent Ladeuil
Cleanups.
48
    # Default protocol version
49
    protocol_version = 'HTTP/1.1'
50
3111.1.2 by Vincent Ladeuil
Preparatory cleanup.
51
    # The Message-like class used to parse the request headers
6791.2.3 by Jelmer Vernooij
Fix more imports.
52
    MessageClass = http_client.HTTPMessage
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
53
3111.1.15 by Vincent Ladeuil
Provide a way to specify the protocol version at the server layer.
54
    def setup(self):
6791.2.3 by Jelmer Vernooij
Fix more imports.
55
        http_server.SimpleHTTPRequestHandler.setup(self)
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
56
        self._cwd = self.server._home_dir
3111.1.15 by Vincent Ladeuil
Provide a way to specify the protocol version at the server layer.
57
        tcs = self.server.test_case_server
58
        if tcs.protocol_version is not None:
59
            # If the test server forced a protocol version, use it
60
            self.protocol_version = tcs.protocol_version
61
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
62
    def log_message(self, format, *args):
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
63
        tcs = self.server.test_case_server
64
        tcs.log('webserver - %s - - [%s] %s "%s" "%s"',
65
                self.address_string(),
66
                self.log_date_time_string(),
67
                format % args,
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
68
                self.headers.get('referer', '-'),
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
69
                self.headers.get('user-agent', '-'))
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
70
71
    def handle_one_request(self):
72
        """Handle a single HTTP request.
73
2831.6.1 by Vincent Ladeuil
Remove some more noise from test suite.
74
        We catch all socket errors occurring when the client close the
75
        connection early to avoid polluting the test results.
76
        """
77
        try:
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
78
            self._handle_one_request()
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
79
        except socket.error as e:
3111.1.24 by Vincent Ladeuil
Cleanups.
80
            # Any socket error should close the connection, but some errors are
81
            # due to the client closing early and we don't want to pollute test
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
82
            # results, so we raise only the others.
83
            self.close_connection = 1
84
            if (len(e.args) == 0
85
                or e.args[0] not in (errno.EPIPE, errno.ECONNRESET,
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
86
                                     errno.ECONNABORTED, errno.EBADF)):
2831.6.1 by Vincent Ladeuil
Remove some more noise from test suite.
87
                raise
88
5354.1.1 by Vincent Ladeuil
Set a Content-Length header on errors for HTTP/1.1.
89
    error_content_type = 'text/plain'
90
    error_message_format = '''\
91
Error code: %(code)s.
92
Message: %(message)s.
93
'''
94
95
    def send_error(self, code, message=None):
96
        """Send and log an error reply.
97
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
98
        We redefine the python-provided version to be able to set a
5354.1.1 by Vincent Ladeuil
Set a Content-Length header on errors for HTTP/1.1.
99
        ``Content-Length`` header as some http/1.1 clients complain otherwise
100
        (see bug #568421).
101
102
        :param code: The HTTP error code.
103
104
        :param message: The explanation of the error code, Defaults to a short
105
             entry.
106
        """
107
108
        if message is None:
109
            try:
110
                message = self.responses[code][0]
111
            except KeyError:
112
                message = '???'
113
        self.log_error("code %d, message %s", code, message)
114
        content = (self.error_message_format %
115
                   {'code': code, 'message': message})
116
        self.send_response(code, message)
117
        self.send_header("Content-Type", self.error_content_type)
118
        self.send_header("Content-Length", "%d" % len(content))
119
        self.send_header('Connection', 'close')
120
        self.end_headers()
121
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
6973.11.6 by Jelmer Vernooij
Fix more http tests.
122
            self.wfile.write(content.encode('utf-8'))
5354.1.1 by Vincent Ladeuil
Set a Content-Length header on errors for HTTP/1.1.
123
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
124
    def _handle_one_request(self):
6791.2.3 by Jelmer Vernooij
Fix more imports.
125
        http_server.SimpleHTTPRequestHandler.handle_one_request(self)
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
126
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
127
    _range_regexp = re.compile(r'^(?P<start>\d+)-(?P<end>\d+)?$')
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
128
    _tail_regexp = re.compile(r'^-(?P<tail>\d+)$')
129
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
130
    def _parse_ranges(self, ranges_header, file_size):
131
        """Parse the range header value and returns ranges.
132
133
        RFC2616 14.35 says that syntactically invalid range specifiers MUST be
134
        ignored. In that case, we return None instead of a range list.
135
136
        :param ranges_header: The 'Range' header value.
137
138
        :param file_size: The size of the requested file.
139
140
        :return: A list of (start, end) tuples or None if some invalid range
141
            specifier is encountered.
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
142
        """
143
        if not ranges_header.startswith('bytes='):
144
            # Syntactically invalid header
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
145
            return None
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
146
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
147
        tail = None
148
        ranges = []
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
149
        ranges_header = ranges_header[len('bytes='):]
150
        for range_str in ranges_header.split(','):
151
            range_match = self._range_regexp.match(range_str)
152
            if range_match is not None:
2182.2.2 by v.ladeuil+lp at free
Thanks again to Aaron, the http server RFC2616 compliance
153
                start = int(range_match.group('start'))
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
154
                end_match = range_match.group('end')
155
                if end_match is None:
156
                    # RFC2616 says end is optional and default to file_size
157
                    end = file_size
158
                else:
159
                    end = int(end_match)
2182.2.2 by v.ladeuil+lp at free
Thanks again to Aaron, the http server RFC2616 compliance
160
                if start > end:
161
                    # Syntactically invalid range
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
162
                    return None
2182.2.2 by v.ladeuil+lp at free
Thanks again to Aaron, the http server RFC2616 compliance
163
                ranges.append((start, end))
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
164
            else:
165
                tail_match = self._tail_regexp.match(range_str)
166
                if tail_match is not None:
167
                    tail = int(tail_match.group('tail'))
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
168
                else:
169
                    # Syntactically invalid range
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
170
                    return None
171
        if tail is not None:
172
            # Normalize tail into ranges
173
            ranges.append((max(0, file_size - tail), file_size))
174
175
        checked_ranges = []
176
        for start, end in ranges:
177
            if start >= file_size:
178
                # RFC2616 14.35, ranges are invalid if start >= file_size
179
                return None
180
            # RFC2616 14.35, end values should be truncated
181
            # to file_size -1 if they exceed it
182
            end = min(end, file_size - 1)
183
            checked_ranges.append((start, end))
184
        return checked_ranges
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
185
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
186
    def _header_line_length(self, keyword, value):
187
        header_line = '%s: %s\r\n' % (keyword, value)
188
        return len(header_line)
189
3111.1.23 by Vincent Ladeuil
Make HTTP/1.1 the default implementation reveals one more bug.
190
    def send_head(self):
191
        """Overrides base implementation to work around a bug in python2.5."""
192
        path = self.translate_path(self.path)
193
        if os.path.isdir(path) and not self.path.endswith('/'):
194
            # redirect browser - doing basically what apache does when
195
            # DirectorySlash option is On which is quite common (braindead, but
196
            # common)
197
            self.send_response(301)
198
            self.send_header("Location", self.path + "/")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
199
            # Indicates that the body is empty for HTTP/1.1 clients
3111.1.23 by Vincent Ladeuil
Make HTTP/1.1 the default implementation reveals one more bug.
200
            self.send_header('Content-Length', '0')
201
            self.end_headers()
202
            return None
203
6791.2.3 by Jelmer Vernooij
Fix more imports.
204
        return http_server.SimpleHTTPRequestHandler.send_head(self)
3111.1.23 by Vincent Ladeuil
Make HTTP/1.1 the default implementation reveals one more bug.
205
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
206
    def send_range_content(self, file, start, length):
207
        file.seek(start)
208
        self.wfile.write(file.read(length))
209
210
    def get_single_range(self, file, file_size, start, end):
211
        self.send_response(206)
212
        length = end - start + 1
213
        self.send_header('Accept-Ranges', 'bytes')
214
        self.send_header("Content-Length", "%d" % length)
215
216
        self.send_header("Content-Type", 'application/octet-stream')
217
        self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
218
                                                              end,
219
                                                              file_size))
220
        self.end_headers()
221
        self.send_range_content(file, start, length)
222
223
    def get_multiple_ranges(self, file, file_size, ranges):
224
        self.send_response(206)
225
        self.send_header('Accept-Ranges', 'bytes')
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
226
        boundary = '%d' % random.randint(0, 0x7FFFFFFF)
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
227
        self.send_header('Content-Type',
228
                         'multipart/byteranges; boundary=%s' % boundary)
7045.5.4 by Jelmer Vernooij
Fix a few more tests.
229
        boundary_line = b'--%s\r\n' % boundary.encode('ascii')
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
230
        # Calculate the Content-Length
231
        content_length = 0
232
        for (start, end) in ranges:
233
            content_length += len(boundary_line)
234
            content_length += self._header_line_length(
235
                'Content-type', 'application/octet-stream')
236
            content_length += self._header_line_length(
237
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
7143.15.2 by Jelmer Vernooij
Run autopep8.
238
            content_length += len('\r\n')  # end headers
2929.3.19 by Vincent Ladeuil
Fix 1.1 related bugs in HTTP server, add HTTPS passing tests (by temporarily disabling pycurl certificate verification).
239
            content_length += end - start + 1
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
240
        content_length += len(boundary_line)
241
        self.send_header('Content-length', content_length)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
242
        self.end_headers()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
243
244
        # Send the multipart body
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
245
        for (start, end) in ranges:
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
246
            self.wfile.write(boundary_line)
247
            self.send_header('Content-type', 'application/octet-stream')
248
            self.send_header('Content-Range', 'bytes %d-%d/%d'
249
                             % (start, end, file_size))
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
250
            self.end_headers()
251
            self.send_range_content(file, start, end - start + 1)
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
252
        # Final boundary
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
253
        self.wfile.write(boundary_line)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
254
255
    def do_GET(self):
256
        """Serve a GET request.
257
258
        Handles the Range header.
259
        """
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
260
        # Update statistics
261
        self.server.test_case_server.GET_request_nb += 1
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
262
263
        path = self.translate_path(self.path)
264
        ranges_header_value = self.headers.get('Range')
265
        if ranges_header_value is None or os.path.isdir(path):
266
            # Let the mother class handle most cases
6791.2.3 by Jelmer Vernooij
Fix more imports.
267
            return http_server.SimpleHTTPRequestHandler.do_GET(self)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
268
269
        try:
270
            # Always read in binary mode. Opening files in text
271
            # mode may cause newline translations, making the
272
            # actual size of the content transmitted *less* than
273
            # the content-length!
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
274
            f = open(path, 'rb')
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
275
        except IOError:
276
            self.send_error(404, "File not found")
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
277
            return
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
278
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
279
        file_size = os.fstat(f.fileno())[6]
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
280
        ranges = self._parse_ranges(ranges_header_value, file_size)
281
        if not ranges:
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
282
            # RFC2616 14.16 and 14.35 says that when a server
283
            # encounters unsatisfiable range specifiers, it
284
            # SHOULD return a 416.
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
285
            f.close()
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
286
            # FIXME: We SHOULD send a Content-Range header too,
287
            # but the implementation of send_error does not
288
            # allows that. So far.
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
289
            self.send_error(416, "Requested range not satisfiable")
290
            return
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
291
292
        if len(ranges) == 1:
293
            (start, end) = ranges[0]
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
294
            self.get_single_range(f, file_size, start, end)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
295
        else:
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
296
            self.get_multiple_ranges(f, file_size, ranges)
297
        f.close()
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
298
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
299
    def translate_path(self, path):
300
        """Translate a /-separated PATH to the local filename syntax.
301
302
        If the server requires it, proxy the path before the usual translation
303
        """
304
        if self.server.test_case_server.proxy_requests:
305
            # We need to act as a proxy and accept absolute urls,
306
            # which SimpleHTTPRequestHandler (parent) is not
307
            # ready for. So we just drop the protocol://host:port
308
            # part in front of the request-url (because we know
309
            # we would not forward the request to *another*
310
            # proxy).
311
312
            # So we do what SimpleHTTPRequestHandler.translate_path
313
            # do beginning with python 2.4.3: abandon query
314
            # parameters, scheme, host port, etc (which ensure we
315
            # provide the right behaviour on all python versions).
6791.2.3 by Jelmer Vernooij
Fix more imports.
316
            path = urlparse(path)[2]
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
317
            # And now, we can apply *our* trick to proxy files
318
            path += '-proxied'
319
320
        return self._translate_path(path)
321
322
    def _translate_path(self, path):
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
323
        """Translate a /-separated PATH to the local filename syntax.
324
3221.9.5 by Ian Clatworthy
some tweaks from abentley's earlier review feedback
325
        Note that we're translating http URLs here, not file URLs.
326
        The URL root location is the server's startup directory.
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
327
        Components that mean special things to the local file system
328
        (e.g. drive or directory names) are ignored.  (XXX They should
329
        probably be diagnosed.)
330
331
        Override from python standard library to stop it calling os.getcwd()
332
        """
333
        # abandon query parameters
6791.2.3 by Jelmer Vernooij
Fix more imports.
334
        path = urlparse(path)[2]
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
335
        path = posixpath.normpath(urlutils.unquote(path))
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
336
        words = path.split('/')
337
        path = self._cwd
6631.4.2 by Martin
Remove uses of filter with None as first argument
338
        for num, word in enumerate(w for w in words if w):
3221.9.5 by Ian Clatworthy
some tweaks from abentley's earlier review feedback
339
            if num == 0:
340
                drive, word = os.path.splitdrive(word)
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
341
            head, word = os.path.split(word)
7143.15.2 by Jelmer Vernooij
Run autopep8.
342
            if word in (os.curdir, os.pardir):
343
                continue
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
344
            path = os.path.join(path, word)
345
        return path
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
346
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
347
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
348
class TestingHTTPServerMixin:
349
350
    def __init__(self, test_case_server):
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
351
        # test_case_server can be used to communicate between the
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
352
        # tests and the server (or the request handler and the
353
        # server), allowing dynamic behaviors to be defined from
354
        # the tests cases.
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
355
        self.test_case_server = test_case_server
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
356
        self._home_dir = test_case_server._home_dir
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
357
358
359
class TestingHTTPServer(test_server.TestingTCPServer, TestingHTTPServerMixin):
3111.1.3 by Vincent Ladeuil
Rework http test servers classes. Both 1.0 and 1.1 passing tests (1.1 forced manually).
360
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
361
    def __init__(self, server_address, request_handler_class,
362
                 test_case_server):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
363
        test_server.TestingTCPServer.__init__(self, server_address,
364
                                              request_handler_class)
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
365
        TestingHTTPServerMixin.__init__(self, test_case_server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
366
367
368
class TestingThreadingHTTPServer(test_server.TestingThreadingTCPServer,
369
                                 TestingHTTPServerMixin):
3111.1.3 by Vincent Ladeuil
Rework http test servers classes. Both 1.0 and 1.1 passing tests (1.1 forced manually).
370
    """A threading HTTP test server for HTTP 1.1.
371
372
    Since tests can initiate several concurrent connections to the same http
373
    server, we need an independent connection for each of them. We achieve that
374
    by spawning a new thread for each connection.
375
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
376
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
377
    def __init__(self, server_address, request_handler_class,
378
                 test_case_server):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
379
        test_server.TestingThreadingTCPServer.__init__(self, server_address,
380
                                                       request_handler_class)
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
381
        TestingHTTPServerMixin.__init__(self, test_case_server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
382
383
384
class HttpServer(test_server.TestingTCPServerInAThread):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
385
    """A test server for http transports.
386
387
    Subclasses can provide a specific request handler.
388
    """
389
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
390
    # The real servers depending on the protocol
391
    http_server_class = {'HTTP/1.0': TestingHTTPServer,
392
                         'HTTP/1.1': TestingThreadingHTTPServer,
393
                         }
394
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
395
    # Whether or not we proxy the requests (see
396
    # TestingHTTPRequestHandler.translate_path).
397
    proxy_requests = False
398
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
399
    # used to form the url that connects to this server
400
    _url_protocol = 'http'
401
3111.1.15 by Vincent Ladeuil
Provide a way to specify the protocol version at the server layer.
402
    def __init__(self, request_handler=TestingHTTPRequestHandler,
403
                 protocol_version=None):
404
        """Constructor.
405
406
        :param request_handler: a class that will be instantiated to handle an
407
            http connection (one or several requests).
408
409
        :param protocol_version: if specified, will override the protocol
410
            version of the request handler.
411
        """
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
412
        # Depending on the protocol version, we will create the approriate
413
        # server
414
        if protocol_version is None:
415
            # Use the request handler one
416
            proto_vers = request_handler.protocol_version
417
        else:
418
            # Use our own, it will be used to override the request handler
419
            # one too.
420
            proto_vers = protocol_version
421
        # Get the appropriate server class for the required protocol
422
        serv_cls = self.http_server_class.get(proto_vers, None)
423
        if serv_cls is None:
6791.2.3 by Jelmer Vernooij
Fix more imports.
424
            raise http_client.UnknownProtocol(proto_vers)
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
425
        self.host = 'localhost'
426
        self.port = 0
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
427
        super(HttpServer, self).__init__((self.host, self.port),
428
                                         serv_cls,
429
                                         request_handler)
430
        self.protocol_version = proto_vers
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
431
        # Allows tests to verify number of GET requests issued
432
        self.GET_request_nb = 0
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
433
        self._http_base_url = None
434
        self.logs = []
435
436
    def create_server(self):
5247.3.16 by Vincent Ladeuil
All http tests passing (including https).
437
        return self.server_class(
438
            (self.host, self.port), self.request_handler_class, self)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
439
440
    def _get_remote_url(self, path):
441
        path_parts = path.split(os.path.sep)
442
        if os.path.isabs(path):
443
            if path_parts[:len(self._local_path_parts)] != \
7143.15.2 by Jelmer Vernooij
Run autopep8.
444
                    self._local_path_parts:
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
445
                raise BadWebserverPath(path, self.test_dir)
446
            remote_path = '/'.join(path_parts[len(self._local_path_parts):])
447
        else:
448
            remote_path = '/'.join(path_parts)
449
450
        return self._http_base_url + remote_path
451
452
    def log(self, format, *args):
453
        """Capture Server log output."""
454
        self.logs.append(format % args)
455
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
456
    def start_server(self, backing_transport_server=None):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
457
        """See breezy.transport.Server.start_server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
458
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
459
        :param backing_transport_server: The transport that requests over this
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
460
            protocol should be forwarded to. Note that this is currently not
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
461
            supported for HTTP.
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
462
        """
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
463
        # XXX: TODO: make the server back onto vfs_server rather than local
464
        # disk.
4731.2.1 by Vincent Ladeuil
Don't use shutdown() to stop http servers.
465
        if not (backing_transport_server is None
5017.3.23 by Vincent Ladeuil
selftest -s bt.test_bzrdir passing
466
                or isinstance(backing_transport_server,
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
467
                              test_server.LocalURLServer)):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
468
            raise AssertionError(
4731.2.1 by Vincent Ladeuil
Don't use shutdown() to stop http servers.
469
                "HTTPServer currently assumes local transport, got %s" %
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
470
                backing_transport_server)
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
471
        self._home_dir = osutils.getcwd()
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
472
        self._local_path_parts = self._home_dir.split(os.path.sep)
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
473
        self.logs = []
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
474
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
475
        super(HttpServer, self).start_server()
476
        self._http_base_url = '%s://%s:%s/' % (
477
            self._url_protocol, self.host, self.port)
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
478
479
    def get_url(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
480
        """See breezy.transport.Server.get_url."""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
481
        return self._get_remote_url(self._home_dir)
482
483
    def get_bogus_url(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
484
        """See breezy.transport.Server.get_bogus_url."""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
485
        # this is chosen to try to prevent trouble with proxies, weird dns,
486
        # etc
2929.3.10 by Vincent Ladeuil
Add a fake https server and test facilities.
487
        return self._url_protocol + '://127.0.0.1:1/'