/brz/remove-bazaar

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