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