78
80
transport_scenarios = [
79
81
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
80
82
_server=http_server.HttpServer_urllib,
81
_url_protocol='http+urllib',)),
83
_qualified_prefix='http+urllib',)),
83
85
if features.pycurl.available():
84
86
transport_scenarios.append(
85
87
('pycurl', dict(_transport=PyCurlTransport,
86
88
_server=http_server.HttpServer_PyCurl,
87
_url_protocol='http+pycurl',)))
89
_qualified_prefix='http+pycurl',)))
88
90
tests.multiply_tests(t_tests, transport_scenarios, result)
90
protocol_scenarios = [
91
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
92
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
95
# some tests are parametrized by the protocol version only
96
p_tests, remaining_tests = tests.split_suite_by_condition(
97
remaining_tests, tests.condition_isinstance((
100
tests.multiply_tests(p_tests, protocol_scenarios, result)
102
92
# each implementation tested with each HTTP version
103
93
tp_tests, remaining_tests = tests.split_suite_by_condition(
104
94
remaining_tests, tests.condition_isinstance((
114
104
TestSpecificRequestHandler,
106
protocol_scenarios = [
107
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
108
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
116
110
tp_scenarios = tests.multiply_scenarios(transport_scenarios,
117
111
protocol_scenarios)
118
112
tests.multiply_tests(tp_tests, tp_scenarios, result)
229
223
self._sock.bind(('127.0.0.1', 0))
230
224
self.host, self.port = self._sock.getsockname()
231
225
self._ready = threading.Event()
232
self._thread = test_server.ThreadWithException(
233
event=self._ready, target=self._accept_read_and_reply)
226
self._thread = threading.Thread(target=self._accept_read_and_reply)
227
self._thread.setDaemon(True)
234
228
self._thread.start()
235
if 'threads' in tests.selftest_debug_flags:
236
sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
239
231
def _accept_read_and_reply(self):
240
232
self._sock.listen(1)
241
233
self._ready.set()
242
conn, address = self._sock.accept()
243
if self._expect_body_tail is not None:
234
self._sock.settimeout(5)
236
conn, address = self._sock.accept()
237
# On win32, the accepted connection will be non-blocking to start
238
# with because we're using settimeout.
239
conn.setblocking(True)
244
240
while not self.received_bytes.endswith(self._expect_body_tail):
245
241
self.received_bytes += conn.recv(4096)
246
242
conn.sendall('HTTP/1.1 200 OK\r\n')
243
except socket.timeout:
244
# Make sure the client isn't stuck waiting for us to e.g. accept.
248
245
self._sock.close()
249
246
except socket.error:
250
247
# The client may have already closed the socket.
253
250
def stop_server(self):
255
# Issue a fake connection to wake up the server and allow it to
257
fake_conn = osutils.connect_socket((self.host, self.port))
259
253
except socket.error:
260
254
# We might have already closed it. We don't care.
265
if 'threads' in tests.selftest_debug_flags:
266
sys.stderr.write('Thread joined: %s\n' % (self._thread.ident,))
269
260
class TestAuthHeader(tests.TestCase):
314
305
protocol_version = 'HTTP/0.1'
316
self.assertRaises(httplib.UnknownProtocol,
317
http_server.HttpServer, BogusRequestHandler)
307
server = http_server.HttpServer(BogusRequestHandler)
309
self.assertRaises(httplib.UnknownProtocol, server.start_server)
312
self.fail('HTTP Server creation did not raise UnknownProtocol')
319
314
def test_force_invalid_protocol(self):
320
self.assertRaises(httplib.UnknownProtocol,
321
http_server.HttpServer, protocol_version='HTTP/0.1')
315
server = http_server.HttpServer(protocol_version='HTTP/0.1')
317
self.assertRaises(httplib.UnknownProtocol, server.start_server)
320
self.fail('HTTP Server creation did not raise UnknownProtocol')
323
322
def test_server_start_and_stop(self):
324
323
server = http_server.HttpServer()
325
self.addCleanup(server.stop_server)
326
324
server.start_server()
327
self.assertTrue(server.server is not None)
328
self.assertTrue(server.server.serving is not None)
329
self.assertTrue(server.server.serving)
326
self.assertTrue(server._http_running)
329
self.assertFalse(server._http_running)
331
331
def test_create_http_server_one_zero(self):
332
332
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
336
336
server = http_server.HttpServer(RequestHandlerOneZero)
337
337
self.start_server(server)
338
self.assertIsInstance(server.server, http_server.TestingHTTPServer)
338
self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
340
340
def test_create_http_server_one_one(self):
341
341
class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
345
345
server = http_server.HttpServer(RequestHandlerOneOne)
346
346
self.start_server(server)
347
self.assertIsInstance(server.server,
347
self.assertIsInstance(server._httpd,
348
348
http_server.TestingThreadingHTTPServer)
350
350
def test_create_http_server_force_one_one(self):
355
355
server = http_server.HttpServer(RequestHandlerOneZero,
356
356
protocol_version='HTTP/1.1')
357
357
self.start_server(server)
358
self.assertIsInstance(server.server,
358
self.assertIsInstance(server._httpd,
359
359
http_server.TestingThreadingHTTPServer)
361
361
def test_create_http_server_force_one_zero(self):
366
366
server = http_server.HttpServer(RequestHandlerOneOne,
367
367
protocol_version='HTTP/1.0')
368
368
self.start_server(server)
369
self.assertIsInstance(server.server,
369
self.assertIsInstance(server._httpd,
370
370
http_server.TestingHTTPServer)
391
391
self.assertEqual('http://example.com', url)
392
392
self.assertEqual(0, len(f.credentials))
393
393
url = http.extract_auth(
394
'http://user:pass@example.com/bzr/bzr.dev', f)
395
self.assertEqual('http://example.com/bzr/bzr.dev', url)
394
'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
395
self.assertEqual('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
396
396
self.assertEqual(1, len(f.credentials))
397
self.assertEqual([None, 'example.com', 'user', 'pass'],
397
self.assertEqual([None, 'www.bazaar-vcs.org', 'user', 'pass'],
398
398
f.credentials[0])
452
452
# Import the module locally now that we now it's available.
453
453
pycurl = features.pycurl.module
455
self.overrideAttr(pycurl, 'version_info',
456
# Fake the pycurl version_info This was taken from
457
# a windows pycurl without SSL (thanks to bialix)
466
('ftp', 'gopher', 'telnet',
467
'dict', 'ldap', 'http', 'file'),
455
version_info_orig = pycurl.version_info
457
pycurl.version_info = version_info_orig
458
self.addCleanup(restore)
460
# Fake the pycurl version_info This was taken from a windows pycurl
461
# without SSL (thanks to bialix)
462
pycurl.version_info = lambda : (2,
470
('ftp', 'gopher', 'telnet',
471
'dict', 'ldap', 'http', 'file'),
471
475
self.assertRaises(errors.DependencyNotPresent, self._transport,
472
476
'https://launchpad.net')
483
487
def test_http_has(self):
484
488
server = self.get_readonly_server()
485
t = self.get_readonly_transport()
489
t = self._transport(server.get_url())
486
490
self.assertEqual(t.has('foo/bar'), True)
487
491
self.assertEqual(len(server.logs), 1)
488
492
self.assertContainsRe(server.logs[0],
491
495
def test_http_has_not_found(self):
492
496
server = self.get_readonly_server()
493
t = self.get_readonly_transport()
497
t = self._transport(server.get_url())
494
498
self.assertEqual(t.has('not-found'), False)
495
499
self.assertContainsRe(server.logs[1],
496
500
r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
498
502
def test_http_get(self):
499
503
server = self.get_readonly_server()
500
t = self.get_readonly_transport()
504
t = self._transport(server.get_url())
501
505
fp = t.get('foo/bar')
502
506
self.assertEqualDiff(
526
530
"""Test registrations of various http implementations"""
528
532
def test_http_registered(self):
529
t = transport.get_transport('%s://foo.com/' % self._url_protocol)
533
t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
530
534
self.assertIsInstance(t, transport.Transport)
531
535
self.assertIsInstance(t, self._transport)
536
540
def test_post_body_is_received(self):
537
541
server = RecordingServer(expect_body_tail='end-of-body',
538
scheme=self._url_protocol)
542
scheme=self._qualified_prefix)
539
543
self.start_server(server)
540
544
url = server.get_url()
541
# FIXME: needs a cleanup -- vila 20100611
542
http_transport = transport.get_transport(url)
545
http_transport = self._transport(url)
543
546
code, response = http_transport._post('abc def end-of-body')
545
548
server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
589
592
_req_handler_class = http_server.TestingHTTPRequestHandler
591
594
def create_transport_readonly_server(self):
592
server = http_server.HttpServer(self._req_handler_class,
593
protocol_version=self._protocol_version)
594
server._url_protocol = self._url_protocol
595
return http_server.HttpServer(self._req_handler_class,
596
protocol_version=self._protocol_version)
597
598
def _testing_pycurl(self):
598
599
# TODO: This is duplicated for lots of the classes in this file
603
604
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
604
605
"""Whatever request comes in, close the connection"""
606
def _handle_one_request(self):
607
def handle_one_request(self):
607
608
"""Handle a single HTTP request, by abruptly closing the connection"""
608
609
self.close_connection = 1
614
615
_req_handler_class = WallRequestHandler
616
617
def test_http_has(self):
617
t = self.get_readonly_transport()
618
server = self.get_readonly_server()
619
t = self._transport(server.get_url())
618
620
# Unfortunately httplib (see HTTPResponse._read_status
619
621
# for details) make no distinction between a closed
620
622
# socket and badly formatted status line, so we can't
649
652
_req_handler_class = BadStatusRequestHandler
651
654
def test_http_has(self):
652
t = self.get_readonly_transport()
655
server = self.get_readonly_server()
656
t = self._transport(server.get_url())
653
657
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
655
659
def test_http_get(self):
656
t = self.get_readonly_transport()
660
server = self.get_readonly_server()
661
t = self._transport(server.get_url())
657
662
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
664
669
"""Fakes handling a single HTTP request, returns a bad status"""
665
670
ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
666
671
self.wfile.write("Invalid status line\r\n")
667
# If we don't close the connection pycurl will hang. Since this is a
668
# stress test we don't *have* to respect the protocol, but we don't
669
# have to sabotage it too much either.
670
self.close_connection = True
680
681
_req_handler_class = InvalidStatusRequestHandler
683
def test_http_has(self):
684
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
685
raise tests.KnownFailure(
686
'pycurl hangs if the server send back garbage')
687
super(TestInvalidStatusServer, self).test_http_has()
689
def test_http_get(self):
690
if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
691
raise tests.KnownFailure(
692
'pycurl hangs if the server send back garbage')
693
super(TestInvalidStatusServer, self).test_http_get()
683
696
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
684
697
"""Whatever request comes in, returns a bad protocol version"""
706
719
super(TestBadProtocolServer, self).setUp()
708
721
def test_http_has(self):
709
t = self.get_readonly_transport()
722
server = self.get_readonly_server()
723
t = self._transport(server.get_url())
710
724
self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
712
726
def test_http_get(self):
713
t = self.get_readonly_transport()
727
server = self.get_readonly_server()
728
t = self._transport(server.get_url())
714
729
self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
730
745
_req_handler_class = ForbiddenRequestHandler
732
747
def test_http_has(self):
733
t = self.get_readonly_transport()
748
server = self.get_readonly_server()
749
t = self._transport(server.get_url())
734
750
self.assertRaises(errors.TransportError, t.has, 'foo/bar')
736
752
def test_http_get(self):
737
t = self.get_readonly_transport()
753
server = self.get_readonly_server()
754
t = self._transport(server.get_url())
738
755
self.assertRaises(errors.TransportError, t.get, 'foo/bar')
779
796
self.build_tree_contents([('a', '0123456789')],)
781
798
def test_readv(self):
782
t = self.get_readonly_transport()
799
server = self.get_readonly_server()
800
t = self._transport(server.get_url())
783
801
l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
784
802
self.assertEqual(l[0], (0, '0'))
785
803
self.assertEqual(l[1], (1, '1'))
787
805
self.assertEqual(l[3], (9, '9'))
789
807
def test_readv_out_of_order(self):
790
t = self.get_readonly_transport()
808
server = self.get_readonly_server()
809
t = self._transport(server.get_url())
791
810
l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
792
811
self.assertEqual(l[0], (1, '1'))
793
812
self.assertEqual(l[1], (9, '9'))
795
814
self.assertEqual(l[3], (3, '34'))
797
816
def test_readv_invalid_ranges(self):
798
t = self.get_readonly_transport()
817
server = self.get_readonly_server()
818
t = self._transport(server.get_url())
800
820
# This is intentionally reading off the end of the file
801
821
# since we are sure that it cannot get there
824
844
def test_readv_get_max_size(self):
825
845
server = self.get_readonly_server()
826
t = self.get_readonly_transport()
846
t = self._transport(server.get_url())
827
847
# force transport to issue multiple requests by limiting the number of
828
848
# bytes by request. Note that this apply to coalesced offsets only, a
829
849
# single range will keep its size even if bigger than the limit.
839
859
def test_complete_readv_leave_pipe_clean(self):
840
860
server = self.get_readonly_server()
841
t = self.get_readonly_transport()
861
t = self._transport(server.get_url())
842
862
# force transport to issue multiple requests
843
863
t._get_max_size = 2
844
864
l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
1006
1026
def test_readv_with_short_reads(self):
1007
1027
server = self.get_readonly_server()
1008
t = self.get_readonly_transport()
1028
t = self._transport(server.get_url())
1009
1029
# Force separate ranges for each offset
1010
1030
t._bytes_to_read_before_seek = 0
1011
1031
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1071
1094
self.build_tree_contents([('a', content)],)
1073
1096
def test_few_ranges(self):
1074
t = self.get_readonly_transport()
1097
t = self.get_transport()
1075
1098
l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
1099
self.assertEqual(l[0], (0, '0000'))
1077
1100
self.assertEqual(l[1], (1024, '0001'))
1078
1101
self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1080
1103
def test_more_ranges(self):
1081
t = self.get_readonly_transport()
1104
t = self.get_transport()
1082
1105
l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
1106
self.assertEqual(l[0], (0, '0000'))
1084
1107
self.assertEqual(l[1], (1024, '0001'))
1137
1163
# FIXME: We don't have an https server available, so we don't
1138
# test https connections. --vila toolongago
1164
# test https connections.
1140
1166
def setUp(self):
1141
1167
super(TestProxyHttpServer, self).setUp()
1142
self.transport_secondary_server = http_utils.ProxyServer
1143
1168
self.build_tree_contents([('foo', 'contents of foo\n'),
1144
1169
('foo-proxied', 'proxied contents of foo\n')])
1145
1170
# Let's setup some attributes for tests
1146
server = self.get_readonly_server()
1147
self.server_host_port = '%s:%d' % (server.host, server.port)
1171
self.server = self.get_readonly_server()
1172
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1148
1173
if self._testing_pycurl():
1149
1174
# Oh my ! pycurl does not check for the port as part of
1150
1175
# no_proxy :-( So we just test the host part
1151
self.no_proxy_host = server.host
1176
self.no_proxy_host = self.server.host
1153
self.no_proxy_host = self.server_host_port
1178
self.no_proxy_host = self.proxy_address
1154
1179
# The secondary server is the proxy
1155
self.proxy_url = self.get_secondary_url()
1180
self.proxy = self.get_secondary_server()
1181
self.proxy_url = self.proxy.get_url()
1156
1182
self._old_env = {}
1158
1184
def _testing_pycurl(self):
1160
1186
return (features.pycurl.available()
1161
1187
and self._transport == PyCurlTransport)
1189
def create_transport_secondary_server(self):
1190
"""Creates an http server that will serve files with
1191
'-proxied' appended to their names.
1193
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1163
1195
def _install_env(self, env):
1164
1196
for name, value in env.iteritems():
1165
1197
self._old_env[name] = osutils.set_or_unset_env(name, value)
1226
1260
# pycurl *ignores* invalid proxy env variables. If that ever change
1227
1261
# in the future, this test will fail indicating that pycurl do not
1228
1262
# ignore anymore such variables.
1229
self.not_proxied_in_env({'http_proxy': self.server_host_port})
1263
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1231
1265
self.assertRaises(errors.InvalidURL,
1232
1266
self.proxied_in_env,
1233
{'http_proxy': self.server_host_port})
1267
{'http_proxy': self.proxy_address})
1236
1270
class TestRanges(http_utils.TestCaseWithWebserver):
1239
1273
def setUp(self):
1240
1274
http_utils.TestCaseWithWebserver.setUp(self)
1241
1275
self.build_tree_contents([('a', '0123456789')],)
1276
server = self.get_readonly_server()
1277
self.transport = self._transport(server.get_url())
1243
1279
def create_transport_readonly_server(self):
1244
1280
return http_server.HttpServer(protocol_version=self._protocol_version)
1246
1282
def _file_contents(self, relpath, ranges):
1247
t = self.get_readonly_transport()
1248
1283
offsets = [ (start, end - start + 1) for start, end in ranges]
1249
coalesce = t._coalesce_offsets
1284
coalesce = self.transport._coalesce_offsets
1250
1285
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1251
code, data = t._get(relpath, coalesced)
1286
code, data = self.transport._get(relpath, coalesced)
1252
1287
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1253
1288
for start, end in ranges:
1254
1289
data.seek(start)
1255
1290
yield data.read(end - start + 1)
1257
1292
def _file_tail(self, relpath, tail_amount):
1258
t = self.get_readonly_transport()
1259
code, data = t._get(relpath, [], tail_amount)
1293
code, data = self.transport._get(relpath, [], tail_amount)
1260
1294
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1261
1295
data.seek(-tail_amount, 2)
1262
1296
return data.read(tail_amount)
1281
1315
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1282
1316
"""Test redirection between http servers."""
1318
def create_transport_secondary_server(self):
1319
"""Create the secondary server redirecting to the primary server"""
1320
new = self.get_readonly_server()
1322
redirecting = http_utils.HTTPServerRedirecting(
1323
protocol_version=self._protocol_version)
1324
redirecting.redirect_to(new.host, new.port)
1284
1327
def setUp(self):
1285
1328
super(TestHTTPRedirections, self).setUp()
1286
1329
self.build_tree_contents([('a', '0123456789'),
1288
1331
'# Bazaar revision bundle v0.9\n#\n')
1333
# The requests to the old server will be redirected to the new server
1334
self.old_transport = self._transport(self.old_server.get_url())
1291
1336
def test_redirected(self):
1292
self.assertRaises(errors.RedirectRequested,
1293
self.get_old_transport().get, 'a')
1294
self.assertEqual('0123456789', self.get_new_transport().get('a').read())
1337
self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1338
t = self._transport(self.new_server.get_url())
1339
self.assertEqual('0123456789', t.get('a').read())
1341
def test_read_redirected_bundle_from_url(self):
1342
from bzrlib.bundle import read_bundle_from_url
1343
url = self.old_transport.abspath('bundle')
1344
bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1345
read_bundle_from_url, url)
1346
# If read_bundle_from_url was successful we get an empty bundle
1347
self.assertEqual([], bundle.revisions)
1297
1350
class RedirectedRequest(_urllib2_wrappers.Request):
1313
1366
def install_redirected_request(test):
1314
test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1317
def cleanup_http_redirection_connections(test):
1318
# Some sockets are opened but never seen by _urllib, so we trap them at
1319
# the _urllib2_wrappers level to be able to clean them up.
1320
def socket_disconnect(sock):
1322
sock.shutdown(socket.SHUT_RDWR)
1324
except socket.error:
1326
def connect(connection):
1327
test.http_connect_orig(connection)
1328
test.addCleanup(socket_disconnect, connection.sock)
1329
test.http_connect_orig = test.overrideAttr(
1330
_urllib2_wrappers.HTTPConnection, 'connect', connect)
1331
def connect(connection):
1332
test.https_connect_orig(connection)
1333
test.addCleanup(socket_disconnect, connection.sock)
1334
test.https_connect_orig = test.overrideAttr(
1335
_urllib2_wrappers.HTTPSConnection, 'connect', connect)
1367
test.original_class = _urllib2_wrappers.Request
1369
_urllib2_wrappers.Request = test.original_class
1370
_urllib2_wrappers.Request = RedirectedRequest
1371
test.addCleanup(restore)
1338
1374
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1353
1389
if (features.pycurl.available()
1354
1390
and self._transport == PyCurlTransport):
1355
1391
raise tests.TestNotApplicable(
1356
"pycurl doesn't redirect silently anymore")
1392
"pycurl doesn't redirect silently annymore")
1357
1393
super(TestHTTPSilentRedirections, self).setUp()
1358
1394
install_redirected_request(self)
1359
cleanup_http_redirection_connections(self)
1360
1395
self.build_tree_contents([('a','a'),
1362
1397
('1/a', 'redirected once'),
1370
1405
('5/a', 'redirected 5 times'),
1408
self.old_transport = self._transport(self.old_server.get_url())
1410
def create_transport_secondary_server(self):
1411
"""Create the secondary server, redirections are defined in the tests"""
1412
return http_utils.HTTPServerRedirecting(
1413
protocol_version=self._protocol_version)
1373
1415
def test_one_redirection(self):
1374
t = self.get_old_transport()
1375
req = RedirectedRequest('GET', t._remote_path('a'))
1416
t = self.old_transport
1418
req = RedirectedRequest('GET', t.abspath('a'))
1376
1419
new_prefix = 'http://%s:%s' % (self.new_server.host,
1377
1420
self.new_server.port)
1378
1421
self.old_server.redirections = \
1379
1422
[('(.*)', r'%s/1\1' % (new_prefix), 301),]
1380
self.assertEqual('redirected once', t._perform(req).read())
1423
self.assertEqual('redirected once',t._perform(req).read())
1382
1425
def test_five_redirections(self):
1383
t = self.get_old_transport()
1384
req = RedirectedRequest('GET', t._remote_path('a'))
1426
t = self.old_transport
1428
req = RedirectedRequest('GET', t.abspath('a'))
1385
1429
old_prefix = 'http://%s:%s' % (self.old_server.host,
1386
1430
self.old_server.port)
1387
1431
new_prefix = 'http://%s:%s' % (self.new_server.host,
1393
1437
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1394
1438
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1396
self.assertEqual('redirected 5 times', t._perform(req).read())
1440
self.assertEqual('redirected 5 times',t._perform(req).read())
1399
1443
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1402
1446
def setUp(self):
1403
1447
super(TestDoCatchRedirections, self).setUp()
1404
1448
self.build_tree_contents([('a', '0123456789'),],)
1405
cleanup_http_redirection_connections(self)
1407
self.old_transport = self.get_old_transport()
1450
self.old_transport = self._transport(self.old_server.get_url())
1452
def get_a(self, transport):
1453
return transport.get('a')
1412
1455
def test_no_redirection(self):
1413
t = self.get_new_transport()
1456
t = self._transport(self.new_server.get_url())
1415
1458
# We use None for redirected so that we fail if redirected
1416
1459
self.assertEqual('0123456789',
1420
1463
def test_one_redirection(self):
1421
1464
self.redirections = 0
1423
def redirected(t, exception, redirection_notice):
1466
def redirected(transport, exception, redirection_notice):
1424
1467
self.redirections += 1
1425
redirected_t = t._redirected_to(exception.source, exception.target)
1468
dir, file = urlutils.split(exception.target)
1469
return self._transport(dir)
1428
1471
self.assertEqual('0123456789',
1429
1472
transport.do_catching_redirections(
1459
1502
('b', 'contents of b\n'),])
1461
1504
def create_transport_readonly_server(self):
1462
server = self._auth_server(protocol_version=self._protocol_version)
1463
server._url_protocol = self._url_protocol
1505
return self._auth_server(protocol_version=self._protocol_version)
1466
1507
def _testing_pycurl(self):
1467
1508
# TODO: This is duplicated for lots of the classes in this file
1673
1713
def get_user_transport(self, user, password):
1674
1714
self._install_env({'all_proxy': self.get_user_url(user, password)})
1675
return TestAuth.get_user_transport(self, user, password)
1715
return self._transport(self.server.get_url())
1677
1717
def _install_env(self, env):
1678
1718
for name, value in env.iteritems():
1721
1760
# We use the VFS layer as part of HTTP tunnelling tests.
1722
1761
self._captureVar('BZR_NO_SMART_VFS', None)
1723
1762
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1724
self.http_server = self.get_readonly_server()
1726
1764
def create_transport_readonly_server(self):
1727
server = http_utils.HTTPServerWithSmarts(
1765
return http_utils.HTTPServerWithSmarts(
1728
1766
protocol_version=self._protocol_version)
1729
server._url_protocol = self._url_protocol
1732
1768
def test_open_bzrdir(self):
1733
1769
branch = self.make_branch('relpath')
1734
url = self.http_server.get_url() + 'relpath'
1770
http_server = self.get_readonly_server()
1771
url = http_server.get_url() + 'relpath'
1735
1772
bd = bzrdir.BzrDir.open(url)
1736
self.addCleanup(bd.transport.disconnect)
1737
1773
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1739
1775
def test_bulk_data(self):
1741
1777
# The 'readv' command in the smart protocol both sends and receives
1742
1778
# bulk data, so we use that.
1743
1779
self.build_tree(['data-file'])
1744
http_transport = transport.get_transport(self.http_server.get_url())
1780
http_server = self.get_readonly_server()
1781
http_transport = self._transport(http_server.get_url())
1745
1782
medium = http_transport.get_smart_medium()
1746
1783
# Since we provide the medium, the url below will be mostly ignored
1747
1784
# during the test, as long as the path is '/'.
1755
1792
post_body = 'hello\n'
1756
1793
expected_reply_body = 'ok\x012\n'
1758
http_transport = transport.get_transport(self.http_server.get_url())
1795
http_server = self.get_readonly_server()
1796
http_transport = self._transport(http_server.get_url())
1759
1797
medium = http_transport.get_smart_medium()
1760
1798
response = medium.send_http_smart_request(post_body)
1761
1799
reply_body = response.read()
1762
1800
self.assertEqual(expected_reply_body, reply_body)
1764
1802
def test_smart_http_server_post_request_handler(self):
1765
httpd = self.http_server.server
1803
httpd = self.get_readonly_server()._get_httpd()
1767
1805
socket = SampleSocket(
1768
1806
'POST /.bzr/smart %s \r\n' % self._protocol_version
1801
1839
def test_probe_smart_server(self):
1802
1840
"""Test error handling against server refusing smart requests."""
1803
t = self.get_readonly_transport()
1841
server = self.get_readonly_server()
1842
t = self._transport(server.get_url())
1804
1843
# No need to build a valid smart request here, the server will not even
1805
1844
# try to interpret it.
1806
1845
self.assertRaises(errors.SmartProtocolError,
1807
1846
t.get_smart_medium().send_http_smart_request,
1811
1849
class Test_redirected_to(tests.TestCase):
1813
1851
def test_redirected_to_subdir(self):
1936
1974
# We override at class level because constructors may propagate the
1937
1975
# bound method and render instance overriding ineffective (an
1938
1976
# alternative would be to define a specific ui factory instead...)
1939
self.overrideAttr(self._transport, '_report_activity', report_activity)
1940
self.addCleanup(self.server.stop_server)
1977
self.orig_report_activity = self._transport._report_activity
1978
self._transport._report_activity = report_activity
1981
self._transport._report_activity = self.orig_report_activity
1982
self.server.stop_server()
1983
tests.TestCase.tearDown(self)
1942
1985
def get_transport(self):
1943
t = self._transport(self.server.get_url())
1944
# FIXME: Needs cleanup -- vila 20100611
1986
return self._transport(self.server.get_url())
1947
1988
def assertActivitiesMatch(self):
1948
1989
self.assertEqual(self.server.bytes_read,
2054
2095
t = self.get_transport()
2055
2096
# We must send a single line of body bytes, see
2056
# PredefinedRequestHandler._handle_one_request
2097
# PredefinedRequestHandler.handle_one_request
2057
2098
code, f = t._post('abc def end-of-body\n')
2058
2099
self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2059
2100
self.assertActivitiesMatch()
2062
2103
class TestActivity(tests.TestCase, TestActivityMixin):
2064
2105
def setUp(self):
2065
TestActivityMixin.setUp(self)
2106
tests.TestCase.setUp(self)
2107
self.server = self._activity_server(self._protocol_version)
2108
self.server.start_server()
2109
self.activities = {}
2110
def report_activity(t, bytes, direction):
2111
count = self.activities.get(direction, 0)
2113
self.activities[direction] = count
2115
# We override at class level because constructors may propagate the
2116
# bound method and render instance overriding ineffective (an
2117
# alternative would be to define a specific ui factory instead...)
2118
self.orig_report_activity = self._transport._report_activity
2119
self._transport._report_activity = report_activity
2122
self._transport._report_activity = self.orig_report_activity
2123
self.server.stop_server()
2124
tests.TestCase.tearDown(self)
2068
2127
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2070
# Unlike TestActivity, we are really testing ReportingFileSocket and
2071
# ReportingSocket, so we don't need all the parametrization. Since
2072
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2073
# test them through their use by the transport than directly (that's a
2074
# bit less clean but far more simpler and effective).
2075
_activity_server = ActivityHTTPServer
2076
_protocol_version = 'HTTP/1.1'
2078
2129
def setUp(self):
2079
self._transport =_urllib.HttpTransport_urllib
2080
TestActivityMixin.setUp(self)
2130
tests.TestCase.setUp(self)
2131
# Unlike TestActivity, we are really testing ReportingFileSocket and
2132
# ReportingSocket, so we don't need all the parametrization. Since
2133
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2134
# test them through their use by the transport than directly (that's a
2135
# bit less clean but far more simpler and effective).
2136
self.server = ActivityHTTPServer('HTTP/1.1')
2137
self._transport=_urllib.HttpTransport_urllib
2139
self.server.start_server()
2141
# We override at class level because constructors may propagate the
2142
# bound method and render instance overriding ineffective (an
2143
# alternative would be to define a specific ui factory instead...)
2144
self.orig_report_activity = self._transport._report_activity
2145
self._transport._report_activity = None
2148
self._transport._report_activity = self.orig_report_activity
2149
self.server.stop_server()
2150
tests.TestCase.tearDown(self)
2082
2152
def assertActivitiesMatch(self):
2083
2153
# Nothing to check here
2093
2163
_auth_server = http_utils.HTTPBasicAuthServer
2094
2164
_transport = _urllib.HttpTransport_urllib
2166
def create_transport_readonly_server(self):
2167
return self._auth_server()
2169
def create_transport_secondary_server(self):
2170
"""Create the secondary server redirecting to the primary server"""
2171
new = self.get_readonly_server()
2173
redirecting = http_utils.HTTPServerRedirecting()
2174
redirecting.redirect_to(new.host, new.port)
2096
2177
def setUp(self):
2097
2178
super(TestAuthOnRedirected, self).setUp()
2098
2179
self.build_tree_contents([('a','a'),
2103
2184
self.new_server.port)
2104
2185
self.old_server.redirections = [
2105
2186
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2106
self.old_transport = self.get_old_transport()
2187
self.old_transport = self._transport(self.old_server.get_url())
2107
2188
self.new_server.add_user('joe', 'foo')
2108
cleanup_http_redirection_connections(self)
2110
def create_transport_readonly_server(self):
2111
server = self._auth_server(protocol_version=self._protocol_version)
2112
server._url_protocol = self._url_protocol
2190
def get_a(self, transport):
2191
return transport.get('a')
2118
2193
def test_auth_on_redirected_via_do_catching_redirections(self):
2119
2194
self.redirections = 0
2121
def redirected(t, exception, redirection_notice):
2196
def redirected(transport, exception, redirection_notice):
2122
2197
self.redirections += 1
2123
redirected_t = t._redirected_to(exception.source, exception.target)
2124
self.addCleanup(redirected_t.disconnect)
2198
dir, file = urlutils.split(exception.target)
2199
return self._transport(dir)
2127
2201
stdout = tests.StringIOWrapper()
2128
2202
stderr = tests.StringIOWrapper()
2149
2223
self.new_server.port)
2150
2224
self.old_server.redirections = [
2151
2225
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2152
self.assertEqual('redirected once', t._perform(req).read())
2226
self.assertEqual('redirected once',t._perform(req).read())
2153
2227
# stdin should be empty
2154
2228
self.assertEqual('', ui.ui_factory.stdin.readline())
2155
2229
# stdout should be empty, stderr will contains the prompts