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