1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
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.
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.
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
17
"""Tests for HTTP implementations.
19
This module defines a load_tests() method that parametrize tests classes for
20
transport implementation, http protocol versions and authentication schemes.
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
26
from cStringIO import StringIO
30
import SimpleHTTPServer
41
remote as _mod_remote,
47
from bzrlib.symbol_versioning import (
50
from bzrlib.tests import (
54
from bzrlib.transport import (
58
from bzrlib.transport.http import (
65
from bzrlib.transport.http._pycurl import PyCurlTransport
67
except errors.DependencyNotPresent:
68
pycurl_present = False
71
def load_tests(standard_tests, module, loader):
72
"""Multiply tests for http clients and protocol versions."""
73
result = loader.suiteClass()
74
adapter = tests.TestScenarioApplier()
75
remaining_tests = standard_tests
77
# one for each transport
78
t_tests, remaining_tests = tests.split_suite_by_condition(
79
remaining_tests, tests.condition_isinstance((
80
TestHttpTransportRegistration,
81
TestHttpTransportUrls,
84
transport_scenarios = [
85
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
86
_server=http_server.HttpServer_urllib,
87
_qualified_prefix='http+urllib',)),
90
transport_scenarios.append(
91
('pycurl', dict(_transport=PyCurlTransport,
92
_server=http_server.HttpServer_PyCurl,
93
_qualified_prefix='http+pycurl',)))
94
adapter.scenarios = transport_scenarios
95
tests.adapt_tests(t_tests, adapter, result)
97
# multiplied by one for each protocol version
98
tp_tests, remaining_tests = tests.split_suite_by_condition(
99
remaining_tests, tests.condition_isinstance((
100
SmartHTTPTunnellingTest,
101
TestDoCatchRedirections,
103
TestHTTPRedirections,
104
TestHTTPSilentRedirections,
105
TestLimitedRangeRequestServer,
109
TestSpecificRequestHandler,
111
protocol_scenarios = [
112
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
113
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
115
tp_scenarios = tests.multiply_scenarios(adapter.scenarios,
117
adapter.scenarios = tp_scenarios
118
tests.adapt_tests(tp_tests, adapter, result)
120
# multiplied by one for each authentication scheme
121
tpa_tests, remaining_tests = tests.split_suite_by_condition(
122
remaining_tests, tests.condition_isinstance((
125
auth_scheme_scenarios = [
126
('basic', dict(_auth_scheme='basic')),
127
('digest', dict(_auth_scheme='digest')),
129
adapter.scenarios = tests.multiply_scenarios(adapter.scenarios,
130
auth_scheme_scenarios)
131
tests.adapt_tests(tpa_tests, adapter, result)
133
tpact_tests, remaining_tests = tests.split_suite_by_condition(
134
remaining_tests, tests.condition_isinstance((
137
activity_scenarios = [
138
('http', dict(_activity_server=ActivityHTTPServer)),
140
if tests.HTTPSServerFeature.available():
141
activity_scenarios.append(
142
('https', dict(_activity_server=ActivityHTTPSServer,)))
143
adapter.scenarios = tests.multiply_scenarios(tp_scenarios,
145
tests.adapt_tests(tpact_tests, adapter, result)
147
# No parametrization for the remaining tests
148
result.addTests(remaining_tests)
153
class FakeManager(object):
156
self.credentials = []
158
def add_password(self, realm, host, username, password):
159
self.credentials.append([realm, host, username, password])
162
class RecordingServer(object):
163
"""A fake HTTP server.
165
It records the bytes sent to it, and replies with a 200.
168
def __init__(self, expect_body_tail=None):
171
:type expect_body_tail: str
172
:param expect_body_tail: a reply won't be sent until this string is
175
self._expect_body_tail = expect_body_tail
178
self.received_bytes = ''
181
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
182
self._sock.bind(('127.0.0.1', 0))
183
self.host, self.port = self._sock.getsockname()
184
self._ready = threading.Event()
185
self._thread = threading.Thread(target=self._accept_read_and_reply)
186
self._thread.setDaemon(True)
190
def _accept_read_and_reply(self):
193
self._sock.settimeout(5)
195
conn, address = self._sock.accept()
196
# On win32, the accepted connection will be non-blocking to start
197
# with because we're using settimeout.
198
conn.setblocking(True)
199
while not self.received_bytes.endswith(self._expect_body_tail):
200
self.received_bytes += conn.recv(4096)
201
conn.sendall('HTTP/1.1 200 OK\r\n')
202
except socket.timeout:
203
# Make sure the client isn't stuck waiting for us to e.g. accept.
206
# The client may have already closed the socket.
213
# We might have already closed it. We don't care.
219
class TestHTTPServer(tests.TestCase):
220
"""Test the HTTP servers implementations."""
222
def test_invalid_protocol(self):
223
class BogusRequestHandler(http_server.TestingHTTPRequestHandler):
225
protocol_version = 'HTTP/0.1'
227
server = http_server.HttpServer(BogusRequestHandler)
229
self.assertRaises(httplib.UnknownProtocol,server.setUp)
232
self.fail('HTTP Server creation did not raise UnknownProtocol')
234
def test_force_invalid_protocol(self):
235
server = http_server.HttpServer(protocol_version='HTTP/0.1')
237
self.assertRaises(httplib.UnknownProtocol,server.setUp)
240
self.fail('HTTP Server creation did not raise UnknownProtocol')
242
def test_server_start_and_stop(self):
243
server = http_server.HttpServer()
245
self.assertTrue(server._http_running)
247
self.assertFalse(server._http_running)
249
def test_create_http_server_one_zero(self):
250
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
252
protocol_version = 'HTTP/1.0'
254
server = http_server.HttpServer(RequestHandlerOneZero)
256
self.addCleanup(server.tearDown)
257
self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
259
def test_create_http_server_one_one(self):
260
class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
262
protocol_version = 'HTTP/1.1'
264
server = http_server.HttpServer(RequestHandlerOneOne)
266
self.addCleanup(server.tearDown)
267
self.assertIsInstance(server._httpd,
268
http_server.TestingThreadingHTTPServer)
270
def test_create_http_server_force_one_one(self):
271
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
273
protocol_version = 'HTTP/1.0'
275
server = http_server.HttpServer(RequestHandlerOneZero,
276
protocol_version='HTTP/1.1')
278
self.addCleanup(server.tearDown)
279
self.assertIsInstance(server._httpd,
280
http_server.TestingThreadingHTTPServer)
282
def test_create_http_server_force_one_zero(self):
283
class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
285
protocol_version = 'HTTP/1.1'
287
server = http_server.HttpServer(RequestHandlerOneOne,
288
protocol_version='HTTP/1.0')
290
self.addCleanup(server.tearDown)
291
self.assertIsInstance(server._httpd,
292
http_server.TestingHTTPServer)
295
class TestWithTransport_pycurl(object):
296
"""Test case to inherit from if pycurl is present"""
298
def _get_pycurl_maybe(self):
300
from bzrlib.transport.http._pycurl import PyCurlTransport
301
return PyCurlTransport
302
except errors.DependencyNotPresent:
303
raise tests.TestSkipped('pycurl not present')
305
_transport = property(_get_pycurl_maybe)
308
class TestHttpUrls(tests.TestCase):
310
# TODO: This should be moved to authorization tests once they
313
def test_url_parsing(self):
315
url = http.extract_auth('http://example.com', f)
316
self.assertEquals('http://example.com', url)
317
self.assertEquals(0, len(f.credentials))
318
url = http.extract_auth(
319
'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
320
self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
321
self.assertEquals(1, len(f.credentials))
322
self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
326
class TestHttpTransportUrls(tests.TestCase):
327
"""Test the http urls."""
329
def test_abs_url(self):
330
"""Construction of absolute http URLs"""
331
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
332
eq = self.assertEqualDiff
333
eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
334
eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
335
eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
336
eq(t.abspath('.bzr/1//2/./3'),
337
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
339
def test_invalid_http_urls(self):
340
"""Trap invalid construction of urls"""
341
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
342
self.assertRaises(errors.InvalidURL,
344
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
346
def test_http_root_urls(self):
347
"""Construction of URLs from server root"""
348
t = self._transport('http://bzr.ozlabs.org/')
349
eq = self.assertEqualDiff
350
eq(t.abspath('.bzr/tree-version'),
351
'http://bzr.ozlabs.org/.bzr/tree-version')
353
def test_http_impl_urls(self):
354
"""There are servers which ask for particular clients to connect"""
355
server = self._server()
358
url = server.get_url()
359
self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
364
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
366
# TODO: This should really be moved into another pycurl
367
# specific test. When https tests will be implemented, take
368
# this one into account.
369
def test_pycurl_without_https_support(self):
370
"""Test that pycurl without SSL do not fail with a traceback.
372
For the purpose of the test, we force pycurl to ignore
373
https by supplying a fake version_info that do not
379
raise tests.TestSkipped('pycurl not present')
381
version_info_orig = pycurl.version_info
383
# Now that we have pycurl imported, we can fake its version_info
384
# This was taken from a windows pycurl without SSL
386
pycurl.version_info = lambda : (2,
394
('ftp', 'gopher', 'telnet',
395
'dict', 'ldap', 'http', 'file'),
399
self.assertRaises(errors.DependencyNotPresent, self._transport,
400
'https://launchpad.net')
402
# Restore the right function
403
pycurl.version_info = version_info_orig
406
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
407
"""Test the http connections."""
410
http_utils.TestCaseWithWebserver.setUp(self)
411
self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
412
transport=self.get_transport())
414
def test_http_has(self):
415
server = self.get_readonly_server()
416
t = self._transport(server.get_url())
417
self.assertEqual(t.has('foo/bar'), True)
418
self.assertEqual(len(server.logs), 1)
419
self.assertContainsRe(server.logs[0],
420
r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
422
def test_http_has_not_found(self):
423
server = self.get_readonly_server()
424
t = self._transport(server.get_url())
425
self.assertEqual(t.has('not-found'), False)
426
self.assertContainsRe(server.logs[1],
427
r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
429
def test_http_get(self):
430
server = self.get_readonly_server()
431
t = self._transport(server.get_url())
432
fp = t.get('foo/bar')
433
self.assertEqualDiff(
435
'contents of foo/bar\n')
436
self.assertEqual(len(server.logs), 1)
437
self.assertTrue(server.logs[0].find(
438
'"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
439
% bzrlib.__version__) > -1)
441
def test_has_on_bogus_host(self):
442
# Get a free address and don't 'accept' on it, so that we
443
# can be sure there is no http handler there, but set a
444
# reasonable timeout to not slow down tests too much.
445
default_timeout = socket.getdefaulttimeout()
447
socket.setdefaulttimeout(2)
449
s.bind(('localhost', 0))
450
t = self._transport('http://%s:%s/' % s.getsockname())
451
self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
453
socket.setdefaulttimeout(default_timeout)
456
class TestHttpTransportRegistration(tests.TestCase):
457
"""Test registrations of various http implementations"""
459
def test_http_registered(self):
460
t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
461
self.assertIsInstance(t, transport.Transport)
462
self.assertIsInstance(t, self._transport)
465
class TestPost(tests.TestCase):
467
def test_post_body_is_received(self):
468
server = RecordingServer(expect_body_tail='end-of-body')
470
self.addCleanup(server.tearDown)
471
scheme = self._qualified_prefix
472
url = '%s://%s:%s/' % (scheme, server.host, server.port)
473
http_transport = self._transport(url)
474
code, response = http_transport._post('abc def end-of-body')
476
server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
477
self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
478
# The transport should not be assuming that the server can accept
479
# chunked encoding the first time it connects, because HTTP/1.1, so we
480
# check for the literal string.
482
server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
485
class TestRangeHeader(tests.TestCase):
486
"""Test range_header method"""
488
def check_header(self, value, ranges=[], tail=0):
489
offsets = [ (start, end - start + 1) for start, end in ranges]
490
coalesce = transport.Transport._coalesce_offsets
491
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
492
range_header = http.HttpTransportBase._range_header
493
self.assertEqual(value, range_header(coalesced, tail))
495
def test_range_header_single(self):
496
self.check_header('0-9', ranges=[(0,9)])
497
self.check_header('100-109', ranges=[(100,109)])
499
def test_range_header_tail(self):
500
self.check_header('-10', tail=10)
501
self.check_header('-50', tail=50)
503
def test_range_header_multi(self):
504
self.check_header('0-9,100-200,300-5000',
505
ranges=[(0,9), (100, 200), (300,5000)])
507
def test_range_header_mixed(self):
508
self.check_header('0-9,300-5000,-50',
509
ranges=[(0,9), (300,5000)],
513
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
514
"""Tests a specific request handler.
516
Daughter classes are expected to override _req_handler_class
519
# Provide a useful default
520
_req_handler_class = http_server.TestingHTTPRequestHandler
522
def create_transport_readonly_server(self):
523
return http_server.HttpServer(self._req_handler_class,
524
protocol_version=self._protocol_version)
526
def _testing_pycurl(self):
527
return pycurl_present and self._transport == PyCurlTransport
530
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
531
"""Whatever request comes in, close the connection"""
533
def handle_one_request(self):
534
"""Handle a single HTTP request, by abruptly closing the connection"""
535
self.close_connection = 1
538
class TestWallServer(TestSpecificRequestHandler):
539
"""Tests exceptions during the connection phase"""
541
_req_handler_class = WallRequestHandler
543
def test_http_has(self):
544
server = self.get_readonly_server()
545
t = self._transport(server.get_url())
546
# Unfortunately httplib (see HTTPResponse._read_status
547
# for details) make no distinction between a closed
548
# socket and badly formatted status line, so we can't
549
# just test for ConnectionError, we have to test
550
# InvalidHttpResponse too.
551
self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
554
def test_http_get(self):
555
server = self.get_readonly_server()
556
t = self._transport(server.get_url())
557
self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
561
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
562
"""Whatever request comes in, returns a bad status"""
564
def parse_request(self):
565
"""Fakes handling a single HTTP request, returns a bad status"""
566
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
567
self.send_response(0, "Bad status")
568
self.close_connection = 1
572
class TestBadStatusServer(TestSpecificRequestHandler):
573
"""Tests bad status from server."""
575
_req_handler_class = BadStatusRequestHandler
577
def test_http_has(self):
578
server = self.get_readonly_server()
579
t = self._transport(server.get_url())
580
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
582
def test_http_get(self):
583
server = self.get_readonly_server()
584
t = self._transport(server.get_url())
585
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
588
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
589
"""Whatever request comes in, returns an invalid status"""
591
def parse_request(self):
592
"""Fakes handling a single HTTP request, returns a bad status"""
593
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
594
self.wfile.write("Invalid status line\r\n")
598
class TestInvalidStatusServer(TestBadStatusServer):
599
"""Tests invalid status from server.
601
Both implementations raises the same error as for a bad status.
604
_req_handler_class = InvalidStatusRequestHandler
606
def test_http_has(self):
607
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
608
raise tests.KnownFailure(
609
'pycurl hangs if the server send back garbage')
610
super(TestInvalidStatusServer, self).test_http_has()
612
def test_http_get(self):
613
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
614
raise tests.KnownFailure(
615
'pycurl hangs if the server send back garbage')
616
super(TestInvalidStatusServer, self).test_http_get()
619
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
620
"""Whatever request comes in, returns a bad protocol version"""
622
def parse_request(self):
623
"""Fakes handling a single HTTP request, returns a bad status"""
624
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
625
# Returns an invalid protocol version, but curl just
626
# ignores it and those cannot be tested.
627
self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
629
'Look at my protocol version'))
633
class TestBadProtocolServer(TestSpecificRequestHandler):
634
"""Tests bad protocol from server."""
636
_req_handler_class = BadProtocolRequestHandler
639
if pycurl_present and self._transport == PyCurlTransport:
640
raise tests.TestNotApplicable(
641
"pycurl doesn't check the protocol version")
642
super(TestBadProtocolServer, self).setUp()
644
def test_http_has(self):
645
server = self.get_readonly_server()
646
t = self._transport(server.get_url())
647
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
649
def test_http_get(self):
650
server = self.get_readonly_server()
651
t = self._transport(server.get_url())
652
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
655
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
656
"""Whatever request comes in, returns a 403 code"""
658
def parse_request(self):
659
"""Handle a single HTTP request, by replying we cannot handle it"""
660
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
665
class TestForbiddenServer(TestSpecificRequestHandler):
666
"""Tests forbidden server"""
668
_req_handler_class = ForbiddenRequestHandler
670
def test_http_has(self):
671
server = self.get_readonly_server()
672
t = self._transport(server.get_url())
673
self.assertRaises(errors.TransportError, t.has, 'foo/bar')
675
def test_http_get(self):
676
server = self.get_readonly_server()
677
t = self._transport(server.get_url())
678
self.assertRaises(errors.TransportError, t.get, 'foo/bar')
681
class TestRecordingServer(tests.TestCase):
683
def test_create(self):
684
server = RecordingServer(expect_body_tail=None)
685
self.assertEqual('', server.received_bytes)
686
self.assertEqual(None, server.host)
687
self.assertEqual(None, server.port)
689
def test_setUp_and_tearDown(self):
690
server = RecordingServer(expect_body_tail=None)
693
self.assertNotEqual(None, server.host)
694
self.assertNotEqual(None, server.port)
697
self.assertEqual(None, server.host)
698
self.assertEqual(None, server.port)
700
def test_send_receive_bytes(self):
701
server = RecordingServer(expect_body_tail='c')
703
self.addCleanup(server.tearDown)
704
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
705
sock.connect((server.host, server.port))
707
self.assertEqual('HTTP/1.1 200 OK\r\n',
708
osutils.recv_all(sock, 4096))
709
self.assertEqual('abc', server.received_bytes)
712
class TestRangeRequestServer(TestSpecificRequestHandler):
713
"""Tests readv requests against server.
715
We test against default "normal" server.
719
super(TestRangeRequestServer, self).setUp()
720
self.build_tree_contents([('a', '0123456789')],)
722
def test_readv(self):
723
server = self.get_readonly_server()
724
t = self._transport(server.get_url())
725
l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
726
self.assertEqual(l[0], (0, '0'))
727
self.assertEqual(l[1], (1, '1'))
728
self.assertEqual(l[2], (3, '34'))
729
self.assertEqual(l[3], (9, '9'))
731
def test_readv_out_of_order(self):
732
server = self.get_readonly_server()
733
t = self._transport(server.get_url())
734
l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
735
self.assertEqual(l[0], (1, '1'))
736
self.assertEqual(l[1], (9, '9'))
737
self.assertEqual(l[2], (0, '0'))
738
self.assertEqual(l[3], (3, '34'))
740
def test_readv_invalid_ranges(self):
741
server = self.get_readonly_server()
742
t = self._transport(server.get_url())
744
# This is intentionally reading off the end of the file
745
# since we are sure that it cannot get there
746
self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
747
t.readv, 'a', [(1,1), (8,10)])
749
# This is trying to seek past the end of the file, it should
750
# also raise a special error
751
self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
752
t.readv, 'a', [(12,2)])
754
def test_readv_multiple_get_requests(self):
755
server = self.get_readonly_server()
756
t = self._transport(server.get_url())
757
# force transport to issue multiple requests
758
t._max_readv_combine = 1
759
t._max_get_ranges = 1
760
l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
761
self.assertEqual(l[0], (0, '0'))
762
self.assertEqual(l[1], (1, '1'))
763
self.assertEqual(l[2], (3, '34'))
764
self.assertEqual(l[3], (9, '9'))
765
# The server should have issued 4 requests
766
self.assertEqual(4, server.GET_request_nb)
768
def test_readv_get_max_size(self):
769
server = self.get_readonly_server()
770
t = self._transport(server.get_url())
771
# force transport to issue multiple requests by limiting the number of
772
# bytes by request. Note that this apply to coalesced offsets only, a
773
# single range will keep its size even if bigger than the limit.
775
l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
776
self.assertEqual(l[0], (0, '0'))
777
self.assertEqual(l[1], (1, '1'))
778
self.assertEqual(l[2], (2, '2345'))
779
self.assertEqual(l[3], (6, '6789'))
780
# The server should have issued 3 requests
781
self.assertEqual(3, server.GET_request_nb)
783
def test_complete_readv_leave_pipe_clean(self):
784
server = self.get_readonly_server()
785
t = self._transport(server.get_url())
786
# force transport to issue multiple requests
788
l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
789
# The server should have issued 3 requests
790
self.assertEqual(3, server.GET_request_nb)
791
self.assertEqual('0123456789', t.get_bytes('a'))
792
self.assertEqual(4, server.GET_request_nb)
794
def test_incomplete_readv_leave_pipe_clean(self):
795
server = self.get_readonly_server()
796
t = self._transport(server.get_url())
797
# force transport to issue multiple requests
799
# Don't collapse readv results into a list so that we leave unread
800
# bytes on the socket
801
ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
802
self.assertEqual((0, '0'), ireadv.next())
803
# The server should have issued one request so far
804
self.assertEqual(1, server.GET_request_nb)
805
self.assertEqual('0123456789', t.get_bytes('a'))
806
# get_bytes issued an additional request, the readv pending ones are
808
self.assertEqual(2, server.GET_request_nb)
811
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
812
"""Always reply to range request as if they were single.
814
Don't be explicit about it, just to annoy the clients.
817
def get_multiple_ranges(self, file, file_size, ranges):
818
"""Answer as if it was a single range request and ignores the rest"""
819
(start, end) = ranges[0]
820
return self.get_single_range(file, file_size, start, end)
823
class TestSingleRangeRequestServer(TestRangeRequestServer):
824
"""Test readv against a server which accept only single range requests"""
826
_req_handler_class = SingleRangeRequestHandler
829
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
830
"""Only reply to simple range requests, errors out on multiple"""
832
def get_multiple_ranges(self, file, file_size, ranges):
833
"""Refuses the multiple ranges request"""
836
self.send_error(416, "Requested range not satisfiable")
838
(start, end) = ranges[0]
839
return self.get_single_range(file, file_size, start, end)
842
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
843
"""Test readv against a server which only accept single range requests"""
845
_req_handler_class = SingleOnlyRangeRequestHandler
848
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
849
"""Ignore range requests without notice"""
852
# Update the statistics
853
self.server.test_case_server.GET_request_nb += 1
854
# Just bypass the range handling done by TestingHTTPRequestHandler
855
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
858
class TestNoRangeRequestServer(TestRangeRequestServer):
859
"""Test readv against a server which do not accept range requests"""
861
_req_handler_class = NoRangeRequestHandler
864
class MultipleRangeWithoutContentLengthRequestHandler(
865
http_server.TestingHTTPRequestHandler):
866
"""Reply to multiple range requests without content length header."""
868
def get_multiple_ranges(self, file, file_size, ranges):
869
self.send_response(206)
870
self.send_header('Accept-Ranges', 'bytes')
871
boundary = "%d" % random.randint(0,0x7FFFFFFF)
872
self.send_header("Content-Type",
873
"multipart/byteranges; boundary=%s" % boundary)
875
for (start, end) in ranges:
876
self.wfile.write("--%s\r\n" % boundary)
877
self.send_header("Content-type", 'application/octet-stream')
878
self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
882
self.send_range_content(file, start, end - start + 1)
884
self.wfile.write("--%s\r\n" % boundary)
887
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
889
_req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
892
class TruncatedMultipleRangeRequestHandler(
893
http_server.TestingHTTPRequestHandler):
894
"""Reply to multiple range requests truncating the last ones.
896
This server generates responses whose Content-Length describes all the
897
ranges, but fail to include the last ones leading to client short reads.
898
This has been observed randomly with lighttpd (bug #179368).
901
_truncated_ranges = 2
903
def get_multiple_ranges(self, file, file_size, ranges):
904
self.send_response(206)
905
self.send_header('Accept-Ranges', 'bytes')
907
self.send_header('Content-Type',
908
'multipart/byteranges; boundary=%s' % boundary)
909
boundary_line = '--%s\r\n' % boundary
910
# Calculate the Content-Length
912
for (start, end) in ranges:
913
content_length += len(boundary_line)
914
content_length += self._header_line_length(
915
'Content-type', 'application/octet-stream')
916
content_length += self._header_line_length(
917
'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
918
content_length += len('\r\n') # end headers
919
content_length += end - start # + 1
920
content_length += len(boundary_line)
921
self.send_header('Content-length', content_length)
924
# Send the multipart body
926
for (start, end) in ranges:
927
self.wfile.write(boundary_line)
928
self.send_header('Content-type', 'application/octet-stream')
929
self.send_header('Content-Range', 'bytes %d-%d/%d'
930
% (start, end, file_size))
932
if cur + self._truncated_ranges >= len(ranges):
933
# Abruptly ends the response and close the connection
934
self.close_connection = 1
936
self.send_range_content(file, start, end - start + 1)
939
self.wfile.write(boundary_line)
942
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
944
_req_handler_class = TruncatedMultipleRangeRequestHandler
947
super(TestTruncatedMultipleRangeServer, self).setUp()
948
self.build_tree_contents([('a', '0123456789')],)
950
def test_readv_with_short_reads(self):
951
server = self.get_readonly_server()
952
t = self._transport(server.get_url())
953
# Force separate ranges for each offset
954
t._bytes_to_read_before_seek = 0
955
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
956
self.assertEqual((0, '0'), ireadv.next())
957
self.assertEqual((2, '2'), ireadv.next())
958
if not self._testing_pycurl():
959
# Only one request have been issued so far (except for pycurl that
960
# try to read the whole response at once)
961
self.assertEqual(1, server.GET_request_nb)
962
self.assertEqual((4, '45'), ireadv.next())
963
self.assertEqual((9, '9'), ireadv.next())
964
# Both implementations issue 3 requests but:
965
# - urllib does two multiple (4 ranges, then 2 ranges) then a single
967
# - pycurl does two multiple (4 ranges, 4 ranges) then a single range
968
self.assertEqual(3, server.GET_request_nb)
969
# Finally the client have tried a single range request and stays in
971
self.assertEqual('single', t._range_hint)
973
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
974
"""Errors out when range specifiers exceed the limit"""
976
def get_multiple_ranges(self, file, file_size, ranges):
977
"""Refuses the multiple ranges request"""
978
tcs = self.server.test_case_server
979
if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
981
# Emulate apache behavior
982
self.send_error(400, "Bad Request")
984
return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
985
self, file, file_size, ranges)
988
class LimitedRangeHTTPServer(http_server.HttpServer):
989
"""An HttpServer erroring out on requests with too much range specifiers"""
991
def __init__(self, request_handler=LimitedRangeRequestHandler,
992
protocol_version=None,
994
http_server.HttpServer.__init__(self, request_handler,
995
protocol_version=protocol_version)
996
self.range_limit = range_limit
999
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1000
"""Tests readv requests against a server erroring out on too much ranges."""
1002
# Requests with more range specifiers will error out
1005
def create_transport_readonly_server(self):
1006
return LimitedRangeHTTPServer(range_limit=self.range_limit,
1007
protocol_version=self._protocol_version)
1009
def get_transport(self):
1010
return self._transport(self.get_readonly_server().get_url())
1013
http_utils.TestCaseWithWebserver.setUp(self)
1014
# We need to manipulate ranges that correspond to real chunks in the
1015
# response, so we build a content appropriately.
1016
filler = ''.join(['abcdefghij' for x in range(102)])
1017
content = ''.join(['%04d' % v + filler for v in range(16)])
1018
self.build_tree_contents([('a', content)],)
1020
def test_few_ranges(self):
1021
t = self.get_transport()
1022
l = list(t.readv('a', ((0, 4), (1024, 4), )))
1023
self.assertEqual(l[0], (0, '0000'))
1024
self.assertEqual(l[1], (1024, '0001'))
1025
self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1027
def test_more_ranges(self):
1028
t = self.get_transport()
1029
l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1030
self.assertEqual(l[0], (0, '0000'))
1031
self.assertEqual(l[1], (1024, '0001'))
1032
self.assertEqual(l[2], (4096, '0004'))
1033
self.assertEqual(l[3], (8192, '0008'))
1034
# The server will refuse to serve the first request (too much ranges),
1035
# a second request will succeed.
1036
self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1039
class TestHttpProxyWhiteBox(tests.TestCase):
1040
"""Whitebox test proxy http authorization.
1042
Only the urllib implementation is tested here.
1046
tests.TestCase.setUp(self)
1051
tests.TestCase.tearDown(self)
1053
def _install_env(self, env):
1054
for name, value in env.iteritems():
1055
self._old_env[name] = osutils.set_or_unset_env(name, value)
1057
def _restore_env(self):
1058
for name, value in self._old_env.iteritems():
1059
osutils.set_or_unset_env(name, value)
1061
def _proxied_request(self):
1062
handler = _urllib2_wrappers.ProxyHandler()
1063
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1064
handler.set_proxy(request, 'http')
1067
def test_empty_user(self):
1068
self._install_env({'http_proxy': 'http://bar.com'})
1069
request = self._proxied_request()
1070
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1072
def test_invalid_proxy(self):
1073
"""A proxy env variable without scheme"""
1074
self._install_env({'http_proxy': 'host:1234'})
1075
self.assertRaises(errors.InvalidURL, self._proxied_request)
1078
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1079
"""Tests proxy server.
1081
Be aware that we do not setup a real proxy here. Instead, we
1082
check that the *connection* goes through the proxy by serving
1083
different content (the faked proxy server append '-proxied'
1087
# FIXME: We don't have an https server available, so we don't
1088
# test https connections.
1091
super(TestProxyHttpServer, self).setUp()
1092
self.build_tree_contents([('foo', 'contents of foo\n'),
1093
('foo-proxied', 'proxied contents of foo\n')])
1094
# Let's setup some attributes for tests
1095
self.server = self.get_readonly_server()
1096
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1097
if self._testing_pycurl():
1098
# Oh my ! pycurl does not check for the port as part of
1099
# no_proxy :-( So we just test the host part
1100
self.no_proxy_host = 'localhost'
1102
self.no_proxy_host = self.proxy_address
1103
# The secondary server is the proxy
1104
self.proxy = self.get_secondary_server()
1105
self.proxy_url = self.proxy.get_url()
1108
def _testing_pycurl(self):
1109
return pycurl_present and self._transport == PyCurlTransport
1111
def create_transport_secondary_server(self):
1112
"""Creates an http server that will serve files with
1113
'-proxied' appended to their names.
1115
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1117
def _install_env(self, env):
1118
for name, value in env.iteritems():
1119
self._old_env[name] = osutils.set_or_unset_env(name, value)
1121
def _restore_env(self):
1122
for name, value in self._old_env.iteritems():
1123
osutils.set_or_unset_env(name, value)
1125
def proxied_in_env(self, env):
1126
self._install_env(env)
1127
url = self.server.get_url()
1128
t = self._transport(url)
1130
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1134
def not_proxied_in_env(self, env):
1135
self._install_env(env)
1136
url = self.server.get_url()
1137
t = self._transport(url)
1139
self.assertEqual('contents of foo\n', t.get('foo').read())
1143
def test_http_proxy(self):
1144
self.proxied_in_env({'http_proxy': self.proxy_url})
1146
def test_HTTP_PROXY(self):
1147
if self._testing_pycurl():
1148
# pycurl does not check HTTP_PROXY for security reasons
1149
# (for use in a CGI context that we do not care
1150
# about. Should we ?)
1151
raise tests.TestNotApplicable(
1152
'pycurl does not check HTTP_PROXY for security reasons')
1153
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1155
def test_all_proxy(self):
1156
self.proxied_in_env({'all_proxy': self.proxy_url})
1158
def test_ALL_PROXY(self):
1159
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1161
def test_http_proxy_with_no_proxy(self):
1162
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1163
'no_proxy': self.no_proxy_host})
1165
def test_HTTP_PROXY_with_NO_PROXY(self):
1166
if self._testing_pycurl():
1167
raise tests.TestNotApplicable(
1168
'pycurl does not check HTTP_PROXY for security reasons')
1169
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1170
'NO_PROXY': self.no_proxy_host})
1172
def test_all_proxy_with_no_proxy(self):
1173
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1174
'no_proxy': self.no_proxy_host})
1176
def test_ALL_PROXY_with_NO_PROXY(self):
1177
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1178
'NO_PROXY': self.no_proxy_host})
1180
def test_http_proxy_without_scheme(self):
1181
if self._testing_pycurl():
1182
# pycurl *ignores* invalid proxy env variables. If that ever change
1183
# in the future, this test will fail indicating that pycurl do not
1184
# ignore anymore such variables.
1185
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1187
self.assertRaises(errors.InvalidURL,
1188
self.proxied_in_env,
1189
{'http_proxy': self.proxy_address})
1192
class TestRanges(http_utils.TestCaseWithWebserver):
1193
"""Test the Range header in GET methods."""
1196
http_utils.TestCaseWithWebserver.setUp(self)
1197
self.build_tree_contents([('a', '0123456789')],)
1198
server = self.get_readonly_server()
1199
self.transport = self._transport(server.get_url())
1201
def create_transport_readonly_server(self):
1202
return http_server.HttpServer(protocol_version=self._protocol_version)
1204
def _file_contents(self, relpath, ranges):
1205
offsets = [ (start, end - start + 1) for start, end in ranges]
1206
coalesce = self.transport._coalesce_offsets
1207
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1208
code, data = self.transport._get(relpath, coalesced)
1209
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1210
for start, end in ranges:
1212
yield data.read(end - start + 1)
1214
def _file_tail(self, relpath, tail_amount):
1215
code, data = self.transport._get(relpath, [], tail_amount)
1216
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1217
data.seek(-tail_amount, 2)
1218
return data.read(tail_amount)
1220
def test_range_header(self):
1222
map(self.assertEqual,['0', '234'],
1223
list(self._file_contents('a', [(0,0), (2,4)])),)
1225
def test_range_header_tail(self):
1226
self.assertEqual('789', self._file_tail('a', 3))
1228
def test_syntactically_invalid_range_header(self):
1229
self.assertListRaises(errors.InvalidHttpRange,
1230
self._file_contents, 'a', [(4, 3)])
1232
def test_semantically_invalid_range_header(self):
1233
self.assertListRaises(errors.InvalidHttpRange,
1234
self._file_contents, 'a', [(42, 128)])
1237
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1238
"""Test redirection between http servers."""
1240
def create_transport_secondary_server(self):
1241
"""Create the secondary server redirecting to the primary server"""
1242
new = self.get_readonly_server()
1244
redirecting = http_utils.HTTPServerRedirecting(
1245
protocol_version=self._protocol_version)
1246
redirecting.redirect_to(new.host, new.port)
1250
super(TestHTTPRedirections, self).setUp()
1251
self.build_tree_contents([('a', '0123456789'),
1253
'# Bazaar revision bundle v0.9\n#\n')
1255
# The requests to the old server will be redirected to the new server
1256
self.old_transport = self._transport(self.old_server.get_url())
1258
def test_redirected(self):
1259
self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1260
t = self._transport(self.new_server.get_url())
1261
self.assertEqual('0123456789', t.get('a').read())
1263
def test_read_redirected_bundle_from_url(self):
1264
from bzrlib.bundle import read_bundle_from_url
1265
url = self.old_transport.abspath('bundle')
1266
bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1267
read_bundle_from_url, url)
1268
# If read_bundle_from_url was successful we get an empty bundle
1269
self.assertEqual([], bundle.revisions)
1272
class RedirectedRequest(_urllib2_wrappers.Request):
1273
"""Request following redirections. """
1275
init_orig = _urllib2_wrappers.Request.__init__
1277
def __init__(self, method, url, *args, **kwargs):
1281
# Since the tests using this class will replace
1282
# _urllib2_wrappers.Request, we can't just call the base class __init__
1284
RedirectedRequest.init_orig(self, method, url, args, kwargs)
1285
self.follow_redirections = True
1288
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1289
"""Test redirections.
1291
http implementations do not redirect silently anymore (they
1292
do not redirect at all in fact). The mechanism is still in
1293
place at the _urllib2_wrappers.Request level and these tests
1296
For the pycurl implementation
1297
the redirection have been deleted as we may deprecate pycurl
1298
and I have no place to keep a working implementation.
1303
if pycurl_present and self._transport == PyCurlTransport:
1304
raise tests.TestNotApplicable(
1305
"pycurl doesn't redirect silently annymore")
1306
super(TestHTTPSilentRedirections, self).setUp()
1307
self.setup_redirected_request()
1308
self.addCleanup(self.cleanup_redirected_request)
1309
self.build_tree_contents([('a','a'),
1311
('1/a', 'redirected once'),
1313
('2/a', 'redirected twice'),
1315
('3/a', 'redirected thrice'),
1317
('4/a', 'redirected 4 times'),
1319
('5/a', 'redirected 5 times'),
1322
self.old_transport = self._transport(self.old_server.get_url())
1324
def setup_redirected_request(self):
1325
self.original_class = _urllib2_wrappers.Request
1326
_urllib2_wrappers.Request = RedirectedRequest
1328
def cleanup_redirected_request(self):
1329
_urllib2_wrappers.Request = self.original_class
1331
def create_transport_secondary_server(self):
1332
"""Create the secondary server, redirections are defined in the tests"""
1333
return http_utils.HTTPServerRedirecting(
1334
protocol_version=self._protocol_version)
1336
def test_one_redirection(self):
1337
t = self.old_transport
1339
req = RedirectedRequest('GET', t.abspath('a'))
1340
req.follow_redirections = True
1341
new_prefix = 'http://%s:%s' % (self.new_server.host,
1342
self.new_server.port)
1343
self.old_server.redirections = \
1344
[('(.*)', r'%s/1\1' % (new_prefix), 301),]
1345
self.assertEquals('redirected once',t._perform(req).read())
1347
def test_five_redirections(self):
1348
t = self.old_transport
1350
req = RedirectedRequest('GET', t.abspath('a'))
1351
req.follow_redirections = True
1352
old_prefix = 'http://%s:%s' % (self.old_server.host,
1353
self.old_server.port)
1354
new_prefix = 'http://%s:%s' % (self.new_server.host,
1355
self.new_server.port)
1356
self.old_server.redirections = [
1357
('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1358
('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1359
('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1360
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1361
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1363
self.assertEquals('redirected 5 times',t._perform(req).read())
1366
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1367
"""Test transport.do_catching_redirections."""
1370
super(TestDoCatchRedirections, self).setUp()
1371
self.build_tree_contents([('a', '0123456789'),],)
1373
self.old_transport = self._transport(self.old_server.get_url())
1375
def get_a(self, transport):
1376
return transport.get('a')
1378
def test_no_redirection(self):
1379
t = self._transport(self.new_server.get_url())
1381
# We use None for redirected so that we fail if redirected
1382
self.assertEquals('0123456789',
1383
transport.do_catching_redirections(
1384
self.get_a, t, None).read())
1386
def test_one_redirection(self):
1387
self.redirections = 0
1389
def redirected(transport, exception, redirection_notice):
1390
self.redirections += 1
1391
dir, file = urlutils.split(exception.target)
1392
return self._transport(dir)
1394
self.assertEquals('0123456789',
1395
transport.do_catching_redirections(
1396
self.get_a, self.old_transport, redirected).read())
1397
self.assertEquals(1, self.redirections)
1399
def test_redirection_loop(self):
1401
def redirected(transport, exception, redirection_notice):
1402
# By using the redirected url as a base dir for the
1403
# *old* transport, we create a loop: a => a/a =>
1405
return self.old_transport.clone(exception.target)
1407
self.assertRaises(errors.TooManyRedirections,
1408
transport.do_catching_redirections,
1409
self.get_a, self.old_transport, redirected)
1412
class TestAuth(http_utils.TestCaseWithWebserver):
1413
"""Test authentication scheme"""
1415
_auth_header = 'Authorization'
1416
_password_prompt_prefix = ''
1419
super(TestAuth, self).setUp()
1420
self.server = self.get_readonly_server()
1421
self.build_tree_contents([('a', 'contents of a\n'),
1422
('b', 'contents of b\n'),])
1424
def create_transport_readonly_server(self):
1425
if self._auth_scheme == 'basic':
1426
server = http_utils.HTTPBasicAuthServer(
1427
protocol_version=self._protocol_version)
1429
if self._auth_scheme != 'digest':
1430
raise AssertionError('Unknown auth scheme: %r'
1431
% self._auth_scheme)
1432
server = http_utils.HTTPDigestAuthServer(
1433
protocol_version=self._protocol_version)
1436
def _testing_pycurl(self):
1437
return pycurl_present and self._transport == PyCurlTransport
1439
def get_user_url(self, user, password):
1440
"""Build an url embedding user and password"""
1441
url = '%s://' % self.server._url_protocol
1442
if user is not None:
1444
if password is not None:
1445
url += ':' + password
1447
url += '%s:%s/' % (self.server.host, self.server.port)
1450
def get_user_transport(self, user, password):
1451
return self._transport(self.get_user_url(user, password))
1453
def test_no_user(self):
1454
self.server.add_user('joe', 'foo')
1455
t = self.get_user_transport(None, None)
1456
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1457
# Only one 'Authentication Required' error should occur
1458
self.assertEqual(1, self.server.auth_required_errors)
1460
def test_empty_pass(self):
1461
self.server.add_user('joe', '')
1462
t = self.get_user_transport('joe', '')
1463
self.assertEqual('contents of a\n', t.get('a').read())
1464
# Only one 'Authentication Required' error should occur
1465
self.assertEqual(1, self.server.auth_required_errors)
1467
def test_user_pass(self):
1468
self.server.add_user('joe', 'foo')
1469
t = self.get_user_transport('joe', 'foo')
1470
self.assertEqual('contents of a\n', t.get('a').read())
1471
# Only one 'Authentication Required' error should occur
1472
self.assertEqual(1, self.server.auth_required_errors)
1474
def test_unknown_user(self):
1475
self.server.add_user('joe', 'foo')
1476
t = self.get_user_transport('bill', 'foo')
1477
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1478
# Two 'Authentication Required' errors should occur (the
1479
# initial 'who are you' and 'I don't know you, who are
1481
self.assertEqual(2, self.server.auth_required_errors)
1483
def test_wrong_pass(self):
1484
self.server.add_user('joe', 'foo')
1485
t = self.get_user_transport('joe', 'bar')
1486
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1487
# Two 'Authentication Required' errors should occur (the
1488
# initial 'who are you' and 'this is not you, who are you')
1489
self.assertEqual(2, self.server.auth_required_errors)
1491
def test_prompt_for_password(self):
1492
if self._testing_pycurl():
1493
raise tests.TestNotApplicable(
1494
'pycurl cannot prompt, it handles auth by embedding'
1495
' user:pass in urls only')
1497
self.server.add_user('joe', 'foo')
1498
t = self.get_user_transport('joe', None)
1499
stdout = tests.StringIOWrapper()
1500
ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
1501
self.assertEqual('contents of a\n',t.get('a').read())
1502
# stdin should be empty
1503
self.assertEqual('', ui.ui_factory.stdin.readline())
1504
self._check_password_prompt(t._unqualified_scheme, 'joe',
1506
# And we shouldn't prompt again for a different request
1507
# against the same transport.
1508
self.assertEqual('contents of b\n',t.get('b').read())
1510
# And neither against a clone
1511
self.assertEqual('contents of b\n',t2.get('b').read())
1512
# Only one 'Authentication Required' error should occur
1513
self.assertEqual(1, self.server.auth_required_errors)
1515
def _check_password_prompt(self, scheme, user, actual_prompt):
1516
expected_prompt = (self._password_prompt_prefix
1517
+ ("%s %s@%s:%d, Realm: '%s' password: "
1519
user, self.server.host, self.server.port,
1520
self.server.auth_realm)))
1521
self.assertEquals(expected_prompt, actual_prompt)
1523
def test_no_prompt_for_password_when_using_auth_config(self):
1524
if self._testing_pycurl():
1525
raise tests.TestNotApplicable(
1526
'pycurl does not support authentication.conf'
1527
' since it cannot prompt')
1531
stdin_content = 'bar\n' # Not the right password
1532
self.server.add_user(user, password)
1533
t = self.get_user_transport(user, None)
1534
ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1535
stdout=tests.StringIOWrapper())
1536
# Create a minimal config file with the right password
1537
conf = config.AuthenticationConfig()
1538
conf._get_config().update(
1539
{'httptest': {'scheme': 'http', 'port': self.server.port,
1540
'user': user, 'password': password}})
1542
# Issue a request to the server to connect
1543
self.assertEqual('contents of a\n',t.get('a').read())
1544
# stdin should have been left untouched
1545
self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1546
# Only one 'Authentication Required' error should occur
1547
self.assertEqual(1, self.server.auth_required_errors)
1549
def test_user_from_auth_conf(self):
1550
if self._testing_pycurl():
1551
raise tests.TestNotApplicable(
1552
'pycurl does not support authentication.conf')
1555
self.server.add_user(user, password)
1556
# Create a minimal config file with the right password
1557
conf = config.AuthenticationConfig()
1558
conf._get_config().update(
1559
{'httptest': {'scheme': 'http', 'port': self.server.port,
1560
'user': user, 'password': password}})
1562
t = self.get_user_transport(None, None)
1563
# Issue a request to the server to connect
1564
self.assertEqual('contents of a\n', t.get('a').read())
1565
# Only one 'Authentication Required' error should occur
1566
self.assertEqual(1, self.server.auth_required_errors)
1568
def test_changing_nonce(self):
1569
if self._auth_scheme != 'digest':
1570
raise tests.TestNotApplicable('HTTP auth digest only test')
1571
if self._testing_pycurl():
1572
raise tests.KnownFailure(
1573
'pycurl does not handle a nonce change')
1574
self.server.add_user('joe', 'foo')
1575
t = self.get_user_transport('joe', 'foo')
1576
self.assertEqual('contents of a\n', t.get('a').read())
1577
self.assertEqual('contents of b\n', t.get('b').read())
1578
# Only one 'Authentication Required' error should have
1580
self.assertEqual(1, self.server.auth_required_errors)
1581
# The server invalidates the current nonce
1582
self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1583
self.assertEqual('contents of a\n', t.get('a').read())
1584
# Two 'Authentication Required' errors should occur (the
1585
# initial 'who are you' and a second 'who are you' with the new nonce)
1586
self.assertEqual(2, self.server.auth_required_errors)
1590
class TestProxyAuth(TestAuth):
1591
"""Test proxy authentication schemes."""
1593
_auth_header = 'Proxy-authorization'
1594
_password_prompt_prefix='Proxy '
1597
super(TestProxyAuth, self).setUp()
1599
self.addCleanup(self._restore_env)
1600
# Override the contents to avoid false positives
1601
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1602
('b', 'not proxied contents of b\n'),
1603
('a-proxied', 'contents of a\n'),
1604
('b-proxied', 'contents of b\n'),
1607
def create_transport_readonly_server(self):
1608
if self._auth_scheme == 'basic':
1609
server = http_utils.ProxyBasicAuthServer(
1610
protocol_version=self._protocol_version)
1612
if self._auth_scheme != 'digest':
1613
raise AssertionError('Unknown auth scheme: %r'
1614
% self._auth_scheme)
1615
server = http_utils.ProxyDigestAuthServer(
1616
protocol_version=self._protocol_version)
1619
def get_user_transport(self, user, password):
1620
self._install_env({'all_proxy': self.get_user_url(user, password)})
1621
return self._transport(self.server.get_url())
1623
def _install_env(self, env):
1624
for name, value in env.iteritems():
1625
self._old_env[name] = osutils.set_or_unset_env(name, value)
1627
def _restore_env(self):
1628
for name, value in self._old_env.iteritems():
1629
osutils.set_or_unset_env(name, value)
1631
def test_empty_pass(self):
1632
if self._testing_pycurl():
1634
if pycurl.version_info()[1] < '7.16.0':
1635
raise tests.KnownFailure(
1636
'pycurl < 7.16.0 does not handle empty proxy passwords')
1637
super(TestProxyAuth, self).test_empty_pass()
1640
class SampleSocket(object):
1641
"""A socket-like object for use in testing the HTTP request handler."""
1643
def __init__(self, socket_read_content):
1644
"""Constructs a sample socket.
1646
:param socket_read_content: a byte sequence
1648
# Use plain python StringIO so we can monkey-patch the close method to
1649
# not discard the contents.
1650
from StringIO import StringIO
1651
self.readfile = StringIO(socket_read_content)
1652
self.writefile = StringIO()
1653
self.writefile.close = lambda: None
1655
def makefile(self, mode='r', bufsize=None):
1657
return self.readfile
1659
return self.writefile
1662
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1665
super(SmartHTTPTunnellingTest, self).setUp()
1666
# We use the VFS layer as part of HTTP tunnelling tests.
1667
self._captureVar('BZR_NO_SMART_VFS', None)
1668
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1670
def create_transport_readonly_server(self):
1671
return http_utils.HTTPServerWithSmarts(
1672
protocol_version=self._protocol_version)
1674
def test_open_bzrdir(self):
1675
branch = self.make_branch('relpath')
1676
http_server = self.get_readonly_server()
1677
url = http_server.get_url() + 'relpath'
1678
bd = bzrdir.BzrDir.open(url)
1679
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1681
def test_bulk_data(self):
1682
# We should be able to send and receive bulk data in a single message.
1683
# The 'readv' command in the smart protocol both sends and receives
1684
# bulk data, so we use that.
1685
self.build_tree(['data-file'])
1686
http_server = self.get_readonly_server()
1687
http_transport = self._transport(http_server.get_url())
1688
medium = http_transport.get_smart_medium()
1689
# Since we provide the medium, the url below will be mostly ignored
1690
# during the test, as long as the path is '/'.
1691
remote_transport = remote.RemoteTransport('bzr://fake_host/',
1694
[(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1696
def test_http_send_smart_request(self):
1698
post_body = 'hello\n'
1699
expected_reply_body = 'ok\x012\n'
1701
http_server = self.get_readonly_server()
1702
http_transport = self._transport(http_server.get_url())
1703
medium = http_transport.get_smart_medium()
1704
response = medium.send_http_smart_request(post_body)
1705
reply_body = response.read()
1706
self.assertEqual(expected_reply_body, reply_body)
1708
def test_smart_http_server_post_request_handler(self):
1709
httpd = self.get_readonly_server()._get_httpd()
1711
socket = SampleSocket(
1712
'POST /.bzr/smart %s \r\n' % self._protocol_version
1713
# HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1715
+ 'Content-Length: 6\r\n'
1718
# Beware: the ('localhost', 80) below is the
1719
# client_address parameter, but we don't have one because
1720
# we have defined a socket which is not bound to an
1721
# address. The test framework never uses this client
1722
# address, so far...
1723
request_handler = http_utils.SmartRequestHandler(socket,
1726
response = socket.writefile.getvalue()
1727
self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1728
# This includes the end of the HTTP headers, and all the body.
1729
expected_end_of_response = '\r\n\r\nok\x012\n'
1730
self.assertEndsWith(response, expected_end_of_response)
1733
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1734
"""No smart server here request handler."""
1737
self.send_error(403, "Forbidden")
1740
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1741
"""Test smart client behaviour against an http server without smarts."""
1743
_req_handler_class = ForbiddenRequestHandler
1745
def test_probe_smart_server(self):
1746
"""Test error handling against server refusing smart requests."""
1747
server = self.get_readonly_server()
1748
t = self._transport(server.get_url())
1749
# No need to build a valid smart request here, the server will not even
1750
# try to interpret it.
1751
self.assertRaises(errors.SmartProtocolError,
1752
t.get_smart_medium().send_http_smart_request,
1755
class Test_redirected_to(tests.TestCase):
1757
def test_redirected_to_subdir(self):
1758
t = self._transport('http://www.example.com/foo')
1759
r = t._redirected_to('http://www.example.com/foo',
1760
'http://www.example.com/foo/subdir')
1761
self.assertIsInstance(r, type(t))
1762
# Both transports share the some connection
1763
self.assertEquals(t._get_connection(), r._get_connection())
1765
def test_redirected_to_self_with_slash(self):
1766
t = self._transport('http://www.example.com/foo')
1767
r = t._redirected_to('http://www.example.com/foo',
1768
'http://www.example.com/foo/')
1769
self.assertIsInstance(r, type(t))
1770
# Both transports share the some connection (one can argue that we
1771
# should return the exact same transport here, but that seems
1773
self.assertEquals(t._get_connection(), r._get_connection())
1775
def test_redirected_to_host(self):
1776
t = self._transport('http://www.example.com/foo')
1777
r = t._redirected_to('http://www.example.com/foo',
1778
'http://foo.example.com/foo/subdir')
1779
self.assertIsInstance(r, type(t))
1781
def test_redirected_to_same_host_sibling_protocol(self):
1782
t = self._transport('http://www.example.com/foo')
1783
r = t._redirected_to('http://www.example.com/foo',
1784
'https://www.example.com/foo')
1785
self.assertIsInstance(r, type(t))
1787
def test_redirected_to_same_host_different_protocol(self):
1788
t = self._transport('http://www.example.com/foo')
1789
r = t._redirected_to('http://www.example.com/foo',
1790
'ftp://www.example.com/foo')
1791
self.assertNotEquals(type(r), type(t))
1793
def test_redirected_to_different_host_same_user(self):
1794
t = self._transport('http://joe@www.example.com/foo')
1795
r = t._redirected_to('http://www.example.com/foo',
1796
'https://foo.example.com/foo')
1797
self.assertIsInstance(r, type(t))
1798
self.assertEquals(t._user, r._user)
1801
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1802
"""Request handler for a unique and pre-defined request.
1804
The only thing we care about here is how many bytes travel on the wire. But
1805
since we want to measure it for a real http client, we have to send it
1808
We expect to receive a *single* request nothing more (and we won't even
1809
check what request it is, we just measure the bytes read until an empty
1813
def handle_one_request(self):
1814
tcs = self.server.test_case_server
1815
requestline = self.rfile.readline()
1816
headers = self.MessageClass(self.rfile, 0)
1817
# We just read: the request, the headers, an empty line indicating the
1818
# end of the headers.
1819
bytes_read = len(requestline)
1820
for line in headers.headers:
1821
bytes_read += len(line)
1822
bytes_read += len('\r\n')
1823
if requestline.startswith('POST'):
1824
# The body should be a single line (or we don't know where it ends
1825
# and we don't want to issue a blocking read)
1826
body = self.rfile.readline()
1827
bytes_read += len(body)
1828
tcs.bytes_read = bytes_read
1830
# We set the bytes written *before* issuing the write, the client is
1831
# supposed to consume every produced byte *before* checking that value.
1833
# Doing the oppposite may lead to test failure: we may be interrupted
1834
# after the write but before updating the value. The client can then
1835
# continue and read the value *before* we can update it. And yes,
1836
# this has been observed -- vila 20090129
1837
tcs.bytes_written = len(tcs.canned_response)
1838
self.wfile.write(tcs.canned_response)
1841
class ActivityServerMixin(object):
1843
def __init__(self, protocol_version):
1844
super(ActivityServerMixin, self).__init__(
1845
request_handler=PredefinedRequestHandler,
1846
protocol_version=protocol_version)
1847
# Bytes read and written by the server
1849
self.bytes_written = 0
1850
self.canned_response = None
1853
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1857
if tests.HTTPSServerFeature.available():
1858
from bzrlib.tests import https_server
1859
class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1863
class TestActivity(tests.TestCase):
1864
"""Test socket activity reporting.
1866
We use a special purpose server to control the bytes sent and received and
1867
be able to predict the activity on the client socket.
1871
tests.TestCase.setUp(self)
1872
self.server = self._activity_server(self._protocol_version)
1874
self.activities = {}
1875
def report_activity(t, bytes, direction):
1876
count = self.activities.get(direction, 0)
1878
self.activities[direction] = count
1880
# We override at class level because constructors may propagate the
1881
# bound method and render instance overriding ineffective (an
1882
# alternative would be be to define a specific ui factory instead...)
1883
self.orig_report_activity = self._transport._report_activity
1884
self._transport._report_activity = report_activity
1887
self._transport._report_activity = self.orig_report_activity
1888
self.server.tearDown()
1889
tests.TestCase.tearDown(self)
1891
def get_transport(self):
1892
return self._transport(self.server.get_url())
1894
def assertActivitiesMatch(self):
1895
self.assertEqual(self.server.bytes_read,
1896
self.activities.get('write', 0), 'written bytes')
1897
self.assertEqual(self.server.bytes_written,
1898
self.activities.get('read', 0), 'read bytes')
1901
self.server.canned_response = '''HTTP/1.1 200 OK\r
1902
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1903
Server: Apache/2.0.54 (Fedora)\r
1904
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1905
ETag: "56691-23-38e9ae00"\r
1906
Accept-Ranges: bytes\r
1907
Content-Length: 35\r
1909
Content-Type: text/plain; charset=UTF-8\r
1911
Bazaar-NG meta directory, format 1
1913
t = self.get_transport()
1914
self.assertEqual('Bazaar-NG meta directory, format 1\n',
1915
t.get('foo/bar').read())
1916
self.assertActivitiesMatch()
1919
self.server.canned_response = '''HTTP/1.1 200 OK\r
1920
Server: SimpleHTTP/0.6 Python/2.5.2\r
1921
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
1922
Content-type: application/octet-stream\r
1923
Content-Length: 20\r
1924
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
1927
t = self.get_transport()
1928
self.assertTrue(t.has('foo/bar'))
1929
self.assertActivitiesMatch()
1931
def test_readv(self):
1932
self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
1933
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
1934
Server: Apache/2.0.54 (Fedora)\r
1935
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
1936
ETag: "238a3c-16ec2-805c5540"\r
1937
Accept-Ranges: bytes\r
1938
Content-Length: 1534\r
1940
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
1943
--418470f848b63279b\r
1944
Content-type: text/plain; charset=UTF-8\r
1945
Content-range: bytes 0-254/93890\r
1947
mbp@sourcefrog.net-20050309040815-13242001617e4a06
1948
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
1949
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
1950
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
1951
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
1953
--418470f848b63279b\r
1954
Content-type: text/plain; charset=UTF-8\r
1955
Content-range: bytes 1000-2049/93890\r
1958
mbp@sourcefrog.net-20050311063625-07858525021f270b
1959
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
1960
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
1961
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
1962
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
1963
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
1964
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
1965
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
1966
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
1967
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
1968
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
1969
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
1970
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
1971
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
1972
mbp@sourcefrog.net-20050313120651-497bd231b19df600
1973
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
1974
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
1975
mbp@sourcefrog.net-20050314025539-637a636692c055cf
1976
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
1977
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
1979
--418470f848b63279b--\r
1981
t = self.get_transport()
1982
# Remember that the request is ignored and that the ranges below
1983
# doesn't have to match the canned response.
1984
l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
1985
self.assertEqual(2, len(l))
1986
self.assertActivitiesMatch()
1988
def test_post(self):
1989
self.server.canned_response = '''HTTP/1.1 200 OK\r
1990
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1991
Server: Apache/2.0.54 (Fedora)\r
1992
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1993
ETag: "56691-23-38e9ae00"\r
1994
Accept-Ranges: bytes\r
1995
Content-Length: 35\r
1997
Content-Type: text/plain; charset=UTF-8\r
1999
lalala whatever as long as itsssss
2001
t = self.get_transport()
2002
# We must send a single line of body bytes, see
2003
# PredefinedRequestHandler.handle_one_request
2004
code, f = t._post('abc def end-of-body\n')
2005
self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2006
self.assertActivitiesMatch()