/brz/remove-bazaar

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