~bzr-pqm/bzr/bzr.dev

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