/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
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
190
    def send_range_content(self, file, start, length):
191
        file.seek(start)
192
        self.wfile.write(file.read(length))
193
194
    def get_single_range(self, file, file_size, start, end):
195
        self.send_response(206)
196
        length = end - start + 1
197
        self.send_header('Accept-Ranges', 'bytes')
198
        self.send_header("Content-Length", "%d" % length)
199
200
        self.send_header("Content-Type", 'application/octet-stream')
201
        self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
202
                                                              end,
203
                                                              file_size))
204
        self.end_headers()
205
        self.send_range_content(file, start, length)
206
207
    def get_multiple_ranges(self, file, file_size, ranges):
208
        self.send_response(206)
209
        self.send_header('Accept-Ranges', 'bytes')
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
210
        boundary = '%d' % random.randint(0, 0x7FFFFFFF)
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
211
        self.send_header('Content-Type',
212
                         'multipart/byteranges; boundary=%s' % boundary)
7045.5.4 by Jelmer Vernooij
Fix a few more tests.
213
        boundary_line = b'--%s\r\n' % boundary.encode('ascii')
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
214
        # Calculate the Content-Length
215
        content_length = 0
216
        for (start, end) in ranges:
217
            content_length += len(boundary_line)
218
            content_length += self._header_line_length(
219
                'Content-type', 'application/octet-stream')
220
            content_length += self._header_line_length(
221
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
7143.15.2 by Jelmer Vernooij
Run autopep8.
222
            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).
223
            content_length += end - start + 1
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
224
        content_length += len(boundary_line)
225
        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 :)
226
        self.end_headers()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
227
228
        # 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 :)
229
        for (start, end) in ranges:
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
230
            self.wfile.write(boundary_line)
231
            self.send_header('Content-type', 'application/octet-stream')
232
            self.send_header('Content-Range', 'bytes %d-%d/%d'
233
                             % (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 :)
234
            self.end_headers()
235
            self.send_range_content(file, start, end - start + 1)
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
236
        # Final boundary
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
237
        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 :)
238
239
    def do_GET(self):
240
        """Serve a GET request.
241
242
        Handles the Range header.
243
        """
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
244
        # Update statistics
245
        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 :)
246
247
        path = self.translate_path(self.path)
248
        ranges_header_value = self.headers.get('Range')
249
        if ranges_header_value is None or os.path.isdir(path):
250
            # Let the mother class handle most cases
6791.2.3 by Jelmer Vernooij
Fix more imports.
251
            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 :)
252
253
        try:
254
            # Always read in binary mode. Opening files in text
255
            # mode may cause newline translations, making the
256
            # actual size of the content transmitted *less* than
257
            # the content-length!
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
258
            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 :)
259
        except IOError:
260
            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 :)
261
            return
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
262
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
263
        file_size = os.fstat(f.fileno())[6]
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
264
        ranges = self._parse_ranges(ranges_header_value, file_size)
265
        if not ranges:
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
266
            # RFC2616 14.16 and 14.35 says that when a server
267
            # encounters unsatisfiable range specifiers, it
268
            # SHOULD return a 416.
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
269
            f.close()
2182.2.1 by v.ladeuil+lp at free
Aaron was right. Thanks to him, the http server RFC2616 compliance
270
            # FIXME: We SHOULD send a Content-Range header too,
271
            # but the implementation of send_error does not
272
            # 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 :)
273
            self.send_error(416, "Requested range not satisfiable")
274
            return
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
275
276
        if len(ranges) == 1:
277
            (start, end) = ranges[0]
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
278
            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 :)
279
        else:
5247.3.17 by Vincent Ladeuil
Fix another python tiny bug revealed by pycurl being picky.
280
            self.get_multiple_ranges(f, file_size, ranges)
281
        f.close()
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
282
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
283
    def translate_path(self, path):
284
        """Translate a /-separated PATH to the local filename syntax.
285
286
        If the server requires it, proxy the path before the usual translation
287
        """
288
        if self.server.test_case_server.proxy_requests:
289
            # We need to act as a proxy and accept absolute urls,
290
            # which SimpleHTTPRequestHandler (parent) is not
291
            # ready for. So we just drop the protocol://host:port
292
            # part in front of the request-url (because we know
293
            # we would not forward the request to *another*
294
            # proxy).
295
296
            # So we do what SimpleHTTPRequestHandler.translate_path
297
            # do beginning with python 2.4.3: abandon query
298
            # parameters, scheme, host port, etc (which ensure we
299
            # provide the right behaviour on all python versions).
6791.2.3 by Jelmer Vernooij
Fix more imports.
300
            path = urlparse(path)[2]
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
301
            # And now, we can apply *our* trick to proxy files
302
            path += '-proxied'
303
304
        return self._translate_path(path)
305
306
    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.
307
        """Translate a /-separated PATH to the local filename syntax.
308
3221.9.5 by Ian Clatworthy
some tweaks from abentley's earlier review feedback
309
        Note that we're translating http URLs here, not file URLs.
310
        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.
311
        Components that mean special things to the local file system
312
        (e.g. drive or directory names) are ignored.  (XXX They should
313
        probably be diagnosed.)
314
315
        Override from python standard library to stop it calling os.getcwd()
316
        """
317
        # abandon query parameters
6791.2.3 by Jelmer Vernooij
Fix more imports.
318
        path = urlparse(path)[2]
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
319
        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.
320
        words = path.split('/')
321
        path = self._cwd
6631.4.2 by Martin
Remove uses of filter with None as first argument
322
        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
323
            if num == 0:
324
                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.
325
            head, word = os.path.split(word)
7143.15.2 by Jelmer Vernooij
Run autopep8.
326
            if word in (os.curdir, os.pardir):
327
                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.
328
            path = os.path.join(path, word)
329
        return path
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
330
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
331
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
332
class TestingHTTPServerMixin:
333
334
    def __init__(self, test_case_server):
2164.2.28 by Vincent Ladeuil
TestingHTTPServer.test_case_server renamed from test_case to avoid confusions.
335
        # 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
336
        # tests and the server (or the request handler and the
337
        # server), allowing dynamic behaviors to be defined from
338
        # the tests cases.
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
339
        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.
340
        self._home_dir = test_case_server._home_dir
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
341
342
343
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).
344
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
345
    def __init__(self, server_address, request_handler_class,
346
                 test_case_server):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
347
        test_server.TestingTCPServer.__init__(self, server_address,
348
                                              request_handler_class)
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
349
        TestingHTTPServerMixin.__init__(self, test_case_server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
350
351
352
class TestingThreadingHTTPServer(test_server.TestingThreadingTCPServer,
353
                                 TestingHTTPServerMixin):
3111.1.3 by Vincent Ladeuil
Rework http test servers classes. Both 1.0 and 1.1 passing tests (1.1 forced manually).
354
    """A threading HTTP test server for HTTP 1.1.
355
356
    Since tests can initiate several concurrent connections to the same http
357
    server, we need an independent connection for each of them. We achieve that
358
    by spawning a new thread for each connection.
359
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
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.TestingThreadingTCPServer.__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 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 :)
369
    """A test server for http transports.
370
371
    Subclasses can provide a specific request handler.
372
    """
373
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
374
    # The real servers depending on the protocol
375
    http_server_class = {'HTTP/1.0': TestingHTTPServer,
376
                         'HTTP/1.1': TestingThreadingHTTPServer,
377
                         }
378
2420.1.9 by Vincent Ladeuil
Refactor proxy and auth test classes. Tests failing for digest auth.
379
    # Whether or not we proxy the requests (see
380
    # TestingHTTPRequestHandler.translate_path).
381
    proxy_requests = False
382
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
383
    # used to form the url that connects to this server
384
    _url_protocol = 'http'
385
3111.1.15 by Vincent Ladeuil
Provide a way to specify the protocol version at the server layer.
386
    def __init__(self, request_handler=TestingHTTPRequestHandler,
387
                 protocol_version=None):
388
        """Constructor.
389
390
        :param request_handler: a class that will be instantiated to handle an
391
            http connection (one or several requests).
392
393
        :param protocol_version: if specified, will override the protocol
394
            version of the request handler.
395
        """
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
396
        # Depending on the protocol version, we will create the approriate
397
        # server
398
        if protocol_version is None:
399
            # Use the request handler one
400
            proto_vers = request_handler.protocol_version
401
        else:
402
            # Use our own, it will be used to override the request handler
403
            # one too.
404
            proto_vers = protocol_version
405
        # Get the appropriate server class for the required protocol
406
        serv_cls = self.http_server_class.get(proto_vers, None)
407
        if serv_cls is None:
6791.2.3 by Jelmer Vernooij
Fix more imports.
408
            raise http_client.UnknownProtocol(proto_vers)
2164.2.13 by v.ladeuil+lp at free
Add tests for redirection. Preserve transport decorations.
409
        self.host = 'localhost'
410
        self.port = 0
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
411
        super(HttpServer, self).__init__((self.host, self.port),
412
                                         serv_cls,
413
                                         request_handler)
414
        self.protocol_version = proto_vers
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
415
        # Allows tests to verify number of GET requests issued
416
        self.GET_request_nb = 0
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
417
        self._http_base_url = None
418
        self.logs = []
419
420
    def create_server(self):
5247.3.16 by Vincent Ladeuil
All http tests passing (including https).
421
        return self.server_class(
422
            (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 :)
423
424
    def _get_remote_url(self, path):
425
        path_parts = path.split(os.path.sep)
426
        if os.path.isabs(path):
427
            if path_parts[:len(self._local_path_parts)] != \
7143.15.2 by Jelmer Vernooij
Run autopep8.
428
                    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 :)
429
                raise BadWebserverPath(path, self.test_dir)
430
            remote_path = '/'.join(path_parts[len(self._local_path_parts):])
431
        else:
432
            remote_path = '/'.join(path_parts)
433
434
        return self._http_base_url + remote_path
435
436
    def log(self, format, *args):
437
        """Capture Server log output."""
438
        self.logs.append(format % args)
439
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
440
    def start_server(self, backing_transport_server=None):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
441
        """See breezy.transport.Server.start_server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
442
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
443
        :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 :).
444
            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.
445
            supported for HTTP.
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
446
        """
2381.1.2 by Robert Collins
Fixup the test changes made for hpss to be clean and self contained.
447
        # XXX: TODO: make the server back onto vfs_server rather than local
448
        # disk.
4731.2.1 by Vincent Ladeuil
Don't use shutdown() to stop http servers.
449
        if not (backing_transport_server is None
5017.3.23 by Vincent Ladeuil
selftest -s bt.test_bzrdir passing
450
                or isinstance(backing_transport_server,
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
451
                              test_server.LocalURLServer)):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
452
            raise AssertionError(
4731.2.1 by Vincent Ladeuil
Don't use shutdown() to stop http servers.
453
                "HTTPServer currently assumes local transport, got %s" %
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
454
                backing_transport_server)
6619.3.26 by Martin
Fix fallout from 2to3 getcwdu transformation and other test uses
455
        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 :)
456
        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.
457
        self.logs = []
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
458
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
459
        super(HttpServer, self).start_server()
460
        self._http_base_url = '%s://%s:%s/' % (
461
            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 :)
462
463
    def get_url(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
464
        """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 :)
465
        return self._get_remote_url(self._home_dir)
466
467
    def get_bogus_url(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
468
        """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 :)
469
        # this is chosen to try to prevent trouble with proxies, weird dns,
470
        # etc
2929.3.10 by Vincent Ladeuil
Add a fake https server and test facilities.
471
        return self._url_protocol + '://127.0.0.1:1/'