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