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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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()
75
# one for each transport implementation
76
t_tests, remaining_tests = tests.split_suite_by_condition(
77
standard_tests, tests.condition_isinstance((
78
TestHttpTransportRegistration,
79
TestHttpTransportUrls,
82
transport_scenarios = [
83
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
84
_server=http_server.HttpServer_urllib,
85
_qualified_prefix='http+urllib',)),
88
transport_scenarios.append(
89
('pycurl', dict(_transport=PyCurlTransport,
90
_server=http_server.HttpServer_PyCurl,
91
_qualified_prefix='http+pycurl',)))
92
tests.multiply_tests(t_tests, transport_scenarios, result)
94
# each implementation tested with each HTTP version
95
tp_tests, remaining_tests = tests.split_suite_by_condition(
96
remaining_tests, tests.condition_isinstance((
97
SmartHTTPTunnellingTest,
98
TestDoCatchRedirections,
100
TestHTTPRedirections,
101
TestHTTPSilentRedirections,
102
TestLimitedRangeRequestServer,
106
TestSpecificRequestHandler,
108
protocol_scenarios = [
109
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
110
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
112
tp_scenarios = tests.multiply_scenarios(transport_scenarios,
114
tests.multiply_tests(tp_tests, tp_scenarios, result)
116
# proxy auth: each auth scheme on all http versions on all implementations.
117
tppa_tests, remaining_tests = tests.split_suite_by_condition(
118
remaining_tests, tests.condition_isinstance((
121
proxy_auth_scheme_scenarios = [
122
('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
123
('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
125
dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
127
tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
128
proxy_auth_scheme_scenarios)
129
tests.multiply_tests(tppa_tests, tppa_scenarios, result)
131
# auth: each auth scheme on all http versions on all implementations.
132
tpa_tests, remaining_tests = tests.split_suite_by_condition(
133
remaining_tests, tests.condition_isinstance((
136
auth_scheme_scenarios = [
137
('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
138
('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
140
dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
142
tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
143
auth_scheme_scenarios)
144
tests.multiply_tests(tpa_tests, tpa_scenarios, result)
146
# activity: activity on all http versions on all implementations
147
tpact_tests, remaining_tests = tests.split_suite_by_condition(
148
remaining_tests, tests.condition_isinstance((
151
activity_scenarios = [
152
('http', dict(_activity_server=ActivityHTTPServer)),
154
if tests.HTTPSServerFeature.available():
155
activity_scenarios.append(
156
('https', dict(_activity_server=ActivityHTTPSServer)))
157
tpact_scenarios = tests.multiply_scenarios(tp_scenarios,
159
tests.multiply_tests(tpact_tests, tpact_scenarios, result)
161
# No parametrization for the remaining tests
162
result.addTests(remaining_tests)
167
class FakeManager(object):
170
self.credentials = []
172
def add_password(self, realm, host, username, password):
173
self.credentials.append([realm, host, username, password])
176
class RecordingServer(object):
177
"""A fake HTTP server.
179
It records the bytes sent to it, and replies with a 200.
182
def __init__(self, expect_body_tail=None):
185
:type expect_body_tail: str
186
:param expect_body_tail: a reply won't be sent until this string is
189
self._expect_body_tail = expect_body_tail
192
self.received_bytes = ''
195
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
196
self._sock.bind(('127.0.0.1', 0))
197
self.host, self.port = self._sock.getsockname()
198
self._ready = threading.Event()
199
self._thread = threading.Thread(target=self._accept_read_and_reply)
200
self._thread.setDaemon(True)
204
def _accept_read_and_reply(self):
207
self._sock.settimeout(5)
209
conn, address = self._sock.accept()
210
# On win32, the accepted connection will be non-blocking to start
211
# with because we're using settimeout.
212
conn.setblocking(True)
213
while not self.received_bytes.endswith(self._expect_body_tail):
214
self.received_bytes += conn.recv(4096)
215
conn.sendall('HTTP/1.1 200 OK\r\n')
216
except socket.timeout:
217
# Make sure the client isn't stuck waiting for us to e.g. accept.
220
# The client may have already closed the socket.
227
# We might have already closed it. We don't care.
233
class TestAuthHeader(tests.TestCase):
235
def parse_header(self, header, auth_handler_class=None):
236
if auth_handler_class is None:
237
auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
238
self.auth_handler = auth_handler_class()
239
return self.auth_handler._parse_auth_header(header)
241
def test_empty_header(self):
242
scheme, remainder = self.parse_header('')
243
self.assertEquals('', scheme)
244
self.assertIs(None, remainder)
246
def test_negotiate_header(self):
247
scheme, remainder = self.parse_header('Negotiate')
248
self.assertEquals('negotiate', scheme)
249
self.assertIs(None, remainder)
251
def test_basic_header(self):
252
scheme, remainder = self.parse_header(
253
'Basic realm="Thou should not pass"')
254
self.assertEquals('basic', scheme)
255
self.assertEquals('realm="Thou should not pass"', remainder)
257
def test_basic_extract_realm(self):
258
scheme, remainder = self.parse_header(
259
'Basic realm="Thou should not pass"',
260
_urllib2_wrappers.BasicAuthHandler)
261
match, realm = self.auth_handler.extract_realm(remainder)
262
self.assertTrue(match is not None)
263
self.assertEquals('Thou should not pass', realm)
265
def test_digest_header(self):
266
scheme, remainder = self.parse_header(
267
'Digest realm="Thou should not pass"')
268
self.assertEquals('digest', scheme)
269
self.assertEquals('realm="Thou should not pass"', remainder)
272
class TestHTTPServer(tests.TestCase):
273
"""Test the HTTP servers implementations."""
275
def test_invalid_protocol(self):
276
class BogusRequestHandler(http_server.TestingHTTPRequestHandler):
278
protocol_version = 'HTTP/0.1'
280
server = http_server.HttpServer(BogusRequestHandler)
282
self.assertRaises(httplib.UnknownProtocol,server.setUp)
285
self.fail('HTTP Server creation did not raise UnknownProtocol')
287
def test_force_invalid_protocol(self):
288
server = http_server.HttpServer(protocol_version='HTTP/0.1')
290
self.assertRaises(httplib.UnknownProtocol,server.setUp)
293
self.fail('HTTP Server creation did not raise UnknownProtocol')
295
def test_server_start_and_stop(self):
296
server = http_server.HttpServer()
298
self.assertTrue(server._http_running)
300
self.assertFalse(server._http_running)
302
def test_create_http_server_one_zero(self):
303
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
305
protocol_version = 'HTTP/1.0'
307
server = http_server.HttpServer(RequestHandlerOneZero)
309
self.addCleanup(server.tearDown)
310
self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
312
def test_create_http_server_one_one(self):
313
class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
315
protocol_version = 'HTTP/1.1'
317
server = http_server.HttpServer(RequestHandlerOneOne)
319
self.addCleanup(server.tearDown)
320
self.assertIsInstance(server._httpd,
321
http_server.TestingThreadingHTTPServer)
323
def test_create_http_server_force_one_one(self):
324
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
326
protocol_version = 'HTTP/1.0'
328
server = http_server.HttpServer(RequestHandlerOneZero,
329
protocol_version='HTTP/1.1')
331
self.addCleanup(server.tearDown)
332
self.assertIsInstance(server._httpd,
333
http_server.TestingThreadingHTTPServer)
335
def test_create_http_server_force_one_zero(self):
336
class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
338
protocol_version = 'HTTP/1.1'
340
server = http_server.HttpServer(RequestHandlerOneOne,
341
protocol_version='HTTP/1.0')
343
self.addCleanup(server.tearDown)
344
self.assertIsInstance(server._httpd,
345
http_server.TestingHTTPServer)
348
class TestWithTransport_pycurl(object):
349
"""Test case to inherit from if pycurl is present"""
351
def _get_pycurl_maybe(self):
353
from bzrlib.transport.http._pycurl import PyCurlTransport
354
return PyCurlTransport
355
except errors.DependencyNotPresent:
356
raise tests.TestSkipped('pycurl not present')
358
_transport = property(_get_pycurl_maybe)
361
class TestHttpUrls(tests.TestCase):
363
# TODO: This should be moved to authorization tests once they
366
def test_url_parsing(self):
368
url = http.extract_auth('http://example.com', f)
369
self.assertEquals('http://example.com', url)
370
self.assertEquals(0, len(f.credentials))
371
url = http.extract_auth(
372
'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
373
self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
374
self.assertEquals(1, len(f.credentials))
375
self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
379
class TestHttpTransportUrls(tests.TestCase):
380
"""Test the http urls."""
382
def test_abs_url(self):
383
"""Construction of absolute http URLs"""
384
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
385
eq = self.assertEqualDiff
386
eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
387
eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
388
eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
389
eq(t.abspath('.bzr/1//2/./3'),
390
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
392
def test_invalid_http_urls(self):
393
"""Trap invalid construction of urls"""
394
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
395
self.assertRaises(errors.InvalidURL,
397
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
399
def test_http_root_urls(self):
400
"""Construction of URLs from server root"""
401
t = self._transport('http://bzr.ozlabs.org/')
402
eq = self.assertEqualDiff
403
eq(t.abspath('.bzr/tree-version'),
404
'http://bzr.ozlabs.org/.bzr/tree-version')
406
def test_http_impl_urls(self):
407
"""There are servers which ask for particular clients to connect"""
408
server = self._server()
411
url = server.get_url()
412
self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
417
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
419
# TODO: This should really be moved into another pycurl
420
# specific test. When https tests will be implemented, take
421
# this one into account.
422
def test_pycurl_without_https_support(self):
423
"""Test that pycurl without SSL do not fail with a traceback.
425
For the purpose of the test, we force pycurl to ignore
426
https by supplying a fake version_info that do not
432
raise tests.TestSkipped('pycurl not present')
434
version_info_orig = pycurl.version_info
436
# Now that we have pycurl imported, we can fake its version_info
437
# This was taken from a windows pycurl without SSL
439
pycurl.version_info = lambda : (2,
447
('ftp', 'gopher', 'telnet',
448
'dict', 'ldap', 'http', 'file'),
452
self.assertRaises(errors.DependencyNotPresent, self._transport,
453
'https://launchpad.net')
455
# Restore the right function
456
pycurl.version_info = version_info_orig
459
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
460
"""Test the http connections."""
463
http_utils.TestCaseWithWebserver.setUp(self)
464
self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
465
transport=self.get_transport())
467
def test_http_has(self):
468
server = self.get_readonly_server()
469
t = self._transport(server.get_url())
470
self.assertEqual(t.has('foo/bar'), True)
471
self.assertEqual(len(server.logs), 1)
472
self.assertContainsRe(server.logs[0],
473
r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
475
def test_http_has_not_found(self):
476
server = self.get_readonly_server()
477
t = self._transport(server.get_url())
478
self.assertEqual(t.has('not-found'), False)
479
self.assertContainsRe(server.logs[1],
480
r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
482
def test_http_get(self):
483
server = self.get_readonly_server()
484
t = self._transport(server.get_url())
485
fp = t.get('foo/bar')
486
self.assertEqualDiff(
488
'contents of foo/bar\n')
489
self.assertEqual(len(server.logs), 1)
490
self.assertTrue(server.logs[0].find(
491
'"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
492
% bzrlib.__version__) > -1)
494
def test_has_on_bogus_host(self):
495
# Get a free address and don't 'accept' on it, so that we
496
# can be sure there is no http handler there, but set a
497
# reasonable timeout to not slow down tests too much.
498
default_timeout = socket.getdefaulttimeout()
500
socket.setdefaulttimeout(2)
502
s.bind(('localhost', 0))
503
t = self._transport('http://%s:%s/' % s.getsockname())
504
self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
506
socket.setdefaulttimeout(default_timeout)
509
class TestHttpTransportRegistration(tests.TestCase):
510
"""Test registrations of various http implementations"""
512
def test_http_registered(self):
513
t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
514
self.assertIsInstance(t, transport.Transport)
515
self.assertIsInstance(t, self._transport)
518
class TestPost(tests.TestCase):
520
def test_post_body_is_received(self):
521
server = RecordingServer(expect_body_tail='end-of-body')
523
self.addCleanup(server.tearDown)
524
scheme = self._qualified_prefix
525
url = '%s://%s:%s/' % (scheme, server.host, server.port)
526
http_transport = self._transport(url)
527
code, response = http_transport._post('abc def end-of-body')
529
server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
530
self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
531
# The transport should not be assuming that the server can accept
532
# chunked encoding the first time it connects, because HTTP/1.1, so we
533
# check for the literal string.
535
server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
538
class TestRangeHeader(tests.TestCase):
539
"""Test range_header method"""
541
def check_header(self, value, ranges=[], tail=0):
542
offsets = [ (start, end - start + 1) for start, end in ranges]
543
coalesce = transport.Transport._coalesce_offsets
544
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
545
range_header = http.HttpTransportBase._range_header
546
self.assertEqual(value, range_header(coalesced, tail))
548
def test_range_header_single(self):
549
self.check_header('0-9', ranges=[(0,9)])
550
self.check_header('100-109', ranges=[(100,109)])
552
def test_range_header_tail(self):
553
self.check_header('-10', tail=10)
554
self.check_header('-50', tail=50)
556
def test_range_header_multi(self):
557
self.check_header('0-9,100-200,300-5000',
558
ranges=[(0,9), (100, 200), (300,5000)])
560
def test_range_header_mixed(self):
561
self.check_header('0-9,300-5000,-50',
562
ranges=[(0,9), (300,5000)],
566
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
567
"""Tests a specific request handler.
569
Daughter classes are expected to override _req_handler_class
572
# Provide a useful default
573
_req_handler_class = http_server.TestingHTTPRequestHandler
575
def create_transport_readonly_server(self):
576
return http_server.HttpServer(self._req_handler_class,
577
protocol_version=self._protocol_version)
579
def _testing_pycurl(self):
580
return pycurl_present and self._transport == PyCurlTransport
583
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
584
"""Whatever request comes in, close the connection"""
586
def handle_one_request(self):
587
"""Handle a single HTTP request, by abruptly closing the connection"""
588
self.close_connection = 1
591
class TestWallServer(TestSpecificRequestHandler):
592
"""Tests exceptions during the connection phase"""
594
_req_handler_class = WallRequestHandler
596
def test_http_has(self):
597
server = self.get_readonly_server()
598
t = self._transport(server.get_url())
599
# Unfortunately httplib (see HTTPResponse._read_status
600
# for details) make no distinction between a closed
601
# socket and badly formatted status line, so we can't
602
# just test for ConnectionError, we have to test
603
# InvalidHttpResponse too.
604
self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
607
def test_http_get(self):
608
server = self.get_readonly_server()
609
t = self._transport(server.get_url())
610
self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
614
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
615
"""Whatever request comes in, returns a bad status"""
617
def parse_request(self):
618
"""Fakes handling a single HTTP request, returns a bad status"""
619
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
620
self.send_response(0, "Bad status")
621
self.close_connection = 1
625
class TestBadStatusServer(TestSpecificRequestHandler):
626
"""Tests bad status from server."""
628
_req_handler_class = BadStatusRequestHandler
630
def test_http_has(self):
631
server = self.get_readonly_server()
632
t = self._transport(server.get_url())
633
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
635
def test_http_get(self):
636
server = self.get_readonly_server()
637
t = self._transport(server.get_url())
638
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
641
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
642
"""Whatever request comes in, returns an invalid status"""
644
def parse_request(self):
645
"""Fakes handling a single HTTP request, returns a bad status"""
646
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
647
self.wfile.write("Invalid status line\r\n")
651
class TestInvalidStatusServer(TestBadStatusServer):
652
"""Tests invalid status from server.
654
Both implementations raises the same error as for a bad status.
657
_req_handler_class = InvalidStatusRequestHandler
659
def test_http_has(self):
660
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
661
raise tests.KnownFailure(
662
'pycurl hangs if the server send back garbage')
663
super(TestInvalidStatusServer, self).test_http_has()
665
def test_http_get(self):
666
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
667
raise tests.KnownFailure(
668
'pycurl hangs if the server send back garbage')
669
super(TestInvalidStatusServer, self).test_http_get()
672
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
673
"""Whatever request comes in, returns a bad protocol version"""
675
def parse_request(self):
676
"""Fakes handling a single HTTP request, returns a bad status"""
677
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
678
# Returns an invalid protocol version, but curl just
679
# ignores it and those cannot be tested.
680
self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
682
'Look at my protocol version'))
686
class TestBadProtocolServer(TestSpecificRequestHandler):
687
"""Tests bad protocol from server."""
689
_req_handler_class = BadProtocolRequestHandler
692
if pycurl_present and self._transport == PyCurlTransport:
693
raise tests.TestNotApplicable(
694
"pycurl doesn't check the protocol version")
695
super(TestBadProtocolServer, self).setUp()
697
def test_http_has(self):
698
server = self.get_readonly_server()
699
t = self._transport(server.get_url())
700
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
702
def test_http_get(self):
703
server = self.get_readonly_server()
704
t = self._transport(server.get_url())
705
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
708
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
709
"""Whatever request comes in, returns a 403 code"""
711
def parse_request(self):
712
"""Handle a single HTTP request, by replying we cannot handle it"""
713
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
718
class TestForbiddenServer(TestSpecificRequestHandler):
719
"""Tests forbidden server"""
721
_req_handler_class = ForbiddenRequestHandler
723
def test_http_has(self):
724
server = self.get_readonly_server()
725
t = self._transport(server.get_url())
726
self.assertRaises(errors.TransportError, t.has, 'foo/bar')
728
def test_http_get(self):
729
server = self.get_readonly_server()
730
t = self._transport(server.get_url())
731
self.assertRaises(errors.TransportError, t.get, 'foo/bar')
734
class TestRecordingServer(tests.TestCase):
736
def test_create(self):
737
server = RecordingServer(expect_body_tail=None)
738
self.assertEqual('', server.received_bytes)
739
self.assertEqual(None, server.host)
740
self.assertEqual(None, server.port)
742
def test_setUp_and_tearDown(self):
743
server = RecordingServer(expect_body_tail=None)
746
self.assertNotEqual(None, server.host)
747
self.assertNotEqual(None, server.port)
750
self.assertEqual(None, server.host)
751
self.assertEqual(None, server.port)
753
def test_send_receive_bytes(self):
754
server = RecordingServer(expect_body_tail='c')
756
self.addCleanup(server.tearDown)
757
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
758
sock.connect((server.host, server.port))
760
self.assertEqual('HTTP/1.1 200 OK\r\n',
761
osutils.recv_all(sock, 4096))
762
self.assertEqual('abc', server.received_bytes)
765
class TestRangeRequestServer(TestSpecificRequestHandler):
766
"""Tests readv requests against server.
768
We test against default "normal" server.
772
super(TestRangeRequestServer, self).setUp()
773
self.build_tree_contents([('a', '0123456789')],)
775
def test_readv(self):
776
server = self.get_readonly_server()
777
t = self._transport(server.get_url())
778
l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
779
self.assertEqual(l[0], (0, '0'))
780
self.assertEqual(l[1], (1, '1'))
781
self.assertEqual(l[2], (3, '34'))
782
self.assertEqual(l[3], (9, '9'))
784
def test_readv_out_of_order(self):
785
server = self.get_readonly_server()
786
t = self._transport(server.get_url())
787
l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
788
self.assertEqual(l[0], (1, '1'))
789
self.assertEqual(l[1], (9, '9'))
790
self.assertEqual(l[2], (0, '0'))
791
self.assertEqual(l[3], (3, '34'))
793
def test_readv_invalid_ranges(self):
794
server = self.get_readonly_server()
795
t = self._transport(server.get_url())
797
# This is intentionally reading off the end of the file
798
# since we are sure that it cannot get there
799
self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
800
t.readv, 'a', [(1,1), (8,10)])
802
# This is trying to seek past the end of the file, it should
803
# also raise a special error
804
self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
805
t.readv, 'a', [(12,2)])
807
def test_readv_multiple_get_requests(self):
808
server = self.get_readonly_server()
809
t = self._transport(server.get_url())
810
# force transport to issue multiple requests
811
t._max_readv_combine = 1
812
t._max_get_ranges = 1
813
l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
814
self.assertEqual(l[0], (0, '0'))
815
self.assertEqual(l[1], (1, '1'))
816
self.assertEqual(l[2], (3, '34'))
817
self.assertEqual(l[3], (9, '9'))
818
# The server should have issued 4 requests
819
self.assertEqual(4, server.GET_request_nb)
821
def test_readv_get_max_size(self):
822
server = self.get_readonly_server()
823
t = self._transport(server.get_url())
824
# force transport to issue multiple requests by limiting the number of
825
# bytes by request. Note that this apply to coalesced offsets only, a
826
# single range will keep its size even if bigger than the limit.
828
l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
829
self.assertEqual(l[0], (0, '0'))
830
self.assertEqual(l[1], (1, '1'))
831
self.assertEqual(l[2], (2, '2345'))
832
self.assertEqual(l[3], (6, '6789'))
833
# The server should have issued 3 requests
834
self.assertEqual(3, server.GET_request_nb)
836
def test_complete_readv_leave_pipe_clean(self):
837
server = self.get_readonly_server()
838
t = self._transport(server.get_url())
839
# force transport to issue multiple requests
841
l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
842
# The server should have issued 3 requests
843
self.assertEqual(3, server.GET_request_nb)
844
self.assertEqual('0123456789', t.get_bytes('a'))
845
self.assertEqual(4, server.GET_request_nb)
847
def test_incomplete_readv_leave_pipe_clean(self):
848
server = self.get_readonly_server()
849
t = self._transport(server.get_url())
850
# force transport to issue multiple requests
852
# Don't collapse readv results into a list so that we leave unread
853
# bytes on the socket
854
ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
855
self.assertEqual((0, '0'), ireadv.next())
856
# The server should have issued one request so far
857
self.assertEqual(1, server.GET_request_nb)
858
self.assertEqual('0123456789', t.get_bytes('a'))
859
# get_bytes issued an additional request, the readv pending ones are
861
self.assertEqual(2, server.GET_request_nb)
864
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
865
"""Always reply to range request as if they were single.
867
Don't be explicit about it, just to annoy the clients.
870
def get_multiple_ranges(self, file, file_size, ranges):
871
"""Answer as if it was a single range request and ignores the rest"""
872
(start, end) = ranges[0]
873
return self.get_single_range(file, file_size, start, end)
876
class TestSingleRangeRequestServer(TestRangeRequestServer):
877
"""Test readv against a server which accept only single range requests"""
879
_req_handler_class = SingleRangeRequestHandler
882
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
883
"""Only reply to simple range requests, errors out on multiple"""
885
def get_multiple_ranges(self, file, file_size, ranges):
886
"""Refuses the multiple ranges request"""
889
self.send_error(416, "Requested range not satisfiable")
891
(start, end) = ranges[0]
892
return self.get_single_range(file, file_size, start, end)
895
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
896
"""Test readv against a server which only accept single range requests"""
898
_req_handler_class = SingleOnlyRangeRequestHandler
901
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
902
"""Ignore range requests without notice"""
905
# Update the statistics
906
self.server.test_case_server.GET_request_nb += 1
907
# Just bypass the range handling done by TestingHTTPRequestHandler
908
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
911
class TestNoRangeRequestServer(TestRangeRequestServer):
912
"""Test readv against a server which do not accept range requests"""
914
_req_handler_class = NoRangeRequestHandler
917
class MultipleRangeWithoutContentLengthRequestHandler(
918
http_server.TestingHTTPRequestHandler):
919
"""Reply to multiple range requests without content length header."""
921
def get_multiple_ranges(self, file, file_size, ranges):
922
self.send_response(206)
923
self.send_header('Accept-Ranges', 'bytes')
924
boundary = "%d" % random.randint(0,0x7FFFFFFF)
925
self.send_header("Content-Type",
926
"multipart/byteranges; boundary=%s" % boundary)
928
for (start, end) in ranges:
929
self.wfile.write("--%s\r\n" % boundary)
930
self.send_header("Content-type", 'application/octet-stream')
931
self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
935
self.send_range_content(file, start, end - start + 1)
937
self.wfile.write("--%s\r\n" % boundary)
940
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
942
_req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
945
class TruncatedMultipleRangeRequestHandler(
946
http_server.TestingHTTPRequestHandler):
947
"""Reply to multiple range requests truncating the last ones.
949
This server generates responses whose Content-Length describes all the
950
ranges, but fail to include the last ones leading to client short reads.
951
This has been observed randomly with lighttpd (bug #179368).
954
_truncated_ranges = 2
956
def get_multiple_ranges(self, file, file_size, ranges):
957
self.send_response(206)
958
self.send_header('Accept-Ranges', 'bytes')
960
self.send_header('Content-Type',
961
'multipart/byteranges; boundary=%s' % boundary)
962
boundary_line = '--%s\r\n' % boundary
963
# Calculate the Content-Length
965
for (start, end) in ranges:
966
content_length += len(boundary_line)
967
content_length += self._header_line_length(
968
'Content-type', 'application/octet-stream')
969
content_length += self._header_line_length(
970
'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
971
content_length += len('\r\n') # end headers
972
content_length += end - start # + 1
973
content_length += len(boundary_line)
974
self.send_header('Content-length', content_length)
977
# Send the multipart body
979
for (start, end) in ranges:
980
self.wfile.write(boundary_line)
981
self.send_header('Content-type', 'application/octet-stream')
982
self.send_header('Content-Range', 'bytes %d-%d/%d'
983
% (start, end, file_size))
985
if cur + self._truncated_ranges >= len(ranges):
986
# Abruptly ends the response and close the connection
987
self.close_connection = 1
989
self.send_range_content(file, start, end - start + 1)
992
self.wfile.write(boundary_line)
995
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
997
_req_handler_class = TruncatedMultipleRangeRequestHandler
1000
super(TestTruncatedMultipleRangeServer, self).setUp()
1001
self.build_tree_contents([('a', '0123456789')],)
1003
def test_readv_with_short_reads(self):
1004
server = self.get_readonly_server()
1005
t = self._transport(server.get_url())
1006
# Force separate ranges for each offset
1007
t._bytes_to_read_before_seek = 0
1008
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1009
self.assertEqual((0, '0'), ireadv.next())
1010
self.assertEqual((2, '2'), ireadv.next())
1011
if not self._testing_pycurl():
1012
# Only one request have been issued so far (except for pycurl that
1013
# try to read the whole response at once)
1014
self.assertEqual(1, server.GET_request_nb)
1015
self.assertEqual((4, '45'), ireadv.next())
1016
self.assertEqual((9, '9'), ireadv.next())
1017
# Both implementations issue 3 requests but:
1018
# - urllib does two multiple (4 ranges, then 2 ranges) then a single
1020
# - pycurl does two multiple (4 ranges, 4 ranges) then a single range
1021
self.assertEqual(3, server.GET_request_nb)
1022
# Finally the client have tried a single range request and stays in
1024
self.assertEqual('single', t._range_hint)
1026
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1027
"""Errors out when range specifiers exceed the limit"""
1029
def get_multiple_ranges(self, file, file_size, ranges):
1030
"""Refuses the multiple ranges request"""
1031
tcs = self.server.test_case_server
1032
if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1034
# Emulate apache behavior
1035
self.send_error(400, "Bad Request")
1037
return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1038
self, file, file_size, ranges)
1041
class LimitedRangeHTTPServer(http_server.HttpServer):
1042
"""An HttpServer erroring out on requests with too much range specifiers"""
1044
def __init__(self, request_handler=LimitedRangeRequestHandler,
1045
protocol_version=None,
1047
http_server.HttpServer.__init__(self, request_handler,
1048
protocol_version=protocol_version)
1049
self.range_limit = range_limit
1052
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1053
"""Tests readv requests against a server erroring out on too much ranges."""
1055
# Requests with more range specifiers will error out
1058
def create_transport_readonly_server(self):
1059
return LimitedRangeHTTPServer(range_limit=self.range_limit,
1060
protocol_version=self._protocol_version)
1062
def get_transport(self):
1063
return self._transport(self.get_readonly_server().get_url())
1066
http_utils.TestCaseWithWebserver.setUp(self)
1067
# We need to manipulate ranges that correspond to real chunks in the
1068
# response, so we build a content appropriately.
1069
filler = ''.join(['abcdefghij' for x in range(102)])
1070
content = ''.join(['%04d' % v + filler for v in range(16)])
1071
self.build_tree_contents([('a', content)],)
1073
def test_few_ranges(self):
1074
t = self.get_transport()
1075
l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
self.assertEqual(l[0], (0, '0000'))
1077
self.assertEqual(l[1], (1024, '0001'))
1078
self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1080
def test_more_ranges(self):
1081
t = self.get_transport()
1082
l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
self.assertEqual(l[0], (0, '0000'))
1084
self.assertEqual(l[1], (1024, '0001'))
1085
self.assertEqual(l[2], (4096, '0004'))
1086
self.assertEqual(l[3], (8192, '0008'))
1087
# The server will refuse to serve the first request (too much ranges),
1088
# a second request will succeed.
1089
self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1092
class TestHttpProxyWhiteBox(tests.TestCase):
1093
"""Whitebox test proxy http authorization.
1095
Only the urllib implementation is tested here.
1099
tests.TestCase.setUp(self)
1104
tests.TestCase.tearDown(self)
1106
def _install_env(self, env):
1107
for name, value in env.iteritems():
1108
self._old_env[name] = osutils.set_or_unset_env(name, value)
1110
def _restore_env(self):
1111
for name, value in self._old_env.iteritems():
1112
osutils.set_or_unset_env(name, value)
1114
def _proxied_request(self):
1115
handler = _urllib2_wrappers.ProxyHandler()
1116
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1117
handler.set_proxy(request, 'http')
1120
def test_empty_user(self):
1121
self._install_env({'http_proxy': 'http://bar.com'})
1122
request = self._proxied_request()
1123
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1125
def test_invalid_proxy(self):
1126
"""A proxy env variable without scheme"""
1127
self._install_env({'http_proxy': 'host:1234'})
1128
self.assertRaises(errors.InvalidURL, self._proxied_request)
1131
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1132
"""Tests proxy server.
1134
Be aware that we do not setup a real proxy here. Instead, we
1135
check that the *connection* goes through the proxy by serving
1136
different content (the faked proxy server append '-proxied'
1140
# FIXME: We don't have an https server available, so we don't
1141
# test https connections.
1144
super(TestProxyHttpServer, self).setUp()
1145
self.build_tree_contents([('foo', 'contents of foo\n'),
1146
('foo-proxied', 'proxied contents of foo\n')])
1147
# Let's setup some attributes for tests
1148
self.server = self.get_readonly_server()
1149
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1150
if self._testing_pycurl():
1151
# Oh my ! pycurl does not check for the port as part of
1152
# no_proxy :-( So we just test the host part
1153
self.no_proxy_host = 'localhost'
1155
self.no_proxy_host = self.proxy_address
1156
# The secondary server is the proxy
1157
self.proxy = self.get_secondary_server()
1158
self.proxy_url = self.proxy.get_url()
1161
def _testing_pycurl(self):
1162
return pycurl_present and self._transport == PyCurlTransport
1164
def create_transport_secondary_server(self):
1165
"""Creates an http server that will serve files with
1166
'-proxied' appended to their names.
1168
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1170
def _install_env(self, env):
1171
for name, value in env.iteritems():
1172
self._old_env[name] = osutils.set_or_unset_env(name, value)
1174
def _restore_env(self):
1175
for name, value in self._old_env.iteritems():
1176
osutils.set_or_unset_env(name, value)
1178
def proxied_in_env(self, env):
1179
self._install_env(env)
1180
url = self.server.get_url()
1181
t = self._transport(url)
1183
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1187
def not_proxied_in_env(self, env):
1188
self._install_env(env)
1189
url = self.server.get_url()
1190
t = self._transport(url)
1192
self.assertEqual('contents of foo\n', t.get('foo').read())
1196
def test_http_proxy(self):
1197
self.proxied_in_env({'http_proxy': self.proxy_url})
1199
def test_HTTP_PROXY(self):
1200
if self._testing_pycurl():
1201
# pycurl does not check HTTP_PROXY for security reasons
1202
# (for use in a CGI context that we do not care
1203
# about. Should we ?)
1204
raise tests.TestNotApplicable(
1205
'pycurl does not check HTTP_PROXY for security reasons')
1206
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1208
def test_all_proxy(self):
1209
self.proxied_in_env({'all_proxy': self.proxy_url})
1211
def test_ALL_PROXY(self):
1212
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1214
def test_http_proxy_with_no_proxy(self):
1215
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1216
'no_proxy': self.no_proxy_host})
1218
def test_HTTP_PROXY_with_NO_PROXY(self):
1219
if self._testing_pycurl():
1220
raise tests.TestNotApplicable(
1221
'pycurl does not check HTTP_PROXY for security reasons')
1222
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1223
'NO_PROXY': self.no_proxy_host})
1225
def test_all_proxy_with_no_proxy(self):
1226
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1227
'no_proxy': self.no_proxy_host})
1229
def test_ALL_PROXY_with_NO_PROXY(self):
1230
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1231
'NO_PROXY': self.no_proxy_host})
1233
def test_http_proxy_without_scheme(self):
1234
if self._testing_pycurl():
1235
# pycurl *ignores* invalid proxy env variables. If that ever change
1236
# in the future, this test will fail indicating that pycurl do not
1237
# ignore anymore such variables.
1238
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1240
self.assertRaises(errors.InvalidURL,
1241
self.proxied_in_env,
1242
{'http_proxy': self.proxy_address})
1245
class TestRanges(http_utils.TestCaseWithWebserver):
1246
"""Test the Range header in GET methods."""
1249
http_utils.TestCaseWithWebserver.setUp(self)
1250
self.build_tree_contents([('a', '0123456789')],)
1251
server = self.get_readonly_server()
1252
self.transport = self._transport(server.get_url())
1254
def create_transport_readonly_server(self):
1255
return http_server.HttpServer(protocol_version=self._protocol_version)
1257
def _file_contents(self, relpath, ranges):
1258
offsets = [ (start, end - start + 1) for start, end in ranges]
1259
coalesce = self.transport._coalesce_offsets
1260
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1261
code, data = self.transport._get(relpath, coalesced)
1262
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1263
for start, end in ranges:
1265
yield data.read(end - start + 1)
1267
def _file_tail(self, relpath, tail_amount):
1268
code, data = self.transport._get(relpath, [], tail_amount)
1269
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1270
data.seek(-tail_amount, 2)
1271
return data.read(tail_amount)
1273
def test_range_header(self):
1275
map(self.assertEqual,['0', '234'],
1276
list(self._file_contents('a', [(0,0), (2,4)])),)
1278
def test_range_header_tail(self):
1279
self.assertEqual('789', self._file_tail('a', 3))
1281
def test_syntactically_invalid_range_header(self):
1282
self.assertListRaises(errors.InvalidHttpRange,
1283
self._file_contents, 'a', [(4, 3)])
1285
def test_semantically_invalid_range_header(self):
1286
self.assertListRaises(errors.InvalidHttpRange,
1287
self._file_contents, 'a', [(42, 128)])
1290
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1291
"""Test redirection between http servers."""
1293
def create_transport_secondary_server(self):
1294
"""Create the secondary server redirecting to the primary server"""
1295
new = self.get_readonly_server()
1297
redirecting = http_utils.HTTPServerRedirecting(
1298
protocol_version=self._protocol_version)
1299
redirecting.redirect_to(new.host, new.port)
1303
super(TestHTTPRedirections, self).setUp()
1304
self.build_tree_contents([('a', '0123456789'),
1306
'# Bazaar revision bundle v0.9\n#\n')
1308
# The requests to the old server will be redirected to the new server
1309
self.old_transport = self._transport(self.old_server.get_url())
1311
def test_redirected(self):
1312
self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1313
t = self._transport(self.new_server.get_url())
1314
self.assertEqual('0123456789', t.get('a').read())
1316
def test_read_redirected_bundle_from_url(self):
1317
from bzrlib.bundle import read_bundle_from_url
1318
url = self.old_transport.abspath('bundle')
1319
bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1320
read_bundle_from_url, url)
1321
# If read_bundle_from_url was successful we get an empty bundle
1322
self.assertEqual([], bundle.revisions)
1325
class RedirectedRequest(_urllib2_wrappers.Request):
1326
"""Request following redirections. """
1328
init_orig = _urllib2_wrappers.Request.__init__
1330
def __init__(self, method, url, *args, **kwargs):
1334
# Since the tests using this class will replace
1335
# _urllib2_wrappers.Request, we can't just call the base class __init__
1337
RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
1338
self.follow_redirections = True
1341
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1342
"""Test redirections.
1344
http implementations do not redirect silently anymore (they
1345
do not redirect at all in fact). The mechanism is still in
1346
place at the _urllib2_wrappers.Request level and these tests
1349
For the pycurl implementation
1350
the redirection have been deleted as we may deprecate pycurl
1351
and I have no place to keep a working implementation.
1356
if pycurl_present and self._transport == PyCurlTransport:
1357
raise tests.TestNotApplicable(
1358
"pycurl doesn't redirect silently annymore")
1359
super(TestHTTPSilentRedirections, self).setUp()
1360
self.setup_redirected_request()
1361
self.addCleanup(self.cleanup_redirected_request)
1362
self.build_tree_contents([('a','a'),
1364
('1/a', 'redirected once'),
1366
('2/a', 'redirected twice'),
1368
('3/a', 'redirected thrice'),
1370
('4/a', 'redirected 4 times'),
1372
('5/a', 'redirected 5 times'),
1375
self.old_transport = self._transport(self.old_server.get_url())
1377
def setup_redirected_request(self):
1378
self.original_class = _urllib2_wrappers.Request
1379
_urllib2_wrappers.Request = RedirectedRequest
1381
def cleanup_redirected_request(self):
1382
_urllib2_wrappers.Request = self.original_class
1384
def create_transport_secondary_server(self):
1385
"""Create the secondary server, redirections are defined in the tests"""
1386
return http_utils.HTTPServerRedirecting(
1387
protocol_version=self._protocol_version)
1389
def test_one_redirection(self):
1390
t = self.old_transport
1392
req = RedirectedRequest('GET', t.abspath('a'))
1393
req.follow_redirections = True
1394
new_prefix = 'http://%s:%s' % (self.new_server.host,
1395
self.new_server.port)
1396
self.old_server.redirections = \
1397
[('(.*)', r'%s/1\1' % (new_prefix), 301),]
1398
self.assertEquals('redirected once',t._perform(req).read())
1400
def test_five_redirections(self):
1401
t = self.old_transport
1403
req = RedirectedRequest('GET', t.abspath('a'))
1404
req.follow_redirections = True
1405
old_prefix = 'http://%s:%s' % (self.old_server.host,
1406
self.old_server.port)
1407
new_prefix = 'http://%s:%s' % (self.new_server.host,
1408
self.new_server.port)
1409
self.old_server.redirections = [
1410
('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1411
('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1412
('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1413
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1414
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1416
self.assertEquals('redirected 5 times',t._perform(req).read())
1419
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1420
"""Test transport.do_catching_redirections."""
1423
super(TestDoCatchRedirections, self).setUp()
1424
self.build_tree_contents([('a', '0123456789'),],)
1426
self.old_transport = self._transport(self.old_server.get_url())
1428
def get_a(self, transport):
1429
return transport.get('a')
1431
def test_no_redirection(self):
1432
t = self._transport(self.new_server.get_url())
1434
# We use None for redirected so that we fail if redirected
1435
self.assertEquals('0123456789',
1436
transport.do_catching_redirections(
1437
self.get_a, t, None).read())
1439
def test_one_redirection(self):
1440
self.redirections = 0
1442
def redirected(transport, exception, redirection_notice):
1443
self.redirections += 1
1444
dir, file = urlutils.split(exception.target)
1445
return self._transport(dir)
1447
self.assertEquals('0123456789',
1448
transport.do_catching_redirections(
1449
self.get_a, self.old_transport, redirected).read())
1450
self.assertEquals(1, self.redirections)
1452
def test_redirection_loop(self):
1454
def redirected(transport, exception, redirection_notice):
1455
# By using the redirected url as a base dir for the
1456
# *old* transport, we create a loop: a => a/a =>
1458
return self.old_transport.clone(exception.target)
1460
self.assertRaises(errors.TooManyRedirections,
1461
transport.do_catching_redirections,
1462
self.get_a, self.old_transport, redirected)
1465
class TestAuth(http_utils.TestCaseWithWebserver):
1466
"""Test authentication scheme"""
1468
_auth_header = 'Authorization'
1469
_password_prompt_prefix = ''
1470
_username_prompt_prefix = ''
1475
super(TestAuth, self).setUp()
1476
self.server = self.get_readonly_server()
1477
self.build_tree_contents([('a', 'contents of a\n'),
1478
('b', 'contents of b\n'),])
1480
def create_transport_readonly_server(self):
1481
return self._auth_server(protocol_version=self._protocol_version)
1483
def _testing_pycurl(self):
1484
return pycurl_present and self._transport == PyCurlTransport
1486
def get_user_url(self, user, password):
1487
"""Build an url embedding user and password"""
1488
url = '%s://' % self.server._url_protocol
1489
if user is not None:
1491
if password is not None:
1492
url += ':' + password
1494
url += '%s:%s/' % (self.server.host, self.server.port)
1497
def get_user_transport(self, user, password):
1498
return self._transport(self.get_user_url(user, password))
1500
def test_no_user(self):
1501
self.server.add_user('joe', 'foo')
1502
t = self.get_user_transport(None, None)
1503
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1504
# Only one 'Authentication Required' error should occur
1505
self.assertEqual(1, self.server.auth_required_errors)
1507
def test_empty_pass(self):
1508
self.server.add_user('joe', '')
1509
t = self.get_user_transport('joe', '')
1510
self.assertEqual('contents of a\n', t.get('a').read())
1511
# Only one 'Authentication Required' error should occur
1512
self.assertEqual(1, self.server.auth_required_errors)
1514
def test_user_pass(self):
1515
self.server.add_user('joe', 'foo')
1516
t = self.get_user_transport('joe', 'foo')
1517
self.assertEqual('contents of a\n', t.get('a').read())
1518
# Only one 'Authentication Required' error should occur
1519
self.assertEqual(1, self.server.auth_required_errors)
1521
def test_unknown_user(self):
1522
self.server.add_user('joe', 'foo')
1523
t = self.get_user_transport('bill', 'foo')
1524
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1525
# Two 'Authentication Required' errors should occur (the
1526
# initial 'who are you' and 'I don't know you, who are
1528
self.assertEqual(2, self.server.auth_required_errors)
1530
def test_wrong_pass(self):
1531
self.server.add_user('joe', 'foo')
1532
t = self.get_user_transport('joe', 'bar')
1533
self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1534
# Two 'Authentication Required' errors should occur (the
1535
# initial 'who are you' and 'this is not you, who are you')
1536
self.assertEqual(2, self.server.auth_required_errors)
1538
def test_prompt_for_username(self):
1539
if self._testing_pycurl():
1540
raise tests.TestNotApplicable(
1541
'pycurl cannot prompt, it handles auth by embedding'
1542
' user:pass in urls only')
1544
self.server.add_user('joe', 'foo')
1545
t = self.get_user_transport(None, None)
1546
stdout = tests.StringIOWrapper()
1547
ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n', stdout=stdout)
1548
self.assertEqual('contents of a\n',t.get('a').read())
1549
# stdin should be empty
1550
self.assertEqual('', ui.ui_factory.stdin.readline())
1552
expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1553
self.assertEquals(expected_prompt, stdout.read(len(expected_prompt)))
1554
self._check_password_prompt(t._unqualified_scheme, 'joe',
1557
def test_prompt_for_password(self):
1558
if self._testing_pycurl():
1559
raise tests.TestNotApplicable(
1560
'pycurl cannot prompt, it handles auth by embedding'
1561
' user:pass in urls only')
1563
self.server.add_user('joe', 'foo')
1564
t = self.get_user_transport('joe', None)
1565
stdout = tests.StringIOWrapper()
1566
ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
1567
self.assertEqual('contents of a\n',t.get('a').read())
1568
# stdin should be empty
1569
self.assertEqual('', ui.ui_factory.stdin.readline())
1570
self._check_password_prompt(t._unqualified_scheme, 'joe',
1572
# And we shouldn't prompt again for a different request
1573
# against the same transport.
1574
self.assertEqual('contents of b\n',t.get('b').read())
1576
# And neither against a clone
1577
self.assertEqual('contents of b\n',t2.get('b').read())
1578
# Only one 'Authentication Required' error should occur
1579
self.assertEqual(1, self.server.auth_required_errors)
1581
def _check_password_prompt(self, scheme, user, actual_prompt):
1582
expected_prompt = (self._password_prompt_prefix
1583
+ ("%s %s@%s:%d, Realm: '%s' password: "
1585
user, self.server.host, self.server.port,
1586
self.server.auth_realm)))
1587
self.assertEquals(expected_prompt, actual_prompt)
1589
def _expected_username_prompt(self, scheme):
1590
return (self._username_prompt_prefix
1591
+ "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1592
self.server.host, self.server.port,
1593
self.server.auth_realm))
1595
def test_no_prompt_for_password_when_using_auth_config(self):
1596
if self._testing_pycurl():
1597
raise tests.TestNotApplicable(
1598
'pycurl does not support authentication.conf'
1599
' since it cannot prompt')
1603
stdin_content = 'bar\n' # Not the right password
1604
self.server.add_user(user, password)
1605
t = self.get_user_transport(user, None)
1606
ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1607
stdout=tests.StringIOWrapper())
1608
# Create a minimal config file with the right password
1609
conf = config.AuthenticationConfig()
1610
conf._get_config().update(
1611
{'httptest': {'scheme': 'http', 'port': self.server.port,
1612
'user': user, 'password': password}})
1614
# Issue a request to the server to connect
1615
self.assertEqual('contents of a\n',t.get('a').read())
1616
# stdin should have been left untouched
1617
self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1618
# Only one 'Authentication Required' error should occur
1619
self.assertEqual(1, self.server.auth_required_errors)
1621
def test_user_from_auth_conf(self):
1622
if self._testing_pycurl():
1623
raise tests.TestNotApplicable(
1624
'pycurl does not support authentication.conf')
1627
self.server.add_user(user, password)
1628
# Create a minimal config file with the right password
1629
conf = config.AuthenticationConfig()
1630
conf._get_config().update(
1631
{'httptest': {'scheme': 'http', 'port': self.server.port,
1632
'user': user, 'password': password}})
1634
t = self.get_user_transport(None, None)
1635
# Issue a request to the server to connect
1636
self.assertEqual('contents of a\n', t.get('a').read())
1637
# Only one 'Authentication Required' error should occur
1638
self.assertEqual(1, self.server.auth_required_errors)
1640
def test_changing_nonce(self):
1641
if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1642
http_utils.ProxyDigestAuthServer):
1643
raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
1644
if self._testing_pycurl():
1645
raise tests.KnownFailure(
1646
'pycurl does not handle a nonce change')
1647
self.server.add_user('joe', 'foo')
1648
t = self.get_user_transport('joe', 'foo')
1649
self.assertEqual('contents of a\n', t.get('a').read())
1650
self.assertEqual('contents of b\n', t.get('b').read())
1651
# Only one 'Authentication Required' error should have
1653
self.assertEqual(1, self.server.auth_required_errors)
1654
# The server invalidates the current nonce
1655
self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1656
self.assertEqual('contents of a\n', t.get('a').read())
1657
# Two 'Authentication Required' errors should occur (the
1658
# initial 'who are you' and a second 'who are you' with the new nonce)
1659
self.assertEqual(2, self.server.auth_required_errors)
1663
class TestProxyAuth(TestAuth):
1664
"""Test proxy authentication schemes."""
1666
_auth_header = 'Proxy-authorization'
1667
_password_prompt_prefix = 'Proxy '
1668
_username_prompt_prefix = 'Proxy '
1671
super(TestProxyAuth, self).setUp()
1673
self.addCleanup(self._restore_env)
1674
# Override the contents to avoid false positives
1675
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1676
('b', 'not proxied contents of b\n'),
1677
('a-proxied', 'contents of a\n'),
1678
('b-proxied', 'contents of b\n'),
1681
def get_user_transport(self, user, password):
1682
self._install_env({'all_proxy': self.get_user_url(user, password)})
1683
return self._transport(self.server.get_url())
1685
def _install_env(self, env):
1686
for name, value in env.iteritems():
1687
self._old_env[name] = osutils.set_or_unset_env(name, value)
1689
def _restore_env(self):
1690
for name, value in self._old_env.iteritems():
1691
osutils.set_or_unset_env(name, value)
1693
def test_empty_pass(self):
1694
if self._testing_pycurl():
1696
if pycurl.version_info()[1] < '7.16.0':
1697
raise tests.KnownFailure(
1698
'pycurl < 7.16.0 does not handle empty proxy passwords')
1699
super(TestProxyAuth, self).test_empty_pass()
1702
class SampleSocket(object):
1703
"""A socket-like object for use in testing the HTTP request handler."""
1705
def __init__(self, socket_read_content):
1706
"""Constructs a sample socket.
1708
:param socket_read_content: a byte sequence
1710
# Use plain python StringIO so we can monkey-patch the close method to
1711
# not discard the contents.
1712
from StringIO import StringIO
1713
self.readfile = StringIO(socket_read_content)
1714
self.writefile = StringIO()
1715
self.writefile.close = lambda: None
1717
def makefile(self, mode='r', bufsize=None):
1719
return self.readfile
1721
return self.writefile
1724
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1727
super(SmartHTTPTunnellingTest, self).setUp()
1728
# We use the VFS layer as part of HTTP tunnelling tests.
1729
self._captureVar('BZR_NO_SMART_VFS', None)
1730
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1732
def create_transport_readonly_server(self):
1733
return http_utils.HTTPServerWithSmarts(
1734
protocol_version=self._protocol_version)
1736
def test_open_bzrdir(self):
1737
branch = self.make_branch('relpath')
1738
http_server = self.get_readonly_server()
1739
url = http_server.get_url() + 'relpath'
1740
bd = bzrdir.BzrDir.open(url)
1741
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1743
def test_bulk_data(self):
1744
# We should be able to send and receive bulk data in a single message.
1745
# The 'readv' command in the smart protocol both sends and receives
1746
# bulk data, so we use that.
1747
self.build_tree(['data-file'])
1748
http_server = self.get_readonly_server()
1749
http_transport = self._transport(http_server.get_url())
1750
medium = http_transport.get_smart_medium()
1751
# Since we provide the medium, the url below will be mostly ignored
1752
# during the test, as long as the path is '/'.
1753
remote_transport = remote.RemoteTransport('bzr://fake_host/',
1756
[(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1758
def test_http_send_smart_request(self):
1760
post_body = 'hello\n'
1761
expected_reply_body = 'ok\x012\n'
1763
http_server = self.get_readonly_server()
1764
http_transport = self._transport(http_server.get_url())
1765
medium = http_transport.get_smart_medium()
1766
response = medium.send_http_smart_request(post_body)
1767
reply_body = response.read()
1768
self.assertEqual(expected_reply_body, reply_body)
1770
def test_smart_http_server_post_request_handler(self):
1771
httpd = self.get_readonly_server()._get_httpd()
1773
socket = SampleSocket(
1774
'POST /.bzr/smart %s \r\n' % self._protocol_version
1775
# HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1777
+ 'Content-Length: 6\r\n'
1780
# Beware: the ('localhost', 80) below is the
1781
# client_address parameter, but we don't have one because
1782
# we have defined a socket which is not bound to an
1783
# address. The test framework never uses this client
1784
# address, so far...
1785
request_handler = http_utils.SmartRequestHandler(socket,
1788
response = socket.writefile.getvalue()
1789
self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1790
# This includes the end of the HTTP headers, and all the body.
1791
expected_end_of_response = '\r\n\r\nok\x012\n'
1792
self.assertEndsWith(response, expected_end_of_response)
1795
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1796
"""No smart server here request handler."""
1799
self.send_error(403, "Forbidden")
1802
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1803
"""Test smart client behaviour against an http server without smarts."""
1805
_req_handler_class = ForbiddenRequestHandler
1807
def test_probe_smart_server(self):
1808
"""Test error handling against server refusing smart requests."""
1809
server = self.get_readonly_server()
1810
t = self._transport(server.get_url())
1811
# No need to build a valid smart request here, the server will not even
1812
# try to interpret it.
1813
self.assertRaises(errors.SmartProtocolError,
1814
t.get_smart_medium().send_http_smart_request,
1817
class Test_redirected_to(tests.TestCase):
1819
def test_redirected_to_subdir(self):
1820
t = self._transport('http://www.example.com/foo')
1821
r = t._redirected_to('http://www.example.com/foo',
1822
'http://www.example.com/foo/subdir')
1823
self.assertIsInstance(r, type(t))
1824
# Both transports share the some connection
1825
self.assertEquals(t._get_connection(), r._get_connection())
1827
def test_redirected_to_self_with_slash(self):
1828
t = self._transport('http://www.example.com/foo')
1829
r = t._redirected_to('http://www.example.com/foo',
1830
'http://www.example.com/foo/')
1831
self.assertIsInstance(r, type(t))
1832
# Both transports share the some connection (one can argue that we
1833
# should return the exact same transport here, but that seems
1835
self.assertEquals(t._get_connection(), r._get_connection())
1837
def test_redirected_to_host(self):
1838
t = self._transport('http://www.example.com/foo')
1839
r = t._redirected_to('http://www.example.com/foo',
1840
'http://foo.example.com/foo/subdir')
1841
self.assertIsInstance(r, type(t))
1843
def test_redirected_to_same_host_sibling_protocol(self):
1844
t = self._transport('http://www.example.com/foo')
1845
r = t._redirected_to('http://www.example.com/foo',
1846
'https://www.example.com/foo')
1847
self.assertIsInstance(r, type(t))
1849
def test_redirected_to_same_host_different_protocol(self):
1850
t = self._transport('http://www.example.com/foo')
1851
r = t._redirected_to('http://www.example.com/foo',
1852
'ftp://www.example.com/foo')
1853
self.assertNotEquals(type(r), type(t))
1855
def test_redirected_to_different_host_same_user(self):
1856
t = self._transport('http://joe@www.example.com/foo')
1857
r = t._redirected_to('http://www.example.com/foo',
1858
'https://foo.example.com/foo')
1859
self.assertIsInstance(r, type(t))
1860
self.assertEquals(t._user, r._user)
1863
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1864
"""Request handler for a unique and pre-defined request.
1866
The only thing we care about here is how many bytes travel on the wire. But
1867
since we want to measure it for a real http client, we have to send it
1870
We expect to receive a *single* request nothing more (and we won't even
1871
check what request it is, we just measure the bytes read until an empty
1875
def handle_one_request(self):
1876
tcs = self.server.test_case_server
1877
requestline = self.rfile.readline()
1878
headers = self.MessageClass(self.rfile, 0)
1879
# We just read: the request, the headers, an empty line indicating the
1880
# end of the headers.
1881
bytes_read = len(requestline)
1882
for line in headers.headers:
1883
bytes_read += len(line)
1884
bytes_read += len('\r\n')
1885
if requestline.startswith('POST'):
1886
# The body should be a single line (or we don't know where it ends
1887
# and we don't want to issue a blocking read)
1888
body = self.rfile.readline()
1889
bytes_read += len(body)
1890
tcs.bytes_read = bytes_read
1892
# We set the bytes written *before* issuing the write, the client is
1893
# supposed to consume every produced byte *before* checking that value.
1895
# Doing the oppposite may lead to test failure: we may be interrupted
1896
# after the write but before updating the value. The client can then
1897
# continue and read the value *before* we can update it. And yes,
1898
# this has been observed -- vila 20090129
1899
tcs.bytes_written = len(tcs.canned_response)
1900
self.wfile.write(tcs.canned_response)
1903
class ActivityServerMixin(object):
1905
def __init__(self, protocol_version):
1906
super(ActivityServerMixin, self).__init__(
1907
request_handler=PredefinedRequestHandler,
1908
protocol_version=protocol_version)
1909
# Bytes read and written by the server
1911
self.bytes_written = 0
1912
self.canned_response = None
1915
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1919
if tests.HTTPSServerFeature.available():
1920
from bzrlib.tests import https_server
1921
class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1925
class TestActivity(tests.TestCase):
1926
"""Test socket activity reporting.
1928
We use a special purpose server to control the bytes sent and received and
1929
be able to predict the activity on the client socket.
1933
tests.TestCase.setUp(self)
1934
self.server = self._activity_server(self._protocol_version)
1936
self.activities = {}
1937
def report_activity(t, bytes, direction):
1938
count = self.activities.get(direction, 0)
1940
self.activities[direction] = count
1942
# We override at class level because constructors may propagate the
1943
# bound method and render instance overriding ineffective (an
1944
# alternative would be to define a specific ui factory instead...)
1945
self.orig_report_activity = self._transport._report_activity
1946
self._transport._report_activity = report_activity
1949
self._transport._report_activity = self.orig_report_activity
1950
self.server.tearDown()
1951
tests.TestCase.tearDown(self)
1953
def get_transport(self):
1954
return self._transport(self.server.get_url())
1956
def assertActivitiesMatch(self):
1957
self.assertEqual(self.server.bytes_read,
1958
self.activities.get('write', 0), 'written bytes')
1959
self.assertEqual(self.server.bytes_written,
1960
self.activities.get('read', 0), 'read bytes')
1963
self.server.canned_response = '''HTTP/1.1 200 OK\r
1964
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1965
Server: Apache/2.0.54 (Fedora)\r
1966
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1967
ETag: "56691-23-38e9ae00"\r
1968
Accept-Ranges: bytes\r
1969
Content-Length: 35\r
1971
Content-Type: text/plain; charset=UTF-8\r
1973
Bazaar-NG meta directory, format 1
1975
t = self.get_transport()
1976
self.assertEqual('Bazaar-NG meta directory, format 1\n',
1977
t.get('foo/bar').read())
1978
self.assertActivitiesMatch()
1981
self.server.canned_response = '''HTTP/1.1 200 OK\r
1982
Server: SimpleHTTP/0.6 Python/2.5.2\r
1983
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
1984
Content-type: application/octet-stream\r
1985
Content-Length: 20\r
1986
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
1989
t = self.get_transport()
1990
self.assertTrue(t.has('foo/bar'))
1991
self.assertActivitiesMatch()
1993
def test_readv(self):
1994
self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
1995
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
1996
Server: Apache/2.0.54 (Fedora)\r
1997
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
1998
ETag: "238a3c-16ec2-805c5540"\r
1999
Accept-Ranges: bytes\r
2000
Content-Length: 1534\r
2002
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2005
--418470f848b63279b\r
2006
Content-type: text/plain; charset=UTF-8\r
2007
Content-range: bytes 0-254/93890\r
2009
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2010
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2011
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2012
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2013
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2015
--418470f848b63279b\r
2016
Content-type: text/plain; charset=UTF-8\r
2017
Content-range: bytes 1000-2049/93890\r
2020
mbp@sourcefrog.net-20050311063625-07858525021f270b
2021
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2022
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2023
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2024
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2025
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2026
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2027
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2028
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2029
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2030
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2031
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2032
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2033
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2034
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2035
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2036
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2037
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2038
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2039
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2041
--418470f848b63279b--\r
2043
t = self.get_transport()
2044
# Remember that the request is ignored and that the ranges below
2045
# doesn't have to match the canned response.
2046
l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2047
self.assertEqual(2, len(l))
2048
self.assertActivitiesMatch()
2050
def test_post(self):
2051
self.server.canned_response = '''HTTP/1.1 200 OK\r
2052
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2053
Server: Apache/2.0.54 (Fedora)\r
2054
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2055
ETag: "56691-23-38e9ae00"\r
2056
Accept-Ranges: bytes\r
2057
Content-Length: 35\r
2059
Content-Type: text/plain; charset=UTF-8\r
2061
lalala whatever as long as itsssss
2063
t = self.get_transport()
2064
# We must send a single line of body bytes, see
2065
# PredefinedRequestHandler.handle_one_request
2066
code, f = t._post('abc def end-of-body\n')
2067
self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2068
self.assertActivitiesMatch()