66
66
from bzrlib.transport.http._pycurl import PyCurlTransport
69
def load_tests(standard_tests, module, loader):
70
"""Multiply tests for http clients and protocol versions."""
71
result = loader.suiteClass()
73
# one for each transport implementation
74
t_tests, remaining_tests = tests.split_suite_by_condition(
75
standard_tests, tests.condition_isinstance((
76
TestHttpTransportRegistration,
77
TestHttpTransportUrls,
69
load_tests = load_tests_apply_scenarios
72
def vary_by_http_client_implementation():
73
"""Test the two libraries we can use, pycurl and urllib."""
80
74
transport_scenarios = [
81
75
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
82
76
_server=http_server.HttpServer_urllib,
83
_qualified_prefix='http+urllib',)),
77
_url_protocol='http+urllib',)),
85
79
if features.pycurl.available():
86
80
transport_scenarios.append(
87
81
('pycurl', dict(_transport=PyCurlTransport,
88
82
_server=http_server.HttpServer_PyCurl,
89
_qualified_prefix='http+pycurl',)))
90
tests.multiply_tests(t_tests, transport_scenarios, result)
92
# each implementation tested with each HTTP version
93
tp_tests, remaining_tests = tests.split_suite_by_condition(
94
remaining_tests, tests.condition_isinstance((
95
SmartHTTPTunnellingTest,
96
TestDoCatchRedirections,
99
TestHTTPSilentRedirections,
100
TestLimitedRangeRequestServer,
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')),
110
tp_scenarios = tests.multiply_scenarios(transport_scenarios,
112
tests.multiply_tests(tp_tests, tp_scenarios, result)
114
# proxy auth: each auth scheme on all http versions on all implementations.
115
tppa_tests, remaining_tests = tests.split_suite_by_condition(
116
remaining_tests, tests.condition_isinstance((
119
proxy_auth_scheme_scenarios = [
120
('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
121
('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
123
dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
83
_url_protocol='http+pycurl',)))
84
return transport_scenarios
87
def vary_by_http_protocol_version():
88
"""Test on http/1.0 and 1.1"""
90
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
91
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
125
tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
126
proxy_auth_scheme_scenarios)
127
tests.multiply_tests(tppa_tests, tppa_scenarios, result)
129
# auth: each auth scheme on all http versions on all implementations.
130
tpa_tests, remaining_tests = tests.split_suite_by_condition(
131
remaining_tests, tests.condition_isinstance((
134
auth_scheme_scenarios = [
95
def vary_by_http_auth_scheme():
135
97
('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
136
98
('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
138
dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
140
tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
141
auth_scheme_scenarios)
142
tests.multiply_tests(tpa_tests, tpa_scenarios, result)
144
# activity: on all http[s] versions on all implementations
145
tpact_tests, remaining_tests = tests.split_suite_by_condition(
146
remaining_tests, tests.condition_isinstance((
100
dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
102
# Add some attributes common to all scenarios
103
for scenario_id, scenario_dict in scenarios:
104
scenario_dict.update(_auth_header='Authorization',
105
_username_prompt_prefix='',
106
_password_prompt_prefix='')
110
def vary_by_http_proxy_auth_scheme():
112
('proxy-basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
113
('proxy-digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
114
('proxy-basicdigest',
115
dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
117
# Add some attributes common to all scenarios
118
for scenario_id, scenario_dict in scenarios:
119
scenario_dict.update(_auth_header='Proxy-Authorization',
120
_username_prompt_prefix='Proxy ',
121
_password_prompt_prefix='Proxy ')
125
def vary_by_http_activity():
149
126
activity_scenarios = [
150
127
('urllib,http', dict(_activity_server=ActivityHTTPServer,
151
_transport=_urllib.HttpTransport_urllib,)),
128
_transport=_urllib.HttpTransport_urllib,)),
153
if tests.HTTPSServerFeature.available():
130
if features.pycurl.available():
131
activity_scenarios.append(
132
('pycurl,http', dict(_activity_server=ActivityHTTPServer,
133
_transport=PyCurlTransport,)),)
134
if features.HTTPSServerFeature.available():
135
# FIXME: Until we have a better way to handle self-signed certificates
136
# (like allowing them in a test specific authentication.conf for
137
# example), we need some specialized pycurl/urllib transport for tests.
139
from bzrlib.tests import (
142
class HTTPS_urllib_transport(_urllib.HttpTransport_urllib):
144
def __init__(self, base, _from_transport=None):
145
super(HTTPS_urllib_transport, self).__init__(
146
base, _from_transport=_from_transport,
147
ca_certs=ssl_certs.build_path('ca.crt'))
154
149
activity_scenarios.append(
155
150
('urllib,https', dict(_activity_server=ActivityHTTPSServer,
156
_transport=_urllib.HttpTransport_urllib,)),)
157
if features.pycurl.available():
158
activity_scenarios.append(
159
('pycurl,http', dict(_activity_server=ActivityHTTPServer,
160
_transport=PyCurlTransport,)),)
161
if tests.HTTPSServerFeature.available():
162
from bzrlib.tests import (
165
# FIXME: Until we have a better way to handle self-signed
166
# certificates (like allowing them in a test specific
167
# authentication.conf for example), we need some specialized pycurl
168
# transport for tests.
151
_transport=HTTPS_urllib_transport,)),)
152
if features.pycurl.available():
169
153
class HTTPS_pycurl_transport(PyCurlTransport):
171
155
def __init__(self, base, _from_transport=None):
296
275
self.assertEqual('realm="Thou should not pass"', remainder)
278
class TestHTTPRangeParsing(tests.TestCase):
281
super(TestHTTPRangeParsing, self).setUp()
282
# We focus on range parsing here and ignore everything else
283
class RequestHandler(http_server.TestingHTTPRequestHandler):
284
def setup(self): pass
285
def handle(self): pass
286
def finish(self): pass
288
self.req_handler = RequestHandler(None, None, None)
290
def assertRanges(self, ranges, header, file_size):
291
self.assertEqual(ranges,
292
self.req_handler._parse_ranges(header, file_size))
294
def test_simple_range(self):
295
self.assertRanges([(0,2)], 'bytes=0-2', 12)
298
self.assertRanges([(8, 11)], 'bytes=-4', 12)
300
def test_tail_bigger_than_file(self):
301
self.assertRanges([(0, 11)], 'bytes=-99', 12)
303
def test_range_without_end(self):
304
self.assertRanges([(4, 11)], 'bytes=4-', 12)
306
def test_invalid_ranges(self):
307
self.assertRanges(None, 'bytes=12-22', 12)
308
self.assertRanges(None, 'bytes=1-3,12-22', 12)
309
self.assertRanges(None, 'bytes=-', 12)
299
312
class TestHTTPServer(tests.TestCase):
300
313
"""Test the HTTP servers implementations."""
380
384
_transport = property(_get_pycurl_maybe)
383
class TestHttpUrls(tests.TestCase):
385
# TODO: This should be moved to authorization tests once they
388
def test_url_parsing(self):
390
url = http.extract_auth('http://example.com', f)
391
self.assertEqual('http://example.com', url)
392
self.assertEqual(0, len(f.credentials))
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)
396
self.assertEqual(1, len(f.credentials))
397
self.assertEqual([None, 'example.com', 'user', 'pass'],
401
387
class TestHttpTransportUrls(tests.TestCase):
402
388
"""Test the http urls."""
390
scenarios = vary_by_http_client_implementation()
404
392
def test_abs_url(self):
405
393
"""Construction of absolute http URLs"""
406
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
394
t = self._transport('http://example.com/bzr/bzr.dev/')
407
395
eq = self.assertEqualDiff
408
eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
409
eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
410
eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
396
eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
397
eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
398
eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
411
399
eq(t.abspath('.bzr/1//2/./3'),
412
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
400
'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
414
402
def test_invalid_http_urls(self):
415
403
"""Trap invalid construction of urls"""
416
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
404
self._transport('http://example.com/bzr/bzr.dev/')
417
405
self.assertRaises(errors.InvalidURL,
419
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
407
'http://http://example.com/bzr/bzr.dev/')
421
409
def test_http_root_urls(self):
422
410
"""Construction of URLs from server root"""
423
t = self._transport('http://bzr.ozlabs.org/')
411
t = self._transport('http://example.com/')
424
412
eq = self.assertEqualDiff
425
413
eq(t.abspath('.bzr/tree-version'),
426
'http://bzr.ozlabs.org/.bzr/tree-version')
414
'http://example.com/.bzr/tree-version')
428
416
def test_http_impl_urls(self):
429
417
"""There are servers which ask for particular clients to connect"""
525
518
class TestHttpTransportRegistration(tests.TestCase):
526
519
"""Test registrations of various http implementations"""
521
scenarios = vary_by_http_client_implementation()
528
523
def test_http_registered(self):
529
t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
524
t = transport.get_transport_from_url(
525
'%s://foo.com/' % self._url_protocol)
530
526
self.assertIsInstance(t, transport.Transport)
531
527
self.assertIsInstance(t, self._transport)
534
530
class TestPost(tests.TestCase):
532
scenarios = multiply_scenarios(
533
vary_by_http_client_implementation(),
534
vary_by_http_protocol_version(),
536
537
def test_post_body_is_received(self):
537
538
server = RecordingServer(expect_body_tail='end-of-body',
538
scheme=self._qualified_prefix)
539
scheme=self._url_protocol)
539
540
self.start_server(server)
540
541
url = server.get_url()
541
http_transport = self._transport(url)
542
# FIXME: needs a cleanup -- vila 20100611
543
http_transport = transport.get_transport_from_url(url)
542
544
code, response = http_transport._post('abc def end-of-body')
544
546
server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
545
547
self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
548
self.assertTrue('content-type: application/octet-stream\r'
549
in server.received_bytes.lower())
546
550
# The transport should not be assuming that the server can accept
547
551
# chunked encoding the first time it connects, because HTTP/1.1, so we
548
552
# check for the literal string.
1043
1052
self.assertEqual('single', t._range_hint)
1055
class TruncatedBeforeBoundaryRequestHandler(
1056
http_server.TestingHTTPRequestHandler):
1057
"""Truncation before a boundary, like in bug 198646"""
1059
_truncated_ranges = 1
1061
def get_multiple_ranges(self, file, file_size, ranges):
1062
self.send_response(206)
1063
self.send_header('Accept-Ranges', 'bytes')
1065
self.send_header('Content-Type',
1066
'multipart/byteranges; boundary=%s' % boundary)
1067
boundary_line = '--%s\r\n' % boundary
1068
# Calculate the Content-Length
1070
for (start, end) in ranges:
1071
content_length += len(boundary_line)
1072
content_length += self._header_line_length(
1073
'Content-type', 'application/octet-stream')
1074
content_length += self._header_line_length(
1075
'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
1076
content_length += len('\r\n') # end headers
1077
content_length += end - start # + 1
1078
content_length += len(boundary_line)
1079
self.send_header('Content-length', content_length)
1082
# Send the multipart body
1084
for (start, end) in ranges:
1085
if cur + self._truncated_ranges >= len(ranges):
1086
# Abruptly ends the response and close the connection
1087
self.close_connection = 1
1089
self.wfile.write(boundary_line)
1090
self.send_header('Content-type', 'application/octet-stream')
1091
self.send_header('Content-Range', 'bytes %d-%d/%d'
1092
% (start, end, file_size))
1094
self.send_range_content(file, start, end - start + 1)
1097
self.wfile.write(boundary_line)
1100
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1101
"""Tests the case of bug 198646, disconnecting before a boundary."""
1103
_req_handler_class = TruncatedBeforeBoundaryRequestHandler
1106
super(TestTruncatedBeforeBoundary, self).setUp()
1107
self.build_tree_contents([('a', '0123456789')],)
1109
def test_readv_with_short_reads(self):
1110
server = self.get_readonly_server()
1111
t = self.get_readonly_transport()
1112
# Force separate ranges for each offset
1113
t._bytes_to_read_before_seek = 0
1114
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1115
self.assertEqual((0, '0'), ireadv.next())
1116
self.assertEqual((2, '2'), ireadv.next())
1117
self.assertEqual((4, '45'), ireadv.next())
1118
self.assertEqual((9, '9'), ireadv.next())
1045
1121
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1046
1122
"""Errors out when range specifiers exceed the limit"""
1114
1192
Only the urllib implementation is tested here.
1118
tests.TestCase.setUp(self)
1123
tests.TestCase.tearDown(self)
1125
def _install_env(self, env):
1126
for name, value in env.iteritems():
1127
self._old_env[name] = osutils.set_or_unset_env(name, value)
1129
def _restore_env(self):
1130
for name, value in self._old_env.iteritems():
1131
osutils.set_or_unset_env(name, value)
1133
1195
def _proxied_request(self):
1134
1196
handler = _urllib2_wrappers.ProxyHandler()
1135
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1197
request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1136
1198
handler.set_proxy(request, 'http')
1201
def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1202
handler = _urllib2_wrappers.ProxyHandler()
1203
self.assertEqual(expected,
1204
handler.evaluate_proxy_bypass(host, no_proxy))
1139
1206
def test_empty_user(self):
1140
self._install_env({'http_proxy': 'http://bar.com'})
1207
self.overrideEnv('http_proxy', 'http://bar.com')
1208
request = self._proxied_request()
1209
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1211
def test_user_with_at(self):
1212
self.overrideEnv('http_proxy',
1213
'http://username@domain:password@proxy_host:1234')
1141
1214
request = self._proxied_request()
1142
1215
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1144
1217
def test_invalid_proxy(self):
1145
1218
"""A proxy env variable without scheme"""
1146
self._install_env({'http_proxy': 'host:1234'})
1219
self.overrideEnv('http_proxy', 'host:1234')
1147
1220
self.assertRaises(errors.InvalidURL, self._proxied_request)
1222
def test_evaluate_proxy_bypass_true(self):
1223
"""The host is not proxied"""
1224
self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1225
self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1227
def test_evaluate_proxy_bypass_false(self):
1228
"""The host is proxied"""
1229
self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1231
def test_evaluate_proxy_bypass_unknown(self):
1232
"""The host is not explicitly proxied"""
1233
self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1234
self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1236
def test_evaluate_proxy_bypass_empty_entries(self):
1237
"""Ignore empty entries"""
1238
self.assertEvaluateProxyBypass(None, 'example.com', '')
1239
self.assertEvaluateProxyBypass(None, 'example.com', ',')
1240
self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1150
1243
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1151
1244
"""Tests proxy server.
1156
1249
to the file names).
1252
scenarios = multiply_scenarios(
1253
vary_by_http_client_implementation(),
1254
vary_by_http_protocol_version(),
1159
1257
# FIXME: We don't have an https server available, so we don't
1160
# test https connections.
1258
# test https connections. --vila toolongago
1162
1260
def setUp(self):
1163
1261
super(TestProxyHttpServer, self).setUp()
1262
self.transport_secondary_server = http_utils.ProxyServer
1164
1263
self.build_tree_contents([('foo', 'contents of foo\n'),
1165
1264
('foo-proxied', 'proxied contents of foo\n')])
1166
1265
# Let's setup some attributes for tests
1167
self.server = self.get_readonly_server()
1168
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1266
server = self.get_readonly_server()
1267
self.server_host_port = '%s:%d' % (server.host, server.port)
1169
1268
if self._testing_pycurl():
1170
1269
# Oh my ! pycurl does not check for the port as part of
1171
1270
# no_proxy :-( So we just test the host part
1172
self.no_proxy_host = self.server.host
1271
self.no_proxy_host = server.host
1174
self.no_proxy_host = self.proxy_address
1273
self.no_proxy_host = self.server_host_port
1175
1274
# The secondary server is the proxy
1176
self.proxy = self.get_secondary_server()
1177
self.proxy_url = self.proxy.get_url()
1275
self.proxy_url = self.get_secondary_url()
1180
1277
def _testing_pycurl(self):
1181
1278
# TODO: This is duplicated for lots of the classes in this file
1182
1279
return (features.pycurl.available()
1183
1280
and self._transport == PyCurlTransport)
1185
def create_transport_secondary_server(self):
1186
"""Creates an http server that will serve files with
1187
'-proxied' appended to their names.
1189
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1191
def _install_env(self, env):
1192
for name, value in env.iteritems():
1193
self._old_env[name] = osutils.set_or_unset_env(name, value)
1195
def _restore_env(self):
1196
for name, value in self._old_env.iteritems():
1197
osutils.set_or_unset_env(name, value)
1199
def proxied_in_env(self, env):
1200
self._install_env(env)
1201
url = self.server.get_url()
1202
t = self._transport(url)
1204
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1208
def not_proxied_in_env(self, env):
1209
self._install_env(env)
1210
url = self.server.get_url()
1211
t = self._transport(url)
1213
self.assertEqual('contents of foo\n', t.get('foo').read())
1282
def assertProxied(self):
1283
t = self.get_readonly_transport()
1284
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1286
def assertNotProxied(self):
1287
t = self.get_readonly_transport()
1288
self.assertEqual('contents of foo\n', t.get('foo').read())
1217
1290
def test_http_proxy(self):
1218
self.proxied_in_env({'http_proxy': self.proxy_url})
1291
self.overrideEnv('http_proxy', self.proxy_url)
1292
self.assertProxied()
1220
1294
def test_HTTP_PROXY(self):
1221
1295
if self._testing_pycurl():
1224
1298
# about. Should we ?)
1225
1299
raise tests.TestNotApplicable(
1226
1300
'pycurl does not check HTTP_PROXY for security reasons')
1227
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1301
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1302
self.assertProxied()
1229
1304
def test_all_proxy(self):
1230
self.proxied_in_env({'all_proxy': self.proxy_url})
1305
self.overrideEnv('all_proxy', self.proxy_url)
1306
self.assertProxied()
1232
1308
def test_ALL_PROXY(self):
1233
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1309
self.overrideEnv('ALL_PROXY', self.proxy_url)
1310
self.assertProxied()
1235
1312
def test_http_proxy_with_no_proxy(self):
1236
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1237
'no_proxy': self.no_proxy_host})
1313
self.overrideEnv('no_proxy', self.no_proxy_host)
1314
self.overrideEnv('http_proxy', self.proxy_url)
1315
self.assertNotProxied()
1239
1317
def test_HTTP_PROXY_with_NO_PROXY(self):
1240
1318
if self._testing_pycurl():
1241
1319
raise tests.TestNotApplicable(
1242
1320
'pycurl does not check HTTP_PROXY for security reasons')
1243
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1244
'NO_PROXY': self.no_proxy_host})
1321
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1322
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1323
self.assertNotProxied()
1246
1325
def test_all_proxy_with_no_proxy(self):
1247
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1248
'no_proxy': self.no_proxy_host})
1326
self.overrideEnv('no_proxy', self.no_proxy_host)
1327
self.overrideEnv('all_proxy', self.proxy_url)
1328
self.assertNotProxied()
1250
1330
def test_ALL_PROXY_with_NO_PROXY(self):
1251
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1252
'NO_PROXY': self.no_proxy_host})
1331
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1332
self.overrideEnv('ALL_PROXY', self.proxy_url)
1333
self.assertNotProxied()
1254
1335
def test_http_proxy_without_scheme(self):
1336
self.overrideEnv('http_proxy', self.server_host_port)
1255
1337
if self._testing_pycurl():
1256
1338
# pycurl *ignores* invalid proxy env variables. If that ever change
1257
1339
# in the future, this test will fail indicating that pycurl do not
1258
1340
# ignore anymore such variables.
1259
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1341
self.assertNotProxied()
1261
self.assertRaises(errors.InvalidURL,
1262
self.proxied_in_env,
1263
{'http_proxy': self.proxy_address})
1343
self.assertRaises(errors.InvalidURL, self.assertProxied)
1266
1346
class TestRanges(http_utils.TestCaseWithWebserver):
1267
1347
"""Test the Range header in GET methods."""
1349
scenarios = multiply_scenarios(
1350
vary_by_http_client_implementation(),
1351
vary_by_http_protocol_version(),
1269
1354
def setUp(self):
1270
http_utils.TestCaseWithWebserver.setUp(self)
1355
super(TestRanges, self).setUp()
1271
1356
self.build_tree_contents([('a', '0123456789')],)
1272
server = self.get_readonly_server()
1273
self.transport = self._transport(server.get_url())
1275
1358
def create_transport_readonly_server(self):
1276
1359
return http_server.HttpServer(protocol_version=self._protocol_version)
1278
1361
def _file_contents(self, relpath, ranges):
1362
t = self.get_readonly_transport()
1279
1363
offsets = [ (start, end - start + 1) for start, end in ranges]
1280
coalesce = self.transport._coalesce_offsets
1364
coalesce = t._coalesce_offsets
1281
1365
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1282
code, data = self.transport._get(relpath, coalesced)
1366
code, data = t._get(relpath, coalesced)
1283
1367
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1284
1368
for start, end in ranges:
1285
1369
data.seek(start)
1286
1370
yield data.read(end - start + 1)
1288
1372
def _file_tail(self, relpath, tail_amount):
1289
code, data = self.transport._get(relpath, [], tail_amount)
1373
t = self.get_readonly_transport()
1374
code, data = t._get(relpath, [], tail_amount)
1290
1375
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1291
1376
data.seek(-tail_amount, 2)
1292
1377
return data.read(tail_amount)
1429
1518
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1430
1519
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1432
self.assertEqual('redirected 5 times',t._perform(req).read())
1521
self.assertEqual('redirected 5 times', t._perform(req).read())
1435
1524
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1436
1525
"""Test transport.do_catching_redirections."""
1527
scenarios = multiply_scenarios(
1528
vary_by_http_client_implementation(),
1529
vary_by_http_protocol_version(),
1438
1532
def setUp(self):
1439
1533
super(TestDoCatchRedirections, self).setUp()
1440
1534
self.build_tree_contents([('a', '0123456789'),],)
1442
self.old_transport = self._transport(self.old_server.get_url())
1444
def get_a(self, transport):
1445
return transport.get('a')
1535
cleanup_http_redirection_connections(self)
1537
self.old_transport = self.get_old_transport()
1447
1542
def test_no_redirection(self):
1448
t = self._transport(self.new_server.get_url())
1543
t = self.get_new_transport()
1450
1545
# We use None for redirected so that we fail if redirected
1451
1546
self.assertEqual('0123456789',
1478
1573
self.get_a, self.old_transport, redirected)
1576
def _setup_authentication_config(**kwargs):
1577
conf = config.AuthenticationConfig()
1578
conf._get_config().update({'httptest': kwargs})
1582
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1583
"""Unit tests for glue by which urllib2 asks us for authentication"""
1585
def test_get_user_password_without_port(self):
1586
"""We cope if urllib2 doesn't tell us the port.
1588
See https://bugs.launchpad.net/bzr/+bug/654684
1592
_setup_authentication_config(scheme='http', host='localhost',
1593
user=user, password=password)
1594
handler = _urllib2_wrappers.HTTPAuthHandler()
1595
got_pass = handler.get_user_password(dict(
1602
self.assertEqual((user, password), got_pass)
1481
1605
class TestAuth(http_utils.TestCaseWithWebserver):
1482
1606
"""Test authentication scheme"""
1484
_auth_header = 'Authorization'
1485
_password_prompt_prefix = ''
1486
_username_prompt_prefix = ''
1608
scenarios = multiply_scenarios(
1609
vary_by_http_client_implementation(),
1610
vary_by_http_protocol_version(),
1611
vary_by_http_auth_scheme(),
1490
1614
def setUp(self):
1491
1615
super(TestAuth, self).setUp()
1642
1767
# Only one 'Authentication Required' error should occur
1643
1768
self.assertEqual(1, self.server.auth_required_errors)
1645
def test_user_from_auth_conf(self):
1646
if self._testing_pycurl():
1647
raise tests.TestNotApplicable(
1648
'pycurl does not support authentication.conf')
1651
self.server.add_user(user, password)
1652
# Create a minimal config file with the right password
1653
conf = config.AuthenticationConfig()
1654
conf._get_config().update(
1655
{'httptest': {'scheme': 'http', 'port': self.server.port,
1656
'user': user, 'password': password}})
1658
t = self.get_user_transport(None, None)
1659
# Issue a request to the server to connect
1660
self.assertEqual('contents of a\n', t.get('a').read())
1661
# Only one 'Authentication Required' error should occur
1662
self.assertEqual(1, self.server.auth_required_errors)
1664
1770
def test_changing_nonce(self):
1665
1771
if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1666
1772
http_utils.ProxyDigestAuthServer):
1667
1773
raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
1668
1774
if self._testing_pycurl():
1669
raise tests.KnownFailure(
1670
1776
'pycurl does not handle a nonce change')
1671
1777
self.server.add_user('joe', 'foo')
1672
1778
t = self.get_user_transport('joe', 'foo')
1682
1788
# initial 'who are you' and a second 'who are you' with the new nonce)
1683
1789
self.assertEqual(2, self.server.auth_required_errors)
1791
def test_user_from_auth_conf(self):
1792
if self._testing_pycurl():
1793
raise tests.TestNotApplicable(
1794
'pycurl does not support authentication.conf')
1797
self.server.add_user(user, password)
1798
_setup_authentication_config(scheme='http', port=self.server.port,
1799
user=user, password=password)
1800
t = self.get_user_transport(None, None)
1801
# Issue a request to the server to connect
1802
self.assertEqual('contents of a\n', t.get('a').read())
1803
# Only one 'Authentication Required' error should occur
1804
self.assertEqual(1, self.server.auth_required_errors)
1806
def test_no_credential_leaks_in_log(self):
1807
self.overrideAttr(debug, 'debug_flags', set(['http']))
1809
password = 'very-sensitive-password'
1810
self.server.add_user(user, password)
1811
t = self.get_user_transport(user, password)
1812
# Capture the debug calls to mutter
1815
lines = args[0] % args[1:]
1816
# Some calls output multiple lines, just split them now since we
1817
# care about a single one later.
1818
self.mutters.extend(lines.splitlines())
1819
self.overrideAttr(trace, 'mutter', mutter)
1820
# Issue a request to the server to connect
1821
self.assertEqual(True, t.has('a'))
1822
# Only one 'Authentication Required' error should occur
1823
self.assertEqual(1, self.server.auth_required_errors)
1824
# Since the authentification succeeded, there should be a corresponding
1826
sent_auth_headers = [line for line in self.mutters
1827
if line.startswith('> %s' % (self._auth_header,))]
1828
self.assertLength(1, sent_auth_headers)
1829
self.assertStartsWith(sent_auth_headers[0],
1830
'> %s: <masked>' % (self._auth_header,))
1687
1833
class TestProxyAuth(TestAuth):
1688
"""Test proxy authentication schemes."""
1690
_auth_header = 'Proxy-authorization'
1691
_password_prompt_prefix = 'Proxy '
1692
_username_prompt_prefix = 'Proxy '
1834
"""Test proxy authentication schemes.
1836
This inherits from TestAuth to tweak the setUp and filter some failing
1840
scenarios = multiply_scenarios(
1841
vary_by_http_client_implementation(),
1842
vary_by_http_protocol_version(),
1843
vary_by_http_proxy_auth_scheme(),
1694
1846
def setUp(self):
1695
1847
super(TestProxyAuth, self).setUp()
1697
self.addCleanup(self._restore_env)
1698
1848
# Override the contents to avoid false positives
1699
1849
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1700
1850
('b', 'not proxied contents of b\n'),
1748
1891
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1893
scenarios = multiply_scenarios(
1894
vary_by_http_client_implementation(),
1895
vary_by_http_protocol_version(),
1750
1898
def setUp(self):
1751
1899
super(SmartHTTPTunnellingTest, self).setUp()
1752
1900
# We use the VFS layer as part of HTTP tunnelling tests.
1753
self._captureVar('BZR_NO_SMART_VFS', None)
1901
self.overrideEnv('BZR_NO_SMART_VFS', None)
1754
1902
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1903
self.http_server = self.get_readonly_server()
1756
1905
def create_transport_readonly_server(self):
1757
return http_utils.HTTPServerWithSmarts(
1906
server = http_utils.HTTPServerWithSmarts(
1758
1907
protocol_version=self._protocol_version)
1908
server._url_protocol = self._url_protocol
1760
def test_open_bzrdir(self):
1911
def test_open_controldir(self):
1761
1912
branch = self.make_branch('relpath')
1762
http_server = self.get_readonly_server()
1763
url = http_server.get_url() + 'relpath'
1764
bd = bzrdir.BzrDir.open(url)
1913
url = self.http_server.get_url() + 'relpath'
1914
bd = controldir.ControlDir.open(url)
1915
self.addCleanup(bd.transport.disconnect)
1765
1916
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1767
1918
def test_bulk_data(self):
1863
2017
r = t._redirected_to('http://www.example.com/foo',
1864
2018
'http://foo.example.com/foo/subdir')
1865
2019
self.assertIsInstance(r, type(t))
2020
self.assertEqual('http://foo.example.com/foo/subdir/',
1867
2023
def test_redirected_to_same_host_sibling_protocol(self):
1868
2024
t = self._transport('http://www.example.com/foo')
1869
2025
r = t._redirected_to('http://www.example.com/foo',
1870
2026
'https://www.example.com/foo')
1871
2027
self.assertIsInstance(r, type(t))
2028
self.assertEqual('https://www.example.com/foo/',
1873
2031
def test_redirected_to_same_host_different_protocol(self):
1874
2032
t = self._transport('http://www.example.com/foo')
1875
2033
r = t._redirected_to('http://www.example.com/foo',
1876
2034
'ftp://www.example.com/foo')
1877
self.assertNotEquals(type(r), type(t))
2035
self.assertNotEqual(type(r), type(t))
2036
self.assertEqual('ftp://www.example.com/foo/', r.external_url())
2038
def test_redirected_to_same_host_specific_implementation(self):
2039
t = self._transport('http://www.example.com/foo')
2040
r = t._redirected_to('http://www.example.com/foo',
2041
'https+urllib://www.example.com/foo')
2042
self.assertEqual('https://www.example.com/foo/', r.external_url())
1879
2044
def test_redirected_to_different_host_same_user(self):
1880
2045
t = self._transport('http://joe@www.example.com/foo')
1881
2046
r = t._redirected_to('http://www.example.com/foo',
1882
2047
'https://foo.example.com/foo')
1883
2048
self.assertIsInstance(r, type(t))
1884
self.assertEqual(t._user, r._user)
2049
self.assertEqual(t._parsed_url.user, r._parsed_url.user)
2050
self.assertEqual('https://joe@foo.example.com/foo/', r.external_url())
1887
2053
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1956
2122
def setUp(self):
1957
tests.TestCase.setUp(self)
1958
2123
self.server = self._activity_server(self._protocol_version)
1959
2124
self.server.start_server()
1960
self.activities = {}
2125
self.addCleanup(self.server.stop_server)
2126
_activities = {} # Don't close over self and create a cycle
1961
2127
def report_activity(t, bytes, direction):
1962
count = self.activities.get(direction, 0)
2128
count = _activities.get(direction, 0)
1964
self.activities[direction] = count
2130
_activities[direction] = count
2131
self.activities = _activities
1966
2132
# We override at class level because constructors may propagate the
1967
2133
# bound method and render instance overriding ineffective (an
1968
2134
# alternative would be to define a specific ui factory instead...)
1969
self.orig_report_activity = self._transport._report_activity
1970
self._transport._report_activity = report_activity
1973
self._transport._report_activity = self.orig_report_activity
1974
self.server.stop_server()
1975
tests.TestCase.tearDown(self)
2135
self.overrideAttr(self._transport, '_report_activity', report_activity)
1977
2137
def get_transport(self):
1978
return self._transport(self.server.get_url())
2138
t = self._transport(self.server.get_url())
2139
# FIXME: Needs cleanup -- vila 20100611
1980
2142
def assertActivitiesMatch(self):
1981
2143
self.assertEqual(self.server.bytes_read,
2095
2257
class TestActivity(tests.TestCase, TestActivityMixin):
2259
scenarios = multiply_scenarios(
2260
vary_by_http_activity(),
2261
vary_by_http_protocol_version(),
2097
2264
def setUp(self):
2098
tests.TestCase.setUp(self)
2099
self.server = self._activity_server(self._protocol_version)
2100
self.server.start_server()
2101
self.activities = {}
2102
def report_activity(t, bytes, direction):
2103
count = self.activities.get(direction, 0)
2105
self.activities[direction] = count
2107
# We override at class level because constructors may propagate the
2108
# bound method and render instance overriding ineffective (an
2109
# alternative would be to define a specific ui factory instead...)
2110
self.orig_report_activity = self._transport._report_activity
2111
self._transport._report_activity = report_activity
2114
self._transport._report_activity = self.orig_report_activity
2115
self.server.stop_server()
2116
tests.TestCase.tearDown(self)
2265
super(TestActivity, self).setUp()
2266
TestActivityMixin.setUp(self)
2119
2269
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2271
# Unlike TestActivity, we are really testing ReportingFileSocket and
2272
# ReportingSocket, so we don't need all the parametrization. Since
2273
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2274
# test them through their use by the transport than directly (that's a
2275
# bit less clean but far more simpler and effective).
2276
_activity_server = ActivityHTTPServer
2277
_protocol_version = 'HTTP/1.1'
2121
2279
def setUp(self):
2122
tests.TestCase.setUp(self)
2123
# Unlike TestActivity, we are really testing ReportingFileSocket and
2124
# ReportingSocket, so we don't need all the parametrization. Since
2125
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2126
# test them through their use by the transport than directly (that's a
2127
# bit less clean but far more simpler and effective).
2128
self.server = ActivityHTTPServer('HTTP/1.1')
2129
self._transport=_urllib.HttpTransport_urllib
2131
self.server.start_server()
2133
# We override at class level because constructors may propagate the
2134
# bound method and render instance overriding ineffective (an
2135
# alternative would be to define a specific ui factory instead...)
2136
self.orig_report_activity = self._transport._report_activity
2137
self._transport._report_activity = None
2140
self._transport._report_activity = self.orig_report_activity
2141
self.server.stop_server()
2142
tests.TestCase.tearDown(self)
2280
super(TestNoReportActivity, self).setUp()
2281
self._transport =_urllib.HttpTransport_urllib
2282
TestActivityMixin.setUp(self)
2144
2284
def assertActivitiesMatch(self):
2145
2285
# Nothing to check here