~bzr-pqm/bzr/bzr.dev

5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2005-2011 Canonical Ltd
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
2
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
7
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
12
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
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
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
16
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
17
"""Tests for HTTP implementations.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
18
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
19
This module defines a load_tests() method that parametrize tests classes for
20
transport implementation, http protocol versions and authentication schemes.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
21
"""
1540.3.3 by Martin Pool
Review updates of pycurl transport
22
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
25
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
26
import httplib
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
27
import SimpleHTTPServer
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
28
import socket
2420.1.20 by Vincent Ladeuil
Fix test failure on pqm.
29
import sys
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
30
import threading
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
31
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
32
import bzrlib
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
33
from bzrlib import (
2900.2.6 by Vincent Ladeuil
Make http aware of authentication config.
34
    config,
6472.2.3 by Jelmer Vernooij
More control dir.
35
    controldir,
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
36
    debug,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
37
    errors,
38
    osutils,
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
39
    remote as _mod_remote,
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
40
    tests,
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
41
    trace,
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
42
    transport,
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
43
    ui,
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
44
    )
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
45
from bzrlib.tests import (
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
46
    features,
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
47
    http_server,
3111.1.7 by Vincent Ladeuil
Further refactoring.
48
    http_utils,
5247.2.5 by Vincent Ladeuil
Some cleanups.
49
    test_server,
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
50
    )
5462.3.15 by Martin Pool
Turn variations into scenario lists
51
from bzrlib.tests.scenarios import (
5462.3.21 by Martin Pool
Rename to load_tests_apply_scenarios
52
    load_tests_apply_scenarios,
5462.3.15 by Martin Pool
Turn variations into scenario lists
53
    multiply_scenarios,
5462.3.2 by Martin Pool
Split variations code to bzrlib.tests.variations
54
    )
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
55
from bzrlib.transport import (
56
    http,
57
    remote,
58
    )
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
59
from bzrlib.transport.http import (
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
60
    _urllib,
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
61
    _urllib2_wrappers,
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
62
    )
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
63
64
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
65
if features.pycurl.available():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
66
    from bzrlib.transport.http._pycurl import PyCurlTransport
67
68
5462.3.21 by Martin Pool
Rename to load_tests_apply_scenarios
69
load_tests = load_tests_apply_scenarios
5462.3.15 by Martin Pool
Turn variations into scenario lists
70
71
72
def vary_by_http_client_implementation():
5462.3.1 by Martin Pool
Split out generation of scenario lists into TestVariations
73
    """Test the two libraries we can use, pycurl and urllib."""
5462.3.15 by Martin Pool
Turn variations into scenario lists
74
    transport_scenarios = [
75
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
76
                        _server=http_server.HttpServer_urllib,
77
                        _url_protocol='http+urllib',)),
78
        ]
79
    if features.pycurl.available():
80
        transport_scenarios.append(
81
            ('pycurl', dict(_transport=PyCurlTransport,
82
                            _server=http_server.HttpServer_PyCurl,
83
                            _url_protocol='http+pycurl',)))
84
    return transport_scenarios
85
86
87
def vary_by_http_protocol_version():
5462.3.1 by Martin Pool
Split out generation of scenario lists into TestVariations
88
    """Test on http/1.0 and 1.1"""
5462.3.15 by Martin Pool
Turn variations into scenario lists
89
    return [
90
        ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
91
        ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
92
        ]
93
94
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
95
def vary_by_http_auth_scheme():
96
    scenarios = [
97
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
98
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
99
        ('basicdigest',
100
            dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
101
        ]
102
    # Add some attributes common to all scenarios
103
    for scenario_id, scenario_dict in scenarios:
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
104
        scenario_dict.update(_auth_header='Authorization',
105
                             _username_prompt_prefix='',
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
106
                             _password_prompt_prefix='')
107
    return scenarios
108
109
5462.3.15 by Martin Pool
Turn variations into scenario lists
110
def vary_by_http_proxy_auth_scheme():
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
111
    scenarios = [
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
112
        ('proxy-basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
113
        ('proxy-digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
114
        ('proxy-basicdigest',
5462.3.15 by Martin Pool
Turn variations into scenario lists
115
            dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
116
        ]
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
117
    # Add some attributes common to all scenarios
118
    for scenario_id, scenario_dict in scenarios:
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
119
        scenario_dict.update(_auth_header='Proxy-Authorization',
120
                             _username_prompt_prefix='Proxy ',
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
121
                             _password_prompt_prefix='Proxy ')
122
    return scenarios
5462.3.15 by Martin Pool
Turn variations into scenario lists
123
124
125
def vary_by_http_activity():
126
    activity_scenarios = [
127
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
128
                            _transport=_urllib.HttpTransport_urllib,)),
129
        ]
6238.2.23 by Vincent Ladeuil
Using the right transport classes, creating a dedicated config store is not needed anymore.
130
    if features.pycurl.available():
131
        activity_scenarios.append(
132
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
133
                                _transport=PyCurlTransport,)),)
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
134
    if features.HTTPSServerFeature.available():
6238.2.23 by Vincent Ladeuil
Using the right transport classes, creating a dedicated config store is not needed anymore.
135
        # FIXME: Until we have a better way to handle self-signed certificates
136
        # (like allowing them in a test specific authentication.conf for
137
        # example), we need some specialized pycurl/urllib transport for tests.
138
        # -- vila 2012-01-20
139
        from bzrlib.tests import (
140
            ssl_certs,
141
            )
142
        class HTTPS_urllib_transport(_urllib.HttpTransport_urllib):
143
144
            def __init__(self, base, _from_transport=None):
145
                super(HTTPS_urllib_transport, self).__init__(
146
                    base, _from_transport=_from_transport,
147
                    ca_certs=ssl_certs.build_path('ca.crt'))
148
5462.3.15 by Martin Pool
Turn variations into scenario lists
149
        activity_scenarios.append(
150
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
6238.2.23 by Vincent Ladeuil
Using the right transport classes, creating a dedicated config store is not needed anymore.
151
                                  _transport=HTTPS_urllib_transport,)),)
152
        if features.pycurl.available():
5462.3.15 by Martin Pool
Turn variations into scenario lists
153
            class HTTPS_pycurl_transport(PyCurlTransport):
154
155
                def __init__(self, base, _from_transport=None):
156
                    super(HTTPS_pycurl_transport, self).__init__(
157
                        base, _from_transport)
158
                    self.cabundle = str(ssl_certs.build_path('ca.crt'))
159
160
            activity_scenarios.append(
161
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
162
                                    _transport=HTTPS_pycurl_transport,)),)
163
    return activity_scenarios
5462.3.1 by Martin Pool
Split out generation of scenario lists into TestVariations
164
165
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
166
class FakeManager(object):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
167
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
168
    def __init__(self):
169
        self.credentials = []
2004.3.1 by vila
Test ConnectionError exceptions.
170
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
171
    def add_password(self, realm, host, username, password):
172
        self.credentials.append([realm, host, username, password])
173
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
174
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
175
class RecordingServer(object):
176
    """A fake HTTP server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
177
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
178
    It records the bytes sent to it, and replies with a 200.
179
    """
180
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
181
    def __init__(self, expect_body_tail=None, scheme=''):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
182
        """Constructor.
183
184
        :type expect_body_tail: str
185
        :param expect_body_tail: a reply won't be sent until this string is
186
            received.
187
        """
188
        self._expect_body_tail = expect_body_tail
189
        self.host = None
190
        self.port = None
191
        self.received_bytes = ''
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
192
        self.scheme = scheme
193
194
    def get_url(self):
195
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
196
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
197
    def start_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
198
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
199
        self._sock.bind(('127.0.0.1', 0))
200
        self.host, self.port = self._sock.getsockname()
201
        self._ready = threading.Event()
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
202
        self._thread = test_server.TestThread(
5652.1.2 by Vincent Ladeuil
Use clearer names.
203
            sync_event=self._ready, target=self._accept_read_and_reply)
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
204
        self._thread.start()
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
205
        if 'threads' in tests.selftest_debug_flags:
5247.5.29 by Vincent Ladeuil
Fixed as per jam's review.
206
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
207
        self._ready.wait()
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
208
209
    def _accept_read_and_reply(self):
210
        self._sock.listen(1)
211
        self._ready.set()
5247.2.5 by Vincent Ladeuil
Some cleanups.
212
        conn, address = self._sock.accept()
213
        if self._expect_body_tail is not None:
214
            while not self.received_bytes.endswith(self._expect_body_tail):
215
                self.received_bytes += conn.recv(4096)
216
            conn.sendall('HTTP/1.1 200 OK\r\n')
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
217
        try:
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
218
            self._sock.close()
219
        except socket.error:
220
            # The client may have already closed the socket.
221
            pass
222
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
223
    def stop_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
224
        try:
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
225
            # Issue a fake connection to wake up the server and allow it to
226
            # finish quickly
5247.3.7 by Vincent Ladeuil
Provide connect_socket (socket.create_connection) for pythons older than 2.6.
227
            fake_conn = osutils.connect_socket((self.host, self.port))
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
228
            fake_conn.close()
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
229
        except socket.error:
230
            # We might have already closed it.  We don't care.
231
            pass
232
        self.host = None
233
        self.port = None
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
234
        self._thread.join()
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
235
        if 'threads' in tests.selftest_debug_flags:
5247.5.29 by Vincent Ladeuil
Fixed as per jam's review.
236
            sys.stderr.write('Thread  joined: %s\n' % (self._thread.ident,))
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
237
238
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
239
class TestAuthHeader(tests.TestCase):
240
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
241
    def parse_header(self, header, auth_handler_class=None):
242
        if auth_handler_class is None:
243
            auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
244
        self.auth_handler =  auth_handler_class()
245
        return self.auth_handler._parse_auth_header(header)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
246
247
    def test_empty_header(self):
248
        scheme, remainder = self.parse_header('')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
249
        self.assertEqual('', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
250
        self.assertIs(None, remainder)
251
252
    def test_negotiate_header(self):
253
        scheme, remainder = self.parse_header('Negotiate')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
254
        self.assertEqual('negotiate', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
255
        self.assertIs(None, remainder)
256
257
    def test_basic_header(self):
258
        scheme, remainder = self.parse_header(
259
            'Basic realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
260
        self.assertEqual('basic', scheme)
261
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
262
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
263
    def test_basic_extract_realm(self):
264
        scheme, remainder = self.parse_header(
265
            'Basic realm="Thou should not pass"',
266
            _urllib2_wrappers.BasicAuthHandler)
267
        match, realm = self.auth_handler.extract_realm(remainder)
268
        self.assertTrue(match is not None)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
269
        self.assertEqual('Thou should not pass', realm)
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
270
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
271
    def test_digest_header(self):
272
        scheme, remainder = self.parse_header(
273
            'Digest realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
274
        self.assertEqual('digest', scheme)
275
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
276
277
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
278
class TestHTTPRangeParsing(tests.TestCase):
279
280
    def setUp(self):
281
        super(TestHTTPRangeParsing, self).setUp()
282
        # We focus on range  parsing here and ignore everything else
283
        class RequestHandler(http_server.TestingHTTPRequestHandler):
284
            def setup(self): pass
285
            def handle(self): pass
286
            def finish(self): pass
287
5705.1.2 by Vincent Ladeuil
Fix spurious space and add a test.
288
        self.req_handler = RequestHandler(None, None, None)
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
289
290
    def assertRanges(self, ranges, header, file_size):
291
        self.assertEquals(ranges,
292
                          self.req_handler._parse_ranges(header, file_size))
293
294
    def test_simple_range(self):
295
        self.assertRanges([(0,2)], 'bytes=0-2', 12)
296
297
    def test_tail(self):
298
        self.assertRanges([(8, 11)], 'bytes=-4', 12)
299
300
    def test_tail_bigger_than_file(self):
301
        self.assertRanges([(0, 11)], 'bytes=-99', 12)
302
303
    def test_range_without_end(self):
304
        self.assertRanges([(4, 11)], 'bytes=4-', 12)
305
306
    def test_invalid_ranges(self):
307
        self.assertRanges(None, 'bytes=12-22', 12)
308
        self.assertRanges(None, 'bytes=1-3,12-22', 12)
5705.1.2 by Vincent Ladeuil
Fix spurious space and add a test.
309
        self.assertRanges(None, 'bytes=-', 12)
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
310
311
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
312
class TestHTTPServer(tests.TestCase):
313
    """Test the HTTP servers implementations."""
314
315
    def test_invalid_protocol(self):
316
        class BogusRequestHandler(http_server.TestingHTTPRequestHandler):
317
318
            protocol_version = 'HTTP/0.1'
319
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
320
        self.assertRaises(httplib.UnknownProtocol,
321
                          http_server.HttpServer, BogusRequestHandler)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
322
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
323
    def test_force_invalid_protocol(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
324
        self.assertRaises(httplib.UnknownProtocol,
325
                          http_server.HttpServer, protocol_version='HTTP/0.1')
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
326
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
327
    def test_server_start_and_stop(self):
328
        server = http_server.HttpServer()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
329
        self.addCleanup(server.stop_server)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
330
        server.start_server()
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
331
        self.assertTrue(server.server is not None)
332
        self.assertTrue(server.server.serving is not None)
5247.6.7 by Vincent Ladeuil
Merge propagate-exceptions into http-leaks resolving conflicts
333
        self.assertTrue(server.server.serving)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
334
335
    def test_create_http_server_one_zero(self):
336
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
337
338
            protocol_version = 'HTTP/1.0'
339
340
        server = http_server.HttpServer(RequestHandlerOneZero)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
341
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
342
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
343
344
    def test_create_http_server_one_one(self):
345
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
346
347
            protocol_version = 'HTTP/1.1'
348
349
        server = http_server.HttpServer(RequestHandlerOneOne)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
350
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
351
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
352
                              http_server.TestingThreadingHTTPServer)
353
354
    def test_create_http_server_force_one_one(self):
355
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
356
357
            protocol_version = 'HTTP/1.0'
358
359
        server = http_server.HttpServer(RequestHandlerOneZero,
360
                                        protocol_version='HTTP/1.1')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
361
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
362
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
363
                              http_server.TestingThreadingHTTPServer)
364
365
    def test_create_http_server_force_one_zero(self):
366
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
367
368
            protocol_version = 'HTTP/1.1'
369
370
        server = http_server.HttpServer(RequestHandlerOneOne,
371
                                        protocol_version='HTTP/1.0')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
372
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
373
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
374
                              http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
375
376
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
377
class TestWithTransport_pycurl(object):
378
    """Test case to inherit from if pycurl is present"""
379
380
    def _get_pycurl_maybe(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
381
        self.requireFeature(features.pycurl)
382
        return PyCurlTransport
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
383
384
    _transport = property(_get_pycurl_maybe)
385
386
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
387
class TestHttpTransportUrls(tests.TestCase):
388
    """Test the http urls."""
389
5462.3.15 by Martin Pool
Turn variations into scenario lists
390
    scenarios = vary_by_http_client_implementation()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
391
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
392
    def test_abs_url(self):
393
        """Construction of absolute http URLs"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
394
        t = self._transport('http://example.com/bzr/bzr.dev/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
395
        eq = self.assertEqualDiff
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
396
        eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
397
        eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
398
        eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
399
        eq(t.abspath('.bzr/1//2/./3'),
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
400
           'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
401
402
    def test_invalid_http_urls(self):
403
        """Trap invalid construction of urls"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
404
        self._transport('http://example.com/bzr/bzr.dev/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
405
        self.assertRaises(errors.InvalidURL,
406
                          self._transport,
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
407
                          'http://http://example.com/bzr/bzr.dev/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
408
409
    def test_http_root_urls(self):
410
        """Construction of URLs from server root"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
411
        t = self._transport('http://example.com/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
412
        eq = self.assertEqualDiff
413
        eq(t.abspath('.bzr/tree-version'),
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
414
           'http://example.com/.bzr/tree-version')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
415
416
    def test_http_impl_urls(self):
417
        """There are servers which ask for particular clients to connect"""
418
        server = self._server()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
419
        server.start_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
420
        try:
421
            url = server.get_url()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
422
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
423
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
424
            server.stop_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
425
426
3111.1.9 by Vincent Ladeuil
Most refactoring regarding parameterization for urllib/pycurl and custom
427
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
428
429
    # TODO: This should really be moved into another pycurl
430
    # specific test. When https tests will be implemented, take
431
    # this one into account.
432
    def test_pycurl_without_https_support(self):
433
        """Test that pycurl without SSL do not fail with a traceback.
434
435
        For the purpose of the test, we force pycurl to ignore
436
        https by supplying a fake version_info that do not
437
        support it.
438
        """
4913.2.13 by John Arbash Meinel
Finish the pycurl feature.
439
        self.requireFeature(features.pycurl)
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
440
        # Import the module locally now that we now it's available.
441
        pycurl = features.pycurl.module
3111.1.14 by Vincent Ladeuil
Fix test leakage.
442
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
443
        self.overrideAttr(pycurl, 'version_info',
444
                          # Fake the pycurl version_info This was taken from
445
                          # a windows pycurl without SSL (thanks to bialix)
446
                          lambda : (2,
447
                                    '7.13.2',
448
                                    462082,
449
                                    'i386-pc-win32',
450
                                    2576,
451
                                    None,
452
                                    0,
453
                                    None,
454
                                    ('ftp', 'gopher', 'telnet',
455
                                     'dict', 'ldap', 'http', 'file'),
456
                                    None,
457
                                    0,
458
                                    None))
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
459
        self.assertRaises(errors.DependencyNotPresent, self._transport,
460
                          'https://launchpad.net')
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
461
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
462
463
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
464
    """Test the http connections."""
465
5462.3.15 by Martin Pool
Turn variations into scenario lists
466
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
467
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
468
        vary_by_http_protocol_version(),
469
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
470
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
471
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
472
        super(TestHTTPConnections, self).setUp()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
473
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
474
                        transport=self.get_transport())
475
476
    def test_http_has(self):
477
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
478
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
479
        self.assertEqual(t.has('foo/bar'), True)
480
        self.assertEqual(len(server.logs), 1)
481
        self.assertContainsRe(server.logs[0],
482
            r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
483
484
    def test_http_has_not_found(self):
485
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
486
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
487
        self.assertEqual(t.has('not-found'), False)
488
        self.assertContainsRe(server.logs[1],
489
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
490
491
    def test_http_get(self):
492
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
493
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
494
        fp = t.get('foo/bar')
495
        self.assertEqualDiff(
496
            fp.read(),
497
            'contents of foo/bar\n')
498
        self.assertEqual(len(server.logs), 1)
499
        self.assertTrue(server.logs[0].find(
500
            '"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
501
            % bzrlib.__version__) > -1)
502
503
    def test_has_on_bogus_host(self):
504
        # Get a free address and don't 'accept' on it, so that we
505
        # can be sure there is no http handler there, but set a
506
        # reasonable timeout to not slow down tests too much.
507
        default_timeout = socket.getdefaulttimeout()
508
        try:
509
            socket.setdefaulttimeout(2)
510
            s = socket.socket()
511
            s.bind(('localhost', 0))
512
            t = self._transport('http://%s:%s/' % s.getsockname())
513
            self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
514
        finally:
515
            socket.setdefaulttimeout(default_timeout)
516
517
518
class TestHttpTransportRegistration(tests.TestCase):
519
    """Test registrations of various http implementations"""
520
5462.3.15 by Martin Pool
Turn variations into scenario lists
521
    scenarios = vary_by_http_client_implementation()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
522
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
523
    def test_http_registered(self):
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
524
        t = transport.get_transport_from_url(
525
            '%s://foo.com/' % self._url_protocol)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
526
        self.assertIsInstance(t, transport.Transport)
527
        self.assertIsInstance(t, self._transport)
528
529
530
class TestPost(tests.TestCase):
531
5462.3.15 by Martin Pool
Turn variations into scenario lists
532
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
533
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
534
        vary_by_http_protocol_version(),
535
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
536
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
537
    def test_post_body_is_received(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
538
        server = RecordingServer(expect_body_tail='end-of-body',
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
539
                                 scheme=self._url_protocol)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
540
        self.start_server(server)
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
541
        url = server.get_url()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
542
        # FIXME: needs a cleanup -- vila 20100611
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
543
        http_transport = transport.get_transport_from_url(url)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
544
        code, response = http_transport._post('abc def end-of-body')
545
        self.assertTrue(
546
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
547
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
5514.1.1 by Vincent Ladeuil
Correctly set the Content-Type header when POSTing.
548
        self.assertTrue('content-type: application/octet-stream\r'
549
                        in server.received_bytes.lower())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
550
        # The transport should not be assuming that the server can accept
551
        # chunked encoding the first time it connects, because HTTP/1.1, so we
552
        # check for the literal string.
553
        self.assertTrue(
554
            server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
555
556
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
557
class TestRangeHeader(tests.TestCase):
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
558
    """Test range_header method"""
559
560
    def check_header(self, value, ranges=[], tail=0):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
561
        offsets = [ (start, end - start + 1) for start, end in ranges]
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
562
        coalesce = transport.Transport._coalesce_offsets
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
563
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
564
        range_header = http.HttpTransportBase._range_header
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
565
        self.assertEqual(value, range_header(coalesced, tail))
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
566
567
    def test_range_header_single(self):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
568
        self.check_header('0-9', ranges=[(0,9)])
569
        self.check_header('100-109', ranges=[(100,109)])
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
570
571
    def test_range_header_tail(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
572
        self.check_header('-10', tail=10)
573
        self.check_header('-50', tail=50)
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
574
575
    def test_range_header_multi(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
576
        self.check_header('0-9,100-200,300-5000',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
577
                          ranges=[(0,9), (100, 200), (300,5000)])
578
579
    def test_range_header_mixed(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
580
        self.check_header('0-9,300-5000,-50',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
581
                          ranges=[(0,9), (300,5000)],
582
                          tail=50)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
583
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
584
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
585
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
586
    """Tests a specific request handler.
587
3111.1.31 by Vincent Ladeuil
Review feeback.
588
    Daughter classes are expected to override _req_handler_class
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
589
    """
590
5462.3.15 by Martin Pool
Turn variations into scenario lists
591
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
592
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
593
        vary_by_http_protocol_version(),
594
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
595
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
596
    # Provide a useful default
597
    _req_handler_class = http_server.TestingHTTPRequestHandler
598
599
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
600
        server = http_server.HttpServer(self._req_handler_class,
601
                                        protocol_version=self._protocol_version)
602
        server._url_protocol = self._url_protocol
603
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
604
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
605
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
606
        # TODO: This is duplicated for lots of the classes in this file
607
        return (features.pycurl.available()
608
                and self._transport == PyCurlTransport)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
609
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
610
611
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
612
    """Whatever request comes in, close the connection"""
613
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
614
    def _handle_one_request(self):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
615
        """Handle a single HTTP request, by abruptly closing the connection"""
616
        self.close_connection = 1
617
618
619
class TestWallServer(TestSpecificRequestHandler):
620
    """Tests exceptions during the connection phase"""
621
622
    _req_handler_class = WallRequestHandler
623
624
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
625
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
626
        # Unfortunately httplib (see HTTPResponse._read_status
627
        # for details) make no distinction between a closed
628
        # socket and badly formatted status line, so we can't
629
        # just test for ConnectionError, we have to test
4628.1.2 by Vincent Ladeuil
More complete fix.
630
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
631
        # instead of ConnectionError too.
632
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
633
                            errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
634
                          t.has, 'foo/bar')
635
636
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
637
        t = self.get_readonly_transport()
4628.1.2 by Vincent Ladeuil
More complete fix.
638
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
639
                           errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
640
                          t.get, 'foo/bar')
641
642
643
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
644
    """Whatever request comes in, returns a bad status"""
645
646
    def parse_request(self):
647
        """Fakes handling a single HTTP request, returns a bad status"""
648
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
649
        self.send_response(0, "Bad status")
650
        self.close_connection = 1
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
651
        return False
652
653
654
class TestBadStatusServer(TestSpecificRequestHandler):
655
    """Tests bad status from server."""
656
657
    _req_handler_class = BadStatusRequestHandler
658
659
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
660
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
661
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
662
663
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
664
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
665
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
666
667
668
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
669
    """Whatever request comes in, returns an invalid status"""
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
670
671
    def parse_request(self):
672
        """Fakes handling a single HTTP request, returns a bad status"""
673
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
674
        self.wfile.write("Invalid status line\r\n")
5247.6.6 by Vincent Ladeuil
Closing the connection is what pycurl was waiting for.
675
        # If we don't close the connection pycurl will hang. Since this is a
676
        # stress test we don't *have* to respect the protocol, but we don't
677
        # have to sabotage it too much either.
678
        self.close_connection = True
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
679
        return False
680
681
682
class TestInvalidStatusServer(TestBadStatusServer):
683
    """Tests invalid status from server.
684
685
    Both implementations raises the same error as for a bad status.
686
    """
687
688
    _req_handler_class = InvalidStatusRequestHandler
689
690
691
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
692
    """Whatever request comes in, returns a bad protocol version"""
693
694
    def parse_request(self):
695
        """Fakes handling a single HTTP request, returns a bad status"""
696
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
697
        # Returns an invalid protocol version, but curl just
698
        # ignores it and those cannot be tested.
699
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
700
                                           404,
701
                                           'Look at my protocol version'))
702
        return False
703
704
705
class TestBadProtocolServer(TestSpecificRequestHandler):
706
    """Tests bad protocol from server."""
707
708
    _req_handler_class = BadProtocolRequestHandler
709
710
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
711
        if self._testing_pycurl():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
712
            raise tests.TestNotApplicable(
713
                "pycurl doesn't check the protocol version")
714
        super(TestBadProtocolServer, self).setUp()
715
716
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
717
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
718
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
719
720
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
721
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
722
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
723
724
725
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
726
    """Whatever request comes in, returns a 403 code"""
727
728
    def parse_request(self):
729
        """Handle a single HTTP request, by replying we cannot handle it"""
730
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
731
        self.send_error(403)
732
        return False
733
734
735
class TestForbiddenServer(TestSpecificRequestHandler):
736
    """Tests forbidden server"""
737
738
    _req_handler_class = ForbiddenRequestHandler
739
740
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
741
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
742
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
743
744
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
745
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
746
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
747
748
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
749
class TestRecordingServer(tests.TestCase):
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
750
751
    def test_create(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
752
        server = RecordingServer(expect_body_tail=None)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
753
        self.assertEqual('', server.received_bytes)
754
        self.assertEqual(None, server.host)
755
        self.assertEqual(None, server.port)
756
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
757
    def test_setUp_and_stop(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
758
        server = RecordingServer(expect_body_tail=None)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
759
        server.start_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
760
        try:
761
            self.assertNotEqual(None, server.host)
762
            self.assertNotEqual(None, server.port)
763
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
764
            server.stop_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
765
        self.assertEqual(None, server.host)
766
        self.assertEqual(None, server.port)
767
768
    def test_send_receive_bytes(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
769
        server = RecordingServer(expect_body_tail='c', scheme='http')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
770
        self.start_server(server)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
771
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
772
        sock.connect((server.host, server.port))
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
773
        sock.sendall('abc')
774
        self.assertEqual('HTTP/1.1 200 OK\r\n',
775
                         osutils.recv_all(sock, 4096))
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
776
        self.assertEqual('abc', server.received_bytes)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
777
778
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
779
class TestRangeRequestServer(TestSpecificRequestHandler):
780
    """Tests readv requests against server.
781
782
    We test against default "normal" server.
783
    """
784
785
    def setUp(self):
786
        super(TestRangeRequestServer, self).setUp()
787
        self.build_tree_contents([('a', '0123456789')],)
788
789
    def test_readv(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
790
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
791
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
792
        self.assertEqual(l[0], (0, '0'))
793
        self.assertEqual(l[1], (1, '1'))
794
        self.assertEqual(l[2], (3, '34'))
795
        self.assertEqual(l[3], (9, '9'))
796
797
    def test_readv_out_of_order(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
798
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
799
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
800
        self.assertEqual(l[0], (1, '1'))
801
        self.assertEqual(l[1], (9, '9'))
802
        self.assertEqual(l[2], (0, '0'))
803
        self.assertEqual(l[3], (3, '34'))
804
805
    def test_readv_invalid_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
806
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
807
808
        # This is intentionally reading off the end of the file
809
        # since we are sure that it cannot get there
810
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
811
                              t.readv, 'a', [(1,1), (8,10)])
812
813
        # This is trying to seek past the end of the file, it should
814
        # also raise a special error
815
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
816
                              t.readv, 'a', [(12,2)])
817
818
    def test_readv_multiple_get_requests(self):
819
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
820
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
821
        # force transport to issue multiple requests
822
        t._max_readv_combine = 1
823
        t._max_get_ranges = 1
824
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
825
        self.assertEqual(l[0], (0, '0'))
826
        self.assertEqual(l[1], (1, '1'))
827
        self.assertEqual(l[2], (3, '34'))
828
        self.assertEqual(l[3], (9, '9'))
829
        # The server should have issued 4 requests
830
        self.assertEqual(4, server.GET_request_nb)
831
832
    def test_readv_get_max_size(self):
833
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
834
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
835
        # force transport to issue multiple requests by limiting the number of
836
        # bytes by request. Note that this apply to coalesced offsets only, a
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
837
        # single range will keep its size even if bigger than the limit.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
838
        t._get_max_size = 2
839
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
840
        self.assertEqual(l[0], (0, '0'))
841
        self.assertEqual(l[1], (1, '1'))
842
        self.assertEqual(l[2], (2, '2345'))
843
        self.assertEqual(l[3], (6, '6789'))
844
        # The server should have issued 3 requests
845
        self.assertEqual(3, server.GET_request_nb)
846
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
847
    def test_complete_readv_leave_pipe_clean(self):
848
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
849
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
850
        # force transport to issue multiple requests
851
        t._get_max_size = 2
5462.3.16 by Martin Pool
pyflakes cleanups
852
        list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
853
        # The server should have issued 3 requests
854
        self.assertEqual(3, server.GET_request_nb)
855
        self.assertEqual('0123456789', t.get_bytes('a'))
856
        self.assertEqual(4, server.GET_request_nb)
857
858
    def test_incomplete_readv_leave_pipe_clean(self):
859
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
860
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
861
        # force transport to issue multiple requests
862
        t._get_max_size = 2
863
        # Don't collapse readv results into a list so that we leave unread
864
        # bytes on the socket
865
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
866
        self.assertEqual((0, '0'), ireadv.next())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
867
        # The server should have issued one request so far
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
868
        self.assertEqual(1, server.GET_request_nb)
869
        self.assertEqual('0123456789', t.get_bytes('a'))
870
        # get_bytes issued an additional request, the readv pending ones are
871
        # lost
872
        self.assertEqual(2, server.GET_request_nb)
873
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
874
875
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
876
    """Always reply to range request as if they were single.
877
878
    Don't be explicit about it, just to annoy the clients.
879
    """
880
881
    def get_multiple_ranges(self, file, file_size, ranges):
882
        """Answer as if it was a single range request and ignores the rest"""
883
        (start, end) = ranges[0]
884
        return self.get_single_range(file, file_size, start, end)
885
886
887
class TestSingleRangeRequestServer(TestRangeRequestServer):
888
    """Test readv against a server which accept only single range requests"""
889
890
    _req_handler_class = SingleRangeRequestHandler
891
892
893
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
894
    """Only reply to simple range requests, errors out on multiple"""
895
896
    def get_multiple_ranges(self, file, file_size, ranges):
897
        """Refuses the multiple ranges request"""
898
        if len(ranges) > 1:
899
            file.close()
900
            self.send_error(416, "Requested range not satisfiable")
901
            return
902
        (start, end) = ranges[0]
903
        return self.get_single_range(file, file_size, start, end)
904
905
906
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
907
    """Test readv against a server which only accept single range requests"""
908
909
    _req_handler_class = SingleOnlyRangeRequestHandler
910
911
912
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
913
    """Ignore range requests without notice"""
914
915
    def do_GET(self):
916
        # Update the statistics
917
        self.server.test_case_server.GET_request_nb += 1
918
        # Just bypass the range handling done by TestingHTTPRequestHandler
919
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
920
921
922
class TestNoRangeRequestServer(TestRangeRequestServer):
923
    """Test readv against a server which do not accept range requests"""
924
925
    _req_handler_class = NoRangeRequestHandler
926
927
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
928
class MultipleRangeWithoutContentLengthRequestHandler(
929
    http_server.TestingHTTPRequestHandler):
930
    """Reply to multiple range requests without content length header."""
931
932
    def get_multiple_ranges(self, file, file_size, ranges):
933
        self.send_response(206)
934
        self.send_header('Accept-Ranges', 'bytes')
5462.3.16 by Martin Pool
pyflakes cleanups
935
        # XXX: this is strange; the 'random' name below seems undefined and
5462.3.19 by Martin Pool
Mention bug 658773 in comment
936
        # yet the tests pass -- mbp 2010-10-11 bug 658773
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
937
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
938
        self.send_header("Content-Type",
939
                         "multipart/byteranges; boundary=%s" % boundary)
940
        self.end_headers()
941
        for (start, end) in ranges:
942
            self.wfile.write("--%s\r\n" % boundary)
943
            self.send_header("Content-type", 'application/octet-stream')
944
            self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
945
                                                                  end,
946
                                                                  file_size))
947
            self.end_headers()
948
            self.send_range_content(file, start, end - start + 1)
949
        # Final boundary
950
        self.wfile.write("--%s\r\n" % boundary)
951
952
953
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
954
955
    _req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
956
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
957
958
class TruncatedMultipleRangeRequestHandler(
959
    http_server.TestingHTTPRequestHandler):
960
    """Reply to multiple range requests truncating the last ones.
961
962
    This server generates responses whose Content-Length describes all the
963
    ranges, but fail to include the last ones leading to client short reads.
964
    This has been observed randomly with lighttpd (bug #179368).
965
    """
966
967
    _truncated_ranges = 2
968
969
    def get_multiple_ranges(self, file, file_size, ranges):
970
        self.send_response(206)
971
        self.send_header('Accept-Ranges', 'bytes')
972
        boundary = 'tagada'
973
        self.send_header('Content-Type',
974
                         'multipart/byteranges; boundary=%s' % boundary)
975
        boundary_line = '--%s\r\n' % boundary
976
        # Calculate the Content-Length
977
        content_length = 0
978
        for (start, end) in ranges:
979
            content_length += len(boundary_line)
980
            content_length += self._header_line_length(
981
                'Content-type', 'application/octet-stream')
982
            content_length += self._header_line_length(
983
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
984
            content_length += len('\r\n') # end headers
985
            content_length += end - start # + 1
986
        content_length += len(boundary_line)
987
        self.send_header('Content-length', content_length)
988
        self.end_headers()
989
990
        # Send the multipart body
991
        cur = 0
992
        for (start, end) in ranges:
993
            self.wfile.write(boundary_line)
994
            self.send_header('Content-type', 'application/octet-stream')
995
            self.send_header('Content-Range', 'bytes %d-%d/%d'
996
                             % (start, end, file_size))
997
            self.end_headers()
998
            if cur + self._truncated_ranges >= len(ranges):
999
                # Abruptly ends the response and close the connection
1000
                self.close_connection = 1
1001
                return
1002
            self.send_range_content(file, start, end - start + 1)
1003
            cur += 1
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
1004
        # Final boundary
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
1005
        self.wfile.write(boundary_line)
1006
1007
1008
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
1009
1010
    _req_handler_class = TruncatedMultipleRangeRequestHandler
1011
1012
    def setUp(self):
1013
        super(TestTruncatedMultipleRangeServer, self).setUp()
1014
        self.build_tree_contents([('a', '0123456789')],)
1015
1016
    def test_readv_with_short_reads(self):
1017
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1018
        t = self.get_readonly_transport()
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
1019
        # Force separate ranges for each offset
1020
        t._bytes_to_read_before_seek = 0
1021
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1022
        self.assertEqual((0, '0'), ireadv.next())
1023
        self.assertEqual((2, '2'), ireadv.next())
1024
        if not self._testing_pycurl():
1025
            # Only one request have been issued so far (except for pycurl that
1026
            # try to read the whole response at once)
1027
            self.assertEqual(1, server.GET_request_nb)
1028
        self.assertEqual((4, '45'), ireadv.next())
1029
        self.assertEqual((9, '9'), ireadv.next())
1030
        # Both implementations issue 3 requests but:
1031
        # - urllib does two multiple (4 ranges, then 2 ranges) then a single
1032
        #   range,
1033
        # - pycurl does two multiple (4 ranges, 4 ranges) then a single range
1034
        self.assertEqual(3, server.GET_request_nb)
1035
        # Finally the client have tried a single range request and stays in
1036
        # that mode
1037
        self.assertEqual('single', t._range_hint)
1038
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
1039
5609.52.1 by Martin Pool
Cope with buggy squids interrupting the response before a mime multipart boundary
1040
class TruncatedBeforeBoundaryRequestHandler(
1041
    http_server.TestingHTTPRequestHandler):
1042
    """Truncation before a boundary, like in bug 198646"""
1043
1044
    _truncated_ranges = 1
1045
1046
    def get_multiple_ranges(self, file, file_size, ranges):
1047
        self.send_response(206)
1048
        self.send_header('Accept-Ranges', 'bytes')
1049
        boundary = 'tagada'
1050
        self.send_header('Content-Type',
1051
                         'multipart/byteranges; boundary=%s' % boundary)
1052
        boundary_line = '--%s\r\n' % boundary
1053
        # Calculate the Content-Length
1054
        content_length = 0
1055
        for (start, end) in ranges:
1056
            content_length += len(boundary_line)
1057
            content_length += self._header_line_length(
1058
                'Content-type', 'application/octet-stream')
1059
            content_length += self._header_line_length(
1060
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
1061
            content_length += len('\r\n') # end headers
1062
            content_length += end - start # + 1
1063
        content_length += len(boundary_line)
1064
        self.send_header('Content-length', content_length)
1065
        self.end_headers()
1066
1067
        # Send the multipart body
1068
        cur = 0
1069
        for (start, end) in ranges:
1070
            if cur + self._truncated_ranges >= len(ranges):
1071
                # Abruptly ends the response and close the connection
1072
                self.close_connection = 1
1073
                return
1074
            self.wfile.write(boundary_line)
1075
            self.send_header('Content-type', 'application/octet-stream')
1076
            self.send_header('Content-Range', 'bytes %d-%d/%d'
1077
                             % (start, end, file_size))
1078
            self.end_headers()
1079
            self.send_range_content(file, start, end - start + 1)
1080
            cur += 1
1081
        # Final boundary
1082
        self.wfile.write(boundary_line)
1083
1084
1085
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1086
    """Tests the case of bug 198646, disconnecting before a boundary."""
1087
1088
    _req_handler_class = TruncatedBeforeBoundaryRequestHandler
1089
1090
    def setUp(self):
1091
        super(TestTruncatedBeforeBoundary, self).setUp()
1092
        self.build_tree_contents([('a', '0123456789')],)
1093
1094
    def test_readv_with_short_reads(self):
1095
        server = self.get_readonly_server()
1096
        t = self.get_readonly_transport()
1097
        # Force separate ranges for each offset
1098
        t._bytes_to_read_before_seek = 0
1099
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1100
        self.assertEqual((0, '0'), ireadv.next())
1101
        self.assertEqual((2, '2'), ireadv.next())
1102
        self.assertEqual((4, '45'), ireadv.next())
1103
        self.assertEqual((9, '9'), ireadv.next())
1104
1105
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1106
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1107
    """Errors out when range specifiers exceed the limit"""
1108
1109
    def get_multiple_ranges(self, file, file_size, ranges):
1110
        """Refuses the multiple ranges request"""
1111
        tcs = self.server.test_case_server
1112
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1113
            file.close()
1114
            # Emulate apache behavior
1115
            self.send_error(400, "Bad Request")
1116
            return
1117
        return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1118
            self, file, file_size, ranges)
1119
1120
1121
class LimitedRangeHTTPServer(http_server.HttpServer):
1122
    """An HttpServer erroring out on requests with too much range specifiers"""
1123
1124
    def __init__(self, request_handler=LimitedRangeRequestHandler,
1125
                 protocol_version=None,
1126
                 range_limit=None):
1127
        http_server.HttpServer.__init__(self, request_handler,
1128
                                        protocol_version=protocol_version)
1129
        self.range_limit = range_limit
1130
1131
1132
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1133
    """Tests readv requests against a server erroring out on too much ranges."""
1134
5462.3.15 by Martin Pool
Turn variations into scenario lists
1135
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1136
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1137
        vary_by_http_protocol_version(),
1138
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1139
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1140
    # Requests with more range specifiers will error out
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1141
    range_limit = 3
1142
1143
    def create_transport_readonly_server(self):
1144
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1145
                                      protocol_version=self._protocol_version)
1146
1147
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
1148
        super(TestLimitedRangeRequestServer, self).setUp()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1149
        # We need to manipulate ranges that correspond to real chunks in the
1150
        # response, so we build a content appropriately.
1151
        filler = ''.join(['abcdefghij' for x in range(102)])
1152
        content = ''.join(['%04d' % v + filler for v in range(16)])
1153
        self.build_tree_contents([('a', content)],)
1154
1155
    def test_few_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1156
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1157
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1158
        self.assertEqual(l[0], (0, '0000'))
1159
        self.assertEqual(l[1], (1024, '0001'))
1160
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1161
1162
    def test_more_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1163
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1164
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1165
        self.assertEqual(l[0], (0, '0000'))
1166
        self.assertEqual(l[1], (1024, '0001'))
1167
        self.assertEqual(l[2], (4096, '0004'))
1168
        self.assertEqual(l[3], (8192, '0008'))
1169
        # The server will refuse to serve the first request (too much ranges),
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1170
        # a second request will succeed.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1171
        self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1172
1173
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1174
class TestHttpProxyWhiteBox(tests.TestCase):
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1175
    """Whitebox test proxy http authorization.
1176
2420.1.3 by Vincent Ladeuil
Implement http proxy basic authentication.
1177
    Only the urllib implementation is tested here.
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1178
    """
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1179
1180
    def _proxied_request(self):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1181
        handler = _urllib2_wrappers.ProxyHandler()
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1182
        request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1183
        handler.set_proxy(request, 'http')
1184
        return request
1185
5639.2.2 by Vincent Ladeuil
Add tests and comments to clarify the feature.
1186
    def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1187
        handler = _urllib2_wrappers.ProxyHandler()
1188
        self.assertEquals(expected,
1189
                          handler.evaluate_proxy_bypass(host, no_proxy))
1190
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1191
    def test_empty_user(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1192
        self.overrideEnv('http_proxy', 'http://bar.com')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1193
        request = self._proxied_request()
1194
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1195
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1196
    def test_user_with_at(self):
1197
        self.overrideEnv('http_proxy',
1198
                         'http://username@domain:password@proxy_host:1234')
1199
        request = self._proxied_request()
1200
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1201
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1202
    def test_invalid_proxy(self):
1203
        """A proxy env variable without scheme"""
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1204
        self.overrideEnv('http_proxy', 'host:1234')
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1205
        self.assertRaises(errors.InvalidURL, self._proxied_request)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1206
5639.2.2 by Vincent Ladeuil
Add tests and comments to clarify the feature.
1207
    def test_evaluate_proxy_bypass_true(self):
1208
        """The host is not proxied"""
1209
        self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1210
        self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1211
1212
    def test_evaluate_proxy_bypass_false(self):
1213
        """The host is proxied"""
1214
        self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1215
1216
    def test_evaluate_proxy_bypass_unknown(self):
1217
        """The host is not explicitly proxied"""
1218
        self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1219
        self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1220
1221
    def test_evaluate_proxy_bypass_empty_entries(self):
1222
        """Ignore empty entries"""
1223
        self.assertEvaluateProxyBypass(None, 'example.com', '')
1224
        self.assertEvaluateProxyBypass(None, 'example.com', ',')
1225
        self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
5639.2.1 by Martin Pool
Empty entries in the ``NO_PROXY`` variable are no longer treated as matching every host.
1226
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1227
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1228
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1229
    """Tests proxy server.
1230
1231
    Be aware that we do not setup a real proxy here. Instead, we
1232
    check that the *connection* goes through the proxy by serving
1233
    different content (the faked proxy server append '-proxied'
1234
    to the file names).
1235
    """
1236
5462.3.15 by Martin Pool
Turn variations into scenario lists
1237
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1238
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1239
        vary_by_http_protocol_version(),
1240
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1241
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1242
    # FIXME: We don't have an https server available, so we don't
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1243
    # test https connections. --vila toolongago
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1244
1245
    def setUp(self):
1246
        super(TestProxyHttpServer, self).setUp()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1247
        self.transport_secondary_server = http_utils.ProxyServer
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1248
        self.build_tree_contents([('foo', 'contents of foo\n'),
1249
                                  ('foo-proxied', 'proxied contents of foo\n')])
1250
        # Let's setup some attributes for tests
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1251
        server = self.get_readonly_server()
1252
        self.server_host_port = '%s:%d' % (server.host, server.port)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1253
        if self._testing_pycurl():
1254
            # Oh my ! pycurl does not check for the port as part of
1255
            # no_proxy :-( So we just test the host part
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1256
            self.no_proxy_host = server.host
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1257
        else:
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1258
            self.no_proxy_host = self.server_host_port
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1259
        # The secondary server is the proxy
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1260
        self.proxy_url = self.get_secondary_url()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1261
1262
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1263
        # TODO: This is duplicated for lots of the classes in this file
1264
        return (features.pycurl.available()
1265
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1266
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1267
    def assertProxied(self):
1268
        t = self.get_readonly_transport()
1269
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1270
1271
    def assertNotProxied(self):
1272
        t = self.get_readonly_transport()
1273
        self.assertEqual('contents of foo\n', t.get('foo').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1274
1275
    def test_http_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1276
        self.overrideEnv('http_proxy', self.proxy_url)
1277
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1278
1279
    def test_HTTP_PROXY(self):
1280
        if self._testing_pycurl():
1281
            # pycurl does not check HTTP_PROXY for security reasons
1282
            # (for use in a CGI context that we do not care
1283
            # about. Should we ?)
1284
            raise tests.TestNotApplicable(
1285
                'pycurl does not check HTTP_PROXY for security reasons')
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1286
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1287
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1288
1289
    def test_all_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1290
        self.overrideEnv('all_proxy', self.proxy_url)
1291
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1292
1293
    def test_ALL_PROXY(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1294
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1295
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1296
1297
    def test_http_proxy_with_no_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1298
        self.overrideEnv('no_proxy', self.no_proxy_host)
1299
        self.overrideEnv('http_proxy', self.proxy_url)
1300
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1301
1302
    def test_HTTP_PROXY_with_NO_PROXY(self):
1303
        if self._testing_pycurl():
1304
            raise tests.TestNotApplicable(
1305
                'pycurl does not check HTTP_PROXY for security reasons')
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1306
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1307
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1308
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1309
1310
    def test_all_proxy_with_no_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1311
        self.overrideEnv('no_proxy', self.no_proxy_host)
1312
        self.overrideEnv('all_proxy', self.proxy_url)
1313
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1314
1315
    def test_ALL_PROXY_with_NO_PROXY(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1316
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1317
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1318
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1319
1320
    def test_http_proxy_without_scheme(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1321
        self.overrideEnv('http_proxy', self.server_host_port)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1322
        if self._testing_pycurl():
1323
            # pycurl *ignores* invalid proxy env variables. If that ever change
1324
            # in the future, this test will fail indicating that pycurl do not
1325
            # ignore anymore such variables.
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1326
            self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1327
        else:
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1328
            self.assertRaises(errors.InvalidURL, self.assertProxied)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1329
1330
1331
class TestRanges(http_utils.TestCaseWithWebserver):
1332
    """Test the Range header in GET methods."""
1333
5462.3.15 by Martin Pool
Turn variations into scenario lists
1334
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1335
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1336
        vary_by_http_protocol_version(),
1337
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1338
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1339
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
1340
        super(TestRanges, self).setUp()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1341
        self.build_tree_contents([('a', '0123456789')],)
1342
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1343
    def create_transport_readonly_server(self):
1344
        return http_server.HttpServer(protocol_version=self._protocol_version)
1345
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1346
    def _file_contents(self, relpath, ranges):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1347
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1348
        offsets = [ (start, end - start + 1) for start, end in ranges]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1349
        coalesce = t._coalesce_offsets
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1350
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1351
        code, data = t._get(relpath, coalesced)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1352
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1353
        for start, end in ranges:
1354
            data.seek(start)
1355
            yield data.read(end - start + 1)
1356
1357
    def _file_tail(self, relpath, tail_amount):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1358
        t = self.get_readonly_transport()
1359
        code, data = t._get(relpath, [], tail_amount)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1360
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1361
        data.seek(-tail_amount, 2)
1362
        return data.read(tail_amount)
1363
1364
    def test_range_header(self):
1365
        # Valid ranges
1366
        map(self.assertEqual,['0', '234'],
1367
            list(self._file_contents('a', [(0,0), (2,4)])),)
1368
1369
    def test_range_header_tail(self):
1370
        self.assertEqual('789', self._file_tail('a', 3))
1371
1372
    def test_syntactically_invalid_range_header(self):
1373
        self.assertListRaises(errors.InvalidHttpRange,
1374
                          self._file_contents, 'a', [(4, 3)])
1375
1376
    def test_semantically_invalid_range_header(self):
1377
        self.assertListRaises(errors.InvalidHttpRange,
1378
                          self._file_contents, 'a', [(42, 128)])
1379
1380
1381
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1382
    """Test redirection between http servers."""
1383
5462.3.15 by Martin Pool
Turn variations into scenario lists
1384
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1385
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1386
        vary_by_http_protocol_version(),
1387
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1388
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1389
    def setUp(self):
1390
        super(TestHTTPRedirections, self).setUp()
1391
        self.build_tree_contents([('a', '0123456789'),
1392
                                  ('bundle',
1393
                                  '# Bazaar revision bundle v0.9\n#\n')
1394
                                  ],)
1395
1396
    def test_redirected(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1397
        self.assertRaises(errors.RedirectRequested,
1398
                          self.get_old_transport().get, 'a')
1399
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1400
1401
1402
class RedirectedRequest(_urllib2_wrappers.Request):
1403
    """Request following redirections. """
1404
1405
    init_orig = _urllib2_wrappers.Request.__init__
1406
1407
    def __init__(self, method, url, *args, **kwargs):
1408
        """Constructor.
1409
1410
        """
1411
        # Since the tests using this class will replace
1412
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1413
        # or we'll loop.
4208.3.2 by Andrew Bennetts
Fix one test failure in test_http under Python 2.7a0.
1414
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1415
        self.follow_redirections = True
1416
1417
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1418
def install_redirected_request(test):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1419
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1420
1421
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1422
def cleanup_http_redirection_connections(test):
1423
    # Some sockets are opened but never seen by _urllib, so we trap them at
1424
    # the _urllib2_wrappers level to be able to clean them up.
1425
    def socket_disconnect(sock):
1426
        try:
1427
            sock.shutdown(socket.SHUT_RDWR)
1428
            sock.close()
1429
        except socket.error:
1430
            pass
1431
    def connect(connection):
1432
        test.http_connect_orig(connection)
1433
        test.addCleanup(socket_disconnect, connection.sock)
1434
    test.http_connect_orig = test.overrideAttr(
1435
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1436
    def connect(connection):
1437
        test.https_connect_orig(connection)
1438
        test.addCleanup(socket_disconnect, connection.sock)
1439
    test.https_connect_orig = test.overrideAttr(
1440
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1441
1442
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1443
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1444
    """Test redirections.
1445
1446
    http implementations do not redirect silently anymore (they
1447
    do not redirect at all in fact). The mechanism is still in
1448
    place at the _urllib2_wrappers.Request level and these tests
1449
    exercise it.
1450
1451
    For the pycurl implementation
1452
    the redirection have been deleted as we may deprecate pycurl
1453
    and I have no place to keep a working implementation.
1454
    -- vila 20070212
1455
    """
1456
5462.3.15 by Martin Pool
Turn variations into scenario lists
1457
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1458
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1459
        vary_by_http_protocol_version(),
1460
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1461
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1462
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1463
        if (features.pycurl.available()
1464
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1465
            raise tests.TestNotApplicable(
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1466
                "pycurl doesn't redirect silently anymore")
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1467
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1468
        install_redirected_request(self)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1469
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1470
        self.build_tree_contents([('a','a'),
1471
                                  ('1/',),
1472
                                  ('1/a', 'redirected once'),
1473
                                  ('2/',),
1474
                                  ('2/a', 'redirected twice'),
1475
                                  ('3/',),
1476
                                  ('3/a', 'redirected thrice'),
1477
                                  ('4/',),
1478
                                  ('4/a', 'redirected 4 times'),
1479
                                  ('5/',),
1480
                                  ('5/a', 'redirected 5 times'),
1481
                                  ],)
1482
1483
    def test_one_redirection(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1484
        t = self.get_old_transport()
1485
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1486
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1487
                                       self.new_server.port)
1488
        self.old_server.redirections = \
1489
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1490
        self.assertEqual('redirected once', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1491
1492
    def test_five_redirections(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1493
        t = self.get_old_transport()
1494
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1495
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1496
                                       self.old_server.port)
1497
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1498
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1499
        self.old_server.redirections = [
1500
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1501
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1502
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1503
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1504
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1505
            ]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1506
        self.assertEqual('redirected 5 times', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1507
1508
1509
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1510
    """Test transport.do_catching_redirections."""
1511
5462.3.15 by Martin Pool
Turn variations into scenario lists
1512
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1513
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1514
        vary_by_http_protocol_version(),
1515
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1516
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1517
    def setUp(self):
1518
        super(TestDoCatchRedirections, self).setUp()
1519
        self.build_tree_contents([('a', '0123456789'),],)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1520
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1521
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1522
        self.old_transport = self.get_old_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1523
5247.3.31 by Vincent Ladeuil
Cleanup some imports in http_utils.py.
1524
    def get_a(self, t):
1525
        return t.get('a')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1526
1527
    def test_no_redirection(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1528
        t = self.get_new_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1529
1530
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1531
        self.assertEqual('0123456789',
1532
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1533
                self.get_a, t, None).read())
1534
1535
    def test_one_redirection(self):
1536
        self.redirections = 0
1537
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1538
        def redirected(t, exception, redirection_notice):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1539
            self.redirections += 1
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1540
            redirected_t = t._redirected_to(exception.source, exception.target)
1541
            return redirected_t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1542
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1543
        self.assertEqual('0123456789',
1544
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1545
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1546
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1547
1548
    def test_redirection_loop(self):
1549
1550
        def redirected(transport, exception, redirection_notice):
1551
            # By using the redirected url as a base dir for the
1552
            # *old* transport, we create a loop: a => a/a =>
1553
            # a/a/a
1554
            return self.old_transport.clone(exception.target)
1555
1556
        self.assertRaises(errors.TooManyRedirections,
1557
                          transport.do_catching_redirections,
1558
                          self.get_a, self.old_transport, redirected)
1559
1560
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
1561
def _setup_authentication_config(**kwargs):
1562
    conf = config.AuthenticationConfig()
1563
    conf._get_config().update({'httptest': kwargs})
1564
    conf._save()
1565
1566
1567
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1568
    """Unit tests for glue by which urllib2 asks us for authentication"""
1569
1570
    def test_get_user_password_without_port(self):
1571
        """We cope if urllib2 doesn't tell us the port.
1572
1573
        See https://bugs.launchpad.net/bzr/+bug/654684
1574
        """
1575
        user = 'joe'
1576
        password = 'foo'
1577
        _setup_authentication_config(scheme='http', host='localhost',
1578
                                     user=user, password=password)
1579
        handler = _urllib2_wrappers.HTTPAuthHandler()
1580
        got_pass = handler.get_user_password(dict(
1581
            user='joe',
1582
            protocol='http',
1583
            host='localhost',
1584
            path='/',
1585
            realm='Realm',
1586
            ))
1587
        self.assertEquals((user, password), got_pass)
1588
1589
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1590
class TestAuth(http_utils.TestCaseWithWebserver):
1591
    """Test authentication scheme"""
1592
5462.3.15 by Martin Pool
Turn variations into scenario lists
1593
    scenarios = multiply_scenarios(
1594
        vary_by_http_client_implementation(),
1595
        vary_by_http_protocol_version(),
1596
        vary_by_http_auth_scheme(),
1597
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1598
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1599
    def setUp(self):
1600
        super(TestAuth, self).setUp()
1601
        self.server = self.get_readonly_server()
1602
        self.build_tree_contents([('a', 'contents of a\n'),
1603
                                  ('b', 'contents of b\n'),])
1604
1605
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1606
        server = self._auth_server(protocol_version=self._protocol_version)
1607
        server._url_protocol = self._url_protocol
1608
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1609
1610
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1611
        # TODO: This is duplicated for lots of the classes in this file
1612
        return (features.pycurl.available()
1613
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1614
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1615
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1616
        """Build an url embedding user and password"""
1617
        url = '%s://' % self.server._url_protocol
1618
        if user is not None:
1619
            url += user
1620
            if password is not None:
1621
                url += ':' + password
1622
            url += '@'
1623
        url += '%s:%s/' % (self.server.host, self.server.port)
1624
        return url
1625
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1626
    def get_user_transport(self, user, password):
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
1627
        t = transport.get_transport_from_url(
1628
            self.get_user_url(user, password))
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1629
        return t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1630
1631
    def test_no_user(self):
1632
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1633
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1634
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1635
        # Only one 'Authentication Required' error should occur
1636
        self.assertEqual(1, self.server.auth_required_errors)
1637
1638
    def test_empty_pass(self):
1639
        self.server.add_user('joe', '')
1640
        t = self.get_user_transport('joe', '')
1641
        self.assertEqual('contents of a\n', t.get('a').read())
1642
        # Only one 'Authentication Required' error should occur
1643
        self.assertEqual(1, self.server.auth_required_errors)
1644
1645
    def test_user_pass(self):
1646
        self.server.add_user('joe', 'foo')
1647
        t = self.get_user_transport('joe', 'foo')
1648
        self.assertEqual('contents of a\n', t.get('a').read())
1649
        # Only one 'Authentication Required' error should occur
1650
        self.assertEqual(1, self.server.auth_required_errors)
1651
1652
    def test_unknown_user(self):
1653
        self.server.add_user('joe', 'foo')
1654
        t = self.get_user_transport('bill', 'foo')
1655
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1656
        # Two 'Authentication Required' errors should occur (the
1657
        # initial 'who are you' and 'I don't know you, who are
1658
        # you').
1659
        self.assertEqual(2, self.server.auth_required_errors)
1660
1661
    def test_wrong_pass(self):
1662
        self.server.add_user('joe', 'foo')
1663
        t = self.get_user_transport('joe', 'bar')
1664
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1665
        # Two 'Authentication Required' errors should occur (the
1666
        # initial 'who are you' and 'this is not you, who are you')
1667
        self.assertEqual(2, self.server.auth_required_errors)
1668
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1669
    def test_prompt_for_username(self):
1670
        if self._testing_pycurl():
1671
            raise tests.TestNotApplicable(
1672
                'pycurl cannot prompt, it handles auth by embedding'
1673
                ' user:pass in urls only')
1674
1675
        self.server.add_user('joe', 'foo')
1676
        t = self.get_user_transport(None, None)
1677
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1678
        stderr = tests.StringIOWrapper()
1679
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1680
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1681
        self.assertEqual('contents of a\n',t.get('a').read())
1682
        # stdin should be empty
1683
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1684
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1685
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1686
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1687
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1688
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1689
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1690
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1691
    def test_prompt_for_password(self):
1692
        if self._testing_pycurl():
1693
            raise tests.TestNotApplicable(
1694
                'pycurl cannot prompt, it handles auth by embedding'
1695
                ' user:pass in urls only')
1696
1697
        self.server.add_user('joe', 'foo')
1698
        t = self.get_user_transport('joe', None)
1699
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1700
        stderr = tests.StringIOWrapper()
1701
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1702
                                            stdout=stdout, stderr=stderr)
1703
        self.assertEqual('contents of a\n', t.get('a').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1704
        # stdin should be empty
1705
        self.assertEqual('', ui.ui_factory.stdin.readline())
1706
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1707
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1708
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1709
        # And we shouldn't prompt again for a different request
1710
        # against the same transport.
1711
        self.assertEqual('contents of b\n',t.get('b').read())
1712
        t2 = t.clone()
1713
        # And neither against a clone
1714
        self.assertEqual('contents of b\n',t2.get('b').read())
1715
        # Only one 'Authentication Required' error should occur
1716
        self.assertEqual(1, self.server.auth_required_errors)
1717
1718
    def _check_password_prompt(self, scheme, user, actual_prompt):
1719
        expected_prompt = (self._password_prompt_prefix
1720
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1721
                              % (scheme.upper(),
1722
                                 user, self.server.host, self.server.port,
1723
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1724
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1725
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1726
    def _expected_username_prompt(self, scheme):
1727
        return (self._username_prompt_prefix
1728
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1729
                                 self.server.host, self.server.port,
1730
                                 self.server.auth_realm))
1731
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1732
    def test_no_prompt_for_password_when_using_auth_config(self):
1733
        if self._testing_pycurl():
1734
            raise tests.TestNotApplicable(
1735
                'pycurl does not support authentication.conf'
1736
                ' since it cannot prompt')
1737
1738
        user =' joe'
1739
        password = 'foo'
1740
        stdin_content = 'bar\n'  # Not the right password
1741
        self.server.add_user(user, password)
1742
        t = self.get_user_transport(user, None)
1743
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1744
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1745
        # Create a minimal config file with the right password
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
1746
        _setup_authentication_config(scheme='http', port=self.server.port,
1747
                                     user=user, password=password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1748
        # Issue a request to the server to connect
1749
        self.assertEqual('contents of a\n',t.get('a').read())
1750
        # stdin should have  been left untouched
1751
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1752
        # Only one 'Authentication Required' error should occur
1753
        self.assertEqual(1, self.server.auth_required_errors)
1754
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1755
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1756
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1757
                                     http_utils.ProxyDigestAuthServer):
1758
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1759
        if self._testing_pycurl():
6050.1.2 by Martin
Make tests raising KnownFailure use the knownFailure method instead
1760
            self.knownFailure(
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1761
                'pycurl does not handle a nonce change')
1762
        self.server.add_user('joe', 'foo')
1763
        t = self.get_user_transport('joe', 'foo')
1764
        self.assertEqual('contents of a\n', t.get('a').read())
1765
        self.assertEqual('contents of b\n', t.get('b').read())
1766
        # Only one 'Authentication Required' error should have
1767
        # occured so far
1768
        self.assertEqual(1, self.server.auth_required_errors)
1769
        # The server invalidates the current nonce
1770
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1771
        self.assertEqual('contents of a\n', t.get('a').read())
1772
        # Two 'Authentication Required' errors should occur (the
1773
        # initial 'who are you' and a second 'who are you' with the new nonce)
1774
        self.assertEqual(2, self.server.auth_required_errors)
1775
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1776
    def test_user_from_auth_conf(self):
1777
        if self._testing_pycurl():
1778
            raise tests.TestNotApplicable(
1779
                'pycurl does not support authentication.conf')
1780
        user = 'joe'
1781
        password = 'foo'
1782
        self.server.add_user(user, password)
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
1783
        _setup_authentication_config(scheme='http', port=self.server.port,
1784
                                     user=user, password=password)
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1785
        t = self.get_user_transport(None, None)
1786
        # Issue a request to the server to connect
1787
        self.assertEqual('contents of a\n', t.get('a').read())
1788
        # Only one 'Authentication Required' error should occur
1789
        self.assertEqual(1, self.server.auth_required_errors)
1790
5957.2.3 by Vincent Ladeuil
Mask credentials in the -Dhttp logging
1791
    def test_no_credential_leaks_in_log(self):
1792
        self.overrideAttr(debug, 'debug_flags', set(['http']))
1793
        user = 'joe'
1794
        password = 'very-sensitive-password'
1795
        self.server.add_user(user, password)
1796
        t = self.get_user_transport(user, password)
1797
        # Capture the debug calls to mutter
1798
        self.mutters = []
1799
        def mutter(*args):
1800
            lines = args[0] % args[1:]
1801
            # Some calls output multiple lines, just split them now since we
1802
            # care about a single one later.
1803
            self.mutters.extend(lines.splitlines())
1804
        self.overrideAttr(trace, 'mutter', mutter)
1805
        # Issue a request to the server to connect
1806
        self.assertEqual(True, t.has('a'))
1807
        # Only one 'Authentication Required' error should occur
1808
        self.assertEqual(1, self.server.auth_required_errors)
1809
        # Since the authentification succeeded, there should be a corresponding
1810
        # debug line
1811
        sent_auth_headers = [line for line in self.mutters
1812
                             if line.startswith('> %s' % (self._auth_header,))]
1813
        self.assertLength(1, sent_auth_headers)
1814
        self.assertStartsWith(sent_auth_headers[0],
1815
                              '> %s: <masked>' % (self._auth_header,))
1816
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1817
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1818
class TestProxyAuth(TestAuth):
5957.2.1 by Vincent Ladeuil
Tweak the http Authorization tests to make some parts easier to reuse (parametrization mostly).
1819
    """Test proxy authentication schemes.
1820
1821
    This inherits from TestAuth to tweak the setUp and filter some failing
1822
    tests.
1823
    """
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1824
5462.3.15 by Martin Pool
Turn variations into scenario lists
1825
    scenarios = multiply_scenarios(
1826
        vary_by_http_client_implementation(),
1827
        vary_by_http_protocol_version(),
1828
        vary_by_http_proxy_auth_scheme(),
1829
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1830
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1831
    def setUp(self):
1832
        super(TestProxyAuth, self).setUp()
1833
        # Override the contents to avoid false positives
1834
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1835
                                  ('b', 'not proxied contents of b\n'),
1836
                                  ('a-proxied', 'contents of a\n'),
1837
                                  ('b-proxied', 'contents of b\n'),
1838
                                  ])
1839
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1840
    def get_user_transport(self, user, password):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1841
        self.overrideEnv('all_proxy', self.get_user_url(user, password))
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1842
        return TestAuth.get_user_transport(self, user, password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1843
1844
    def test_empty_pass(self):
1845
        if self._testing_pycurl():
1846
            import pycurl
1847
            if pycurl.version_info()[1] < '7.16.0':
6050.1.2 by Martin
Make tests raising KnownFailure use the knownFailure method instead
1848
                self.knownFailure(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1849
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1850
        super(TestProxyAuth, self).test_empty_pass()
1851
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1852
1853
class SampleSocket(object):
1854
    """A socket-like object for use in testing the HTTP request handler."""
1855
1856
    def __init__(self, socket_read_content):
1857
        """Constructs a sample socket.
1858
1859
        :param socket_read_content: a byte sequence
1860
        """
1861
        # Use plain python StringIO so we can monkey-patch the close method to
1862
        # not discard the contents.
1863
        from StringIO import StringIO
1864
        self.readfile = StringIO(socket_read_content)
1865
        self.writefile = StringIO()
1866
        self.writefile.close = lambda: None
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
1867
        self.close = lambda: None
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1868
1869
    def makefile(self, mode='r', bufsize=None):
1870
        if 'r' in mode:
1871
            return self.readfile
1872
        else:
1873
            return self.writefile
1874
1875
1876
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1877
5462.3.15 by Martin Pool
Turn variations into scenario lists
1878
    scenarios = multiply_scenarios(
5705.1.1 by Vincent Ladeuil
Correctly parse partial range specifiers in the HTTP test server
1879
        vary_by_http_client_implementation(),
5462.3.15 by Martin Pool
Turn variations into scenario lists
1880
        vary_by_http_protocol_version(),
1881
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1882
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1883
    def setUp(self):
1884
        super(SmartHTTPTunnellingTest, self).setUp()
1885
        # We use the VFS layer as part of HTTP tunnelling tests.
5570.3.6 by Vincent Ladeuil
Get rid of all _captureVar() calls, no test failures, pfew.
1886
        self.overrideEnv('BZR_NO_SMART_VFS', None)
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1887
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1888
        self.http_server = self.get_readonly_server()
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1889
1890
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1891
        server = http_utils.HTTPServerWithSmarts(
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1892
            protocol_version=self._protocol_version)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1893
        server._url_protocol = self._url_protocol
1894
        return server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1895
6472.2.3 by Jelmer Vernooij
More control dir.
1896
    def test_open_controldir(self):
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1897
        branch = self.make_branch('relpath')
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1898
        url = self.http_server.get_url() + 'relpath'
6472.2.3 by Jelmer Vernooij
More control dir.
1899
        bd = controldir.ControlDir.open(url)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
1900
        self.addCleanup(bd.transport.disconnect)
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1901
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1902
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1903
    def test_bulk_data(self):
1904
        # We should be able to send and receive bulk data in a single message.
1905
        # The 'readv' command in the smart protocol both sends and receives
1906
        # bulk data, so we use that.
1907
        self.build_tree(['data-file'])
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
1908
        http_transport = transport.get_transport_from_url(
1909
            self.http_server.get_url())
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1910
        medium = http_transport.get_smart_medium()
1911
        # Since we provide the medium, the url below will be mostly ignored
1912
        # during the test, as long as the path is '/'.
1913
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1914
                                                  medium=medium)
1915
        self.assertEqual(
1916
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1917
1918
    def test_http_send_smart_request(self):
1919
1920
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1921
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1922
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
1923
        http_transport = transport.get_transport_from_url(
1924
            self.http_server.get_url())
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1925
        medium = http_transport.get_smart_medium()
1926
        response = medium.send_http_smart_request(post_body)
1927
        reply_body = response.read()
1928
        self.assertEqual(expected_reply_body, reply_body)
1929
1930
    def test_smart_http_server_post_request_handler(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1931
        httpd = self.http_server.server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1932
1933
        socket = SampleSocket(
1934
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1935
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1936
            # for 1.0)
1937
            + 'Content-Length: 6\r\n'
1938
            '\r\n'
1939
            'hello\n')
1940
        # Beware: the ('localhost', 80) below is the
1941
        # client_address parameter, but we don't have one because
1942
        # we have defined a socket which is not bound to an
1943
        # address. The test framework never uses this client
1944
        # address, so far...
1945
        request_handler = http_utils.SmartRequestHandler(socket,
1946
                                                         ('localhost', 80),
1947
                                                         httpd)
1948
        response = socket.writefile.getvalue()
1949
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1950
        # This includes the end of the HTTP headers, and all the body.
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1951
        expected_end_of_response = '\r\n\r\nok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1952
        self.assertEndsWith(response, expected_end_of_response)
1953
1954
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1955
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1956
    """No smart server here request handler."""
1957
1958
    def do_POST(self):
1959
        self.send_error(403, "Forbidden")
1960
1961
1962
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1963
    """Test smart client behaviour against an http server without smarts."""
1964
1965
    _req_handler_class = ForbiddenRequestHandler
1966
1967
    def test_probe_smart_server(self):
1968
        """Test error handling against server refusing smart requests."""
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1969
        t = self.get_readonly_transport()
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1970
        # No need to build a valid smart request here, the server will not even
1971
        # try to interpret it.
1972
        self.assertRaises(errors.SmartProtocolError,
5599.3.6 by John Arbash Meinel
Revert the medium check, since it isn't necessary, and vila is worried about confusing people.
1973
                          t.get_smart_medium().send_http_smart_request,
1974
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1975
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
1976
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1977
class Test_redirected_to(tests.TestCase):
1978
5462.3.15 by Martin Pool
Turn variations into scenario lists
1979
    scenarios = vary_by_http_client_implementation()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1980
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1981
    def test_redirected_to_subdir(self):
1982
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1983
        r = t._redirected_to('http://www.example.com/foo',
1984
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1985
        self.assertIsInstance(r, type(t))
1986
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1987
        self.assertEqual(t._get_connection(), r._get_connection())
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
1988
        self.assertEquals('http://www.example.com/foo/subdir/', r.base)
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1989
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1990
    def test_redirected_to_self_with_slash(self):
1991
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1992
        r = t._redirected_to('http://www.example.com/foo',
1993
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1994
        self.assertIsInstance(r, type(t))
1995
        # Both transports share the some connection (one can argue that we
1996
        # should return the exact same transport here, but that seems
1997
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1998
        self.assertEqual(t._get_connection(), r._get_connection())
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1999
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2000
    def test_redirected_to_host(self):
2001
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
2002
        r = t._redirected_to('http://www.example.com/foo',
2003
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2004
        self.assertIsInstance(r, type(t))
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
2005
        self.assertEquals('http://foo.example.com/foo/subdir/',
6145.1.1 by Jelmer Vernooij
Add some tests.
2006
            r.external_url())
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2007
2008
    def test_redirected_to_same_host_sibling_protocol(self):
2009
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
2010
        r = t._redirected_to('http://www.example.com/foo',
2011
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2012
        self.assertIsInstance(r, type(t))
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
2013
        self.assertEquals('https://www.example.com/foo/',
6145.1.1 by Jelmer Vernooij
Add some tests.
2014
            r.external_url())
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2015
2016
    def test_redirected_to_same_host_different_protocol(self):
2017
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
2018
        r = t._redirected_to('http://www.example.com/foo',
2019
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2020
        self.assertNotEquals(type(r), type(t))
6145.1.1 by Jelmer Vernooij
Add some tests.
2021
        self.assertEquals('ftp://www.example.com/foo/', r.external_url())
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2022
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
2023
    def test_redirected_to_same_host_specific_implementation(self):
2024
        t = self._transport('http://www.example.com/foo')
2025
        r = t._redirected_to('http://www.example.com/foo',
2026
                             'https+urllib://www.example.com/foo')
2027
        self.assertEquals('https://www.example.com/foo/', r.external_url())
2028
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2029
    def test_redirected_to_different_host_same_user(self):
2030
        t = self._transport('http://joe@www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
2031
        r = t._redirected_to('http://www.example.com/foo',
2032
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
2033
        self.assertIsInstance(r, type(t))
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
2034
        self.assertEqual(t._parsed_url.user, r._parsed_url.user)
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
2035
        self.assertEquals('https://joe@foo.example.com/foo/', r.external_url())
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2036
2037
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2038
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
2039
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2040
2041
    The only thing we care about here is how many bytes travel on the wire. But
2042
    since we want to measure it for a real http client, we have to send it
2043
    correct responses.
2044
2045
    We expect to receive a *single* request nothing more (and we won't even
2046
    check what request it is, we just measure the bytes read until an empty
2047
    line.
2048
    """
2049
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
2050
    def _handle_one_request(self):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2051
        tcs = self.server.test_case_server
2052
        requestline = self.rfile.readline()
2053
        headers = self.MessageClass(self.rfile, 0)
2054
        # We just read: the request, the headers, an empty line indicating the
2055
        # end of the headers.
2056
        bytes_read = len(requestline)
2057
        for line in headers.headers:
2058
            bytes_read += len(line)
2059
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2060
        if requestline.startswith('POST'):
2061
            # The body should be a single line (or we don't know where it ends
2062
            # and we don't want to issue a blocking read)
2063
            body = self.rfile.readline()
2064
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2065
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2066
2067
        # We set the bytes written *before* issuing the write, the client is
2068
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
2069
2070
        # Doing the oppposite may lead to test failure: we may be interrupted
2071
        # after the write but before updating the value. The client can then
2072
        # continue and read the value *before* we can update it. And yes,
2073
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2074
        tcs.bytes_written = len(tcs.canned_response)
2075
        self.wfile.write(tcs.canned_response)
2076
2077
2078
class ActivityServerMixin(object):
2079
2080
    def __init__(self, protocol_version):
2081
        super(ActivityServerMixin, self).__init__(
2082
            request_handler=PredefinedRequestHandler,
2083
            protocol_version=protocol_version)
2084
        # Bytes read and written by the server
2085
        self.bytes_read = 0
2086
        self.bytes_written = 0
2087
        self.canned_response = None
2088
2089
2090
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
2091
    pass
2092
2093
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
2094
if features.HTTPSServerFeature.available():
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2095
    from bzrlib.tests import https_server
2096
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
2097
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2098
2099
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2100
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2101
    """Test socket activity reporting.
2102
2103
    We use a special purpose server to control the bytes sent and received and
2104
    be able to predict the activity on the client socket.
2105
    """
2106
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2107
    def setUp(self):
2108
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2109
        self.server.start_server()
6238.2.20 by Vincent Ladeuil
Call the proper base class setUp() and set the inheritance order correctly now that get_transport exists in the base class.
2110
        self.addCleanup(self.server.stop_server)
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2111
        _activities = {} # Don't close over self and create a cycle
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2112
        def report_activity(t, bytes, direction):
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2113
            count = _activities.get(direction, 0)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2114
            count += bytes
5340.15.1 by John Arbash Meinel
supersede exc-info branch
2115
            _activities[direction] = count
2116
        self.activities = _activities
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2117
        # We override at class level because constructors may propagate the
2118
        # bound method and render instance overriding ineffective (an
4031.3.1 by Frank Aspell
Fixing various typos
2119
        # alternative would be to define a specific ui factory instead...)
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2120
        self.overrideAttr(self._transport, '_report_activity', report_activity)
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2121
2122
    def get_transport(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2123
        t = self._transport(self.server.get_url())
2124
        # FIXME: Needs cleanup -- vila 20100611
2125
        return t
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2126
2127
    def assertActivitiesMatch(self):
2128
        self.assertEqual(self.server.bytes_read,
2129
                         self.activities.get('write', 0), 'written bytes')
2130
        self.assertEqual(self.server.bytes_written,
2131
                         self.activities.get('read', 0), 'read bytes')
2132
2133
    def test_get(self):
2134
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2135
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2136
Server: Apache/2.0.54 (Fedora)\r
2137
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2138
ETag: "56691-23-38e9ae00"\r
2139
Accept-Ranges: bytes\r
2140
Content-Length: 35\r
2141
Connection: close\r
2142
Content-Type: text/plain; charset=UTF-8\r
2143
\r
2144
Bazaar-NG meta directory, format 1
2145
'''
2146
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2147
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
2148
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2149
        self.assertActivitiesMatch()
2150
2151
    def test_has(self):
2152
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2153
Server: SimpleHTTP/0.6 Python/2.5.2\r
2154
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2155
Content-type: application/octet-stream\r
2156
Content-Length: 20\r
2157
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2158
\r
2159
'''
2160
        t = self.get_transport()
2161
        self.assertTrue(t.has('foo/bar'))
2162
        self.assertActivitiesMatch()
2163
2164
    def test_readv(self):
2165
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2166
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2167
Server: Apache/2.0.54 (Fedora)\r
2168
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2169
ETag: "238a3c-16ec2-805c5540"\r
2170
Accept-Ranges: bytes\r
2171
Content-Length: 1534\r
2172
Connection: close\r
2173
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2174
\r
2175
\r
2176
--418470f848b63279b\r
2177
Content-type: text/plain; charset=UTF-8\r
2178
Content-range: bytes 0-254/93890\r
2179
\r
2180
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2181
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2182
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2183
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2184
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2185
\r
2186
--418470f848b63279b\r
2187
Content-type: text/plain; charset=UTF-8\r
2188
Content-range: bytes 1000-2049/93890\r
2189
\r
2190
40-fd4ec249b6b139ab
2191
mbp@sourcefrog.net-20050311063625-07858525021f270b
2192
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2193
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2194
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2195
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2196
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2197
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2198
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2199
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2200
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2201
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2202
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2203
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2204
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2205
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2206
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2207
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2208
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2209
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2210
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2211
mbp@source\r
2212
--418470f848b63279b--\r
2213
'''
2214
        t = self.get_transport()
2215
        # Remember that the request is ignored and that the ranges below
2216
        # doesn't have to match the canned response.
2217
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2218
        self.assertEqual(2, len(l))
2219
        self.assertActivitiesMatch()
2220
2221
    def test_post(self):
2222
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2223
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2224
Server: Apache/2.0.54 (Fedora)\r
2225
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2226
ETag: "56691-23-38e9ae00"\r
2227
Accept-Ranges: bytes\r
2228
Content-Length: 35\r
2229
Connection: close\r
2230
Content-Type: text/plain; charset=UTF-8\r
2231
\r
2232
lalala whatever as long as itsssss
2233
'''
2234
        t = self.get_transport()
2235
        # We must send a single line of body bytes, see
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
2236
        # PredefinedRequestHandler._handle_one_request
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2237
        code, f = t._post('abc def end-of-body\n')
2238
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2239
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2240
2241
6238.2.23 by Vincent Ladeuil
Using the right transport classes, creating a dedicated config store is not needed anymore.
2242
class TestActivity(tests.TestCase, TestActivityMixin):
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2243
5462.3.15 by Martin Pool
Turn variations into scenario lists
2244
    scenarios = multiply_scenarios(
2245
        vary_by_http_activity(),
2246
        vary_by_http_protocol_version(),
2247
        )
5462.3.11 by Martin Pool
Delete test_http.load_tests, and just specify variations per test
2248
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2249
    def setUp(self):
6552.1.2 by Vincent Ladeuil
Stop assuming that classes deriving from TestActivityMixin will also derive directly from tests.TestCase.
2250
        super(TestActivity, self).setUp()
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2251
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2252
2253
6238.2.23 by Vincent Ladeuil
Using the right transport classes, creating a dedicated config store is not needed anymore.
2254
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2255
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2256
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2257
    # ReportingSocket, so we don't need all the parametrization. Since
2258
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2259
    # test them through their use by the transport than directly (that's a
2260
    # bit less clean but far more simpler and effective).
2261
    _activity_server = ActivityHTTPServer
2262
    _protocol_version = 'HTTP/1.1'
2263
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2264
    def setUp(self):
6552.1.2 by Vincent Ladeuil
Stop assuming that classes deriving from TestActivityMixin will also derive directly from tests.TestCase.
2265
        super(TestNoReportActivity, self).setUp()
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2266
        self._transport =_urllib.HttpTransport_urllib
2267
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2268
2269
    def assertActivitiesMatch(self):
2270
        # Nothing to check here
2271
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2272
2273
2274
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2275
    """Test authentication on the redirected http server."""
2276
5462.3.15 by Martin Pool
Turn variations into scenario lists
2277
    scenarios = vary_by_http_protocol_version()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
2278
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2279
    _auth_header = 'Authorization'
2280
    _password_prompt_prefix = ''
2281
    _username_prompt_prefix = ''
2282
    _auth_server = http_utils.HTTPBasicAuthServer
2283
    _transport = _urllib.HttpTransport_urllib
2284
2285
    def setUp(self):
2286
        super(TestAuthOnRedirected, self).setUp()
2287
        self.build_tree_contents([('a','a'),
2288
                                  ('1/',),
2289
                                  ('1/a', 'redirected once'),
2290
                                  ],)
2291
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2292
                                       self.new_server.port)
2293
        self.old_server.redirections = [
2294
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2295
        self.old_transport = self.get_old_transport()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2296
        self.new_server.add_user('joe', 'foo')
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
2297
        cleanup_http_redirection_connections(self)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2298
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2299
    def create_transport_readonly_server(self):
2300
        server = self._auth_server(protocol_version=self._protocol_version)
2301
        server._url_protocol = self._url_protocol
2302
        return server
2303
2304
    def get_a(self, t):
2305
        return t.get('a')
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2306
2307
    def test_auth_on_redirected_via_do_catching_redirections(self):
2308
        self.redirections = 0
2309
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2310
        def redirected(t, exception, redirection_notice):
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2311
            self.redirections += 1
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2312
            redirected_t = t._redirected_to(exception.source, exception.target)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2313
            self.addCleanup(redirected_t.disconnect)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2314
            return redirected_t
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2315
2316
        stdout = tests.StringIOWrapper()
2317
        stderr = tests.StringIOWrapper()
2318
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2319
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2320
        self.assertEqual('redirected once',
2321
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2322
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2323
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2324
        # stdin should be empty
2325
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2326
        # stdout should be empty, stderr will contains the prompts
2327
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2328
2329
    def test_auth_on_redirected_via_following_redirections(self):
2330
        self.new_server.add_user('joe', 'foo')
2331
        stdout = tests.StringIOWrapper()
2332
        stderr = tests.StringIOWrapper()
2333
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2334
                                            stdout=stdout, stderr=stderr)
2335
        t = self.old_transport
2336
        req = RedirectedRequest('GET', t.abspath('a'))
2337
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2338
                                       self.new_server.port)
2339
        self.old_server.redirections = [
2340
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2341
        self.assertEqual('redirected once', t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2342
        # stdin should be empty
2343
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2344
        # stdout should be empty, stderr will contains the prompts
2345
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2346