67
66
from bzrlib.transport.http._pycurl import PyCurlTransport
70
load_tests = load_tests_apply_scenarios
73
def vary_by_http_client_implementation():
74
"""Test the two libraries we can use, pycurl and urllib."""
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,
75
80
transport_scenarios = [
76
81
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
77
82
_server=http_server.HttpServer_urllib,
78
_url_protocol='http+urllib',)),
83
_qualified_prefix='http+urllib',)),
80
85
if features.pycurl.available():
81
86
transport_scenarios.append(
82
87
('pycurl', dict(_transport=PyCurlTransport,
83
88
_server=http_server.HttpServer_PyCurl,
84
_url_protocol='http+pycurl',)))
85
return transport_scenarios
88
def vary_by_http_protocol_version():
89
"""Test on http/1.0 and 1.1"""
91
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
92
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
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)),
96
def vary_by_http_auth_scheme():
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 = [
98
135
('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
99
136
('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
101
dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
103
# Add some attributes common to all scenarios
104
for scenario_id, scenario_dict in scenarios:
105
scenario_dict.update(_auth_header='Authorization',
106
_username_prompt_prefix='',
107
_password_prompt_prefix='')
111
def vary_by_http_proxy_auth_scheme():
113
('proxy-basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
114
('proxy-digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
115
('proxy-basicdigest',
116
dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
118
# Add some attributes common to all scenarios
119
for scenario_id, scenario_dict in scenarios:
120
scenario_dict.update(_auth_header='Proxy-Authorization',
121
_username_prompt_prefix='Proxy ',
122
_password_prompt_prefix='Proxy ')
126
def vary_by_http_activity():
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((
127
149
activity_scenarios = [
128
150
('urllib,http', dict(_activity_server=ActivityHTTPServer,
129
_transport=_urllib.HttpTransport_urllib,)),
151
_transport=_urllib.HttpTransport_urllib,)),
131
153
if tests.HTTPSServerFeature.available():
132
154
activity_scenarios.append(
133
155
('urllib,https', dict(_activity_server=ActivityHTTPSServer,
134
_transport=_urllib.HttpTransport_urllib,)),)
156
_transport=_urllib.HttpTransport_urllib,)),)
135
157
if features.pycurl.available():
136
158
activity_scenarios.append(
137
159
('pycurl,http', dict(_activity_server=ActivityHTTPServer,
138
_transport=PyCurlTransport,)),)
160
_transport=PyCurlTransport,)),)
139
161
if tests.HTTPSServerFeature.available():
140
162
from bzrlib.tests import (
193
223
self._sock.bind(('127.0.0.1', 0))
194
224
self.host, self.port = self._sock.getsockname()
195
225
self._ready = threading.Event()
196
self._thread = test_server.TestThread(
197
sync_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)
198
228
self._thread.start()
199
if 'threads' in tests.selftest_debug_flags:
200
sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
203
231
def _accept_read_and_reply(self):
204
232
self._sock.listen(1)
205
233
self._ready.set()
206
conn, address = self._sock.accept()
207
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)
208
240
while not self.received_bytes.endswith(self._expect_body_tail):
209
241
self.received_bytes += conn.recv(4096)
210
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.
212
245
self._sock.close()
213
246
except socket.error:
214
247
# The client may have already closed the socket.
269
296
self.assertEqual('realm="Thou should not pass"', remainder)
272
class TestHTTPRangeParsing(tests.TestCase):
275
super(TestHTTPRangeParsing, self).setUp()
276
# We focus on range parsing here and ignore everything else
277
class RequestHandler(http_server.TestingHTTPRequestHandler):
278
def setup(self): pass
279
def handle(self): pass
280
def finish(self): pass
282
self.req_handler = RequestHandler(None, None, None)
284
def assertRanges(self, ranges, header, file_size):
285
self.assertEquals(ranges,
286
self.req_handler._parse_ranges(header, file_size))
288
def test_simple_range(self):
289
self.assertRanges([(0,2)], 'bytes=0-2', 12)
292
self.assertRanges([(8, 11)], 'bytes=-4', 12)
294
def test_tail_bigger_than_file(self):
295
self.assertRanges([(0, 11)], 'bytes=-99', 12)
297
def test_range_without_end(self):
298
self.assertRanges([(4, 11)], 'bytes=4-', 12)
300
def test_invalid_ranges(self):
301
self.assertRanges(None, 'bytes=12-22', 12)
302
self.assertRanges(None, 'bytes=1-3,12-22', 12)
303
self.assertRanges(None, 'bytes=-', 12)
306
299
class TestHTTPServer(tests.TestCase):
307
300
"""Test the HTTP servers implementations."""
312
305
protocol_version = 'HTTP/0.1'
314
self.assertRaises(httplib.UnknownProtocol,
315
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')
317
314
def test_force_invalid_protocol(self):
318
self.assertRaises(httplib.UnknownProtocol,
319
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')
321
322
def test_server_start_and_stop(self):
322
323
server = http_server.HttpServer()
323
self.addCleanup(server.stop_server)
324
324
server.start_server()
325
self.assertTrue(server.server is not None)
326
self.assertTrue(server.server.serving is not None)
327
self.assertTrue(server.server.serving)
326
self.assertTrue(server._http_running)
329
self.assertFalse(server._http_running)
329
331
def test_create_http_server_one_zero(self):
330
332
class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
399
401
class TestHttpTransportUrls(tests.TestCase):
400
402
"""Test the http urls."""
402
scenarios = vary_by_http_client_implementation()
404
404
def test_abs_url(self):
405
405
"""Construction of absolute http URLs"""
406
t = self._transport('http://example.com/bzr/bzr.dev/')
406
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
407
eq = self.assertEqualDiff
408
eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
409
eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
410
eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
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')
411
411
eq(t.abspath('.bzr/1//2/./3'),
412
'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
412
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
414
414
def test_invalid_http_urls(self):
415
415
"""Trap invalid construction of urls"""
416
self._transport('http://example.com/bzr/bzr.dev/')
416
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
417
self.assertRaises(errors.InvalidURL,
419
'http://http://example.com/bzr/bzr.dev/')
419
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
421
421
def test_http_root_urls(self):
422
422
"""Construction of URLs from server root"""
423
t = self._transport('http://example.com/')
423
t = self._transport('http://bzr.ozlabs.org/')
424
424
eq = self.assertEqualDiff
425
425
eq(t.abspath('.bzr/tree-version'),
426
'http://example.com/.bzr/tree-version')
426
'http://bzr.ozlabs.org/.bzr/tree-version')
428
428
def test_http_impl_urls(self):
429
429
"""There are servers which ask for particular clients to connect"""
530
525
class TestHttpTransportRegistration(tests.TestCase):
531
526
"""Test registrations of various http implementations"""
533
scenarios = vary_by_http_client_implementation()
535
528
def test_http_registered(self):
536
t = transport.get_transport('%s://foo.com/' % self._url_protocol)
529
t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
537
530
self.assertIsInstance(t, transport.Transport)
538
531
self.assertIsInstance(t, self._transport)
541
534
class TestPost(tests.TestCase):
543
scenarios = multiply_scenarios(
544
vary_by_http_client_implementation(),
545
vary_by_http_protocol_version(),
548
536
def test_post_body_is_received(self):
549
537
server = RecordingServer(expect_body_tail='end-of-body',
550
scheme=self._url_protocol)
538
scheme=self._qualified_prefix)
551
539
self.start_server(server)
552
540
url = server.get_url()
553
# FIXME: needs a cleanup -- vila 20100611
554
http_transport = transport.get_transport(url)
541
http_transport = self._transport(url)
555
542
code, response = http_transport._post('abc def end-of-body')
557
544
server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
558
545
self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
559
self.assertTrue('content-type: application/octet-stream\r'
560
in server.received_bytes.lower())
561
546
# The transport should not be assuming that the server can accept
562
547
# chunked encoding the first time it connects, because HTTP/1.1, so we
563
548
# check for the literal string.
1122
1114
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)
1125
1133
def _proxied_request(self):
1126
1134
handler = _urllib2_wrappers.ProxyHandler()
1127
request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1135
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1128
1136
handler.set_proxy(request, 'http')
1131
def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1132
handler = _urllib2_wrappers.ProxyHandler()
1133
self.assertEquals(expected,
1134
handler.evaluate_proxy_bypass(host, no_proxy))
1136
1139
def test_empty_user(self):
1137
self.overrideEnv('http_proxy', 'http://bar.com')
1138
request = self._proxied_request()
1139
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1141
def test_user_with_at(self):
1142
self.overrideEnv('http_proxy',
1143
'http://username@domain:password@proxy_host:1234')
1140
self._install_env({'http_proxy': 'http://bar.com'})
1144
1141
request = self._proxied_request()
1145
1142
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1147
1144
def test_invalid_proxy(self):
1148
1145
"""A proxy env variable without scheme"""
1149
self.overrideEnv('http_proxy', 'host:1234')
1146
self._install_env({'http_proxy': 'host:1234'})
1150
1147
self.assertRaises(errors.InvalidURL, self._proxied_request)
1152
def test_evaluate_proxy_bypass_true(self):
1153
"""The host is not proxied"""
1154
self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1155
self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1157
def test_evaluate_proxy_bypass_false(self):
1158
"""The host is proxied"""
1159
self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1161
def test_evaluate_proxy_bypass_unknown(self):
1162
"""The host is not explicitly proxied"""
1163
self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1164
self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1166
def test_evaluate_proxy_bypass_empty_entries(self):
1167
"""Ignore empty entries"""
1168
self.assertEvaluateProxyBypass(None, 'example.com', '')
1169
self.assertEvaluateProxyBypass(None, 'example.com', ',')
1170
self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1173
1150
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1174
1151
"""Tests proxy server.
1179
1156
to the file names).
1182
scenarios = multiply_scenarios(
1183
vary_by_http_client_implementation(),
1184
vary_by_http_protocol_version(),
1187
1159
# FIXME: We don't have an https server available, so we don't
1188
# test https connections. --vila toolongago
1160
# test https connections.
1190
1162
def setUp(self):
1191
1163
super(TestProxyHttpServer, self).setUp()
1192
self.transport_secondary_server = http_utils.ProxyServer
1193
1164
self.build_tree_contents([('foo', 'contents of foo\n'),
1194
1165
('foo-proxied', 'proxied contents of foo\n')])
1195
1166
# Let's setup some attributes for tests
1196
server = self.get_readonly_server()
1197
self.server_host_port = '%s:%d' % (server.host, server.port)
1167
self.server = self.get_readonly_server()
1168
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1198
1169
if self._testing_pycurl():
1199
1170
# Oh my ! pycurl does not check for the port as part of
1200
1171
# no_proxy :-( So we just test the host part
1201
self.no_proxy_host = server.host
1172
self.no_proxy_host = self.server.host
1203
self.no_proxy_host = self.server_host_port
1174
self.no_proxy_host = self.proxy_address
1204
1175
# The secondary server is the proxy
1205
self.proxy_url = self.get_secondary_url()
1176
self.proxy = self.get_secondary_server()
1177
self.proxy_url = self.proxy.get_url()
1207
1180
def _testing_pycurl(self):
1208
1181
# TODO: This is duplicated for lots of the classes in this file
1209
1182
return (features.pycurl.available()
1210
1183
and self._transport == PyCurlTransport)
1212
def assertProxied(self):
1213
t = self.get_readonly_transport()
1214
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1216
def assertNotProxied(self):
1217
t = self.get_readonly_transport()
1218
self.assertEqual('contents of foo\n', t.get('foo').read())
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())
1220
1217
def test_http_proxy(self):
1221
self.overrideEnv('http_proxy', self.proxy_url)
1222
self.assertProxied()
1218
self.proxied_in_env({'http_proxy': self.proxy_url})
1224
1220
def test_HTTP_PROXY(self):
1225
1221
if self._testing_pycurl():
1228
1224
# about. Should we ?)
1229
1225
raise tests.TestNotApplicable(
1230
1226
'pycurl does not check HTTP_PROXY for security reasons')
1231
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1232
self.assertProxied()
1227
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1234
1229
def test_all_proxy(self):
1235
self.overrideEnv('all_proxy', self.proxy_url)
1236
self.assertProxied()
1230
self.proxied_in_env({'all_proxy': self.proxy_url})
1238
1232
def test_ALL_PROXY(self):
1239
self.overrideEnv('ALL_PROXY', self.proxy_url)
1240
self.assertProxied()
1233
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1242
1235
def test_http_proxy_with_no_proxy(self):
1243
self.overrideEnv('no_proxy', self.no_proxy_host)
1244
self.overrideEnv('http_proxy', self.proxy_url)
1245
self.assertNotProxied()
1236
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1237
'no_proxy': self.no_proxy_host})
1247
1239
def test_HTTP_PROXY_with_NO_PROXY(self):
1248
1240
if self._testing_pycurl():
1249
1241
raise tests.TestNotApplicable(
1250
1242
'pycurl does not check HTTP_PROXY for security reasons')
1251
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1252
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1253
self.assertNotProxied()
1243
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1244
'NO_PROXY': self.no_proxy_host})
1255
1246
def test_all_proxy_with_no_proxy(self):
1256
self.overrideEnv('no_proxy', self.no_proxy_host)
1257
self.overrideEnv('all_proxy', self.proxy_url)
1258
self.assertNotProxied()
1247
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1248
'no_proxy': self.no_proxy_host})
1260
1250
def test_ALL_PROXY_with_NO_PROXY(self):
1261
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1262
self.overrideEnv('ALL_PROXY', self.proxy_url)
1263
self.assertNotProxied()
1251
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1252
'NO_PROXY': self.no_proxy_host})
1265
1254
def test_http_proxy_without_scheme(self):
1266
self.overrideEnv('http_proxy', self.server_host_port)
1267
1255
if self._testing_pycurl():
1268
1256
# pycurl *ignores* invalid proxy env variables. If that ever change
1269
1257
# in the future, this test will fail indicating that pycurl do not
1270
1258
# ignore anymore such variables.
1271
self.assertNotProxied()
1259
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1273
self.assertRaises(errors.InvalidURL, self.assertProxied)
1261
self.assertRaises(errors.InvalidURL,
1262
self.proxied_in_env,
1263
{'http_proxy': self.proxy_address})
1276
1266
class TestRanges(http_utils.TestCaseWithWebserver):
1277
1267
"""Test the Range header in GET methods."""
1279
scenarios = multiply_scenarios(
1280
vary_by_http_client_implementation(),
1281
vary_by_http_protocol_version(),
1284
1269
def setUp(self):
1285
1270
http_utils.TestCaseWithWebserver.setUp(self)
1286
1271
self.build_tree_contents([('a', '0123456789')],)
1272
server = self.get_readonly_server()
1273
self.transport = self._transport(server.get_url())
1288
1275
def create_transport_readonly_server(self):
1289
1276
return http_server.HttpServer(protocol_version=self._protocol_version)
1291
1278
def _file_contents(self, relpath, ranges):
1292
t = self.get_readonly_transport()
1293
1279
offsets = [ (start, end - start + 1) for start, end in ranges]
1294
coalesce = t._coalesce_offsets
1280
coalesce = self.transport._coalesce_offsets
1295
1281
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1296
code, data = t._get(relpath, coalesced)
1282
code, data = self.transport._get(relpath, coalesced)
1297
1283
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1298
1284
for start, end in ranges:
1299
1285
data.seek(start)
1300
1286
yield data.read(end - start + 1)
1302
1288
def _file_tail(self, relpath, tail_amount):
1303
t = self.get_readonly_transport()
1304
code, data = t._get(relpath, [], tail_amount)
1289
code, data = self.transport._get(relpath, [], tail_amount)
1305
1290
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1306
1291
data.seek(-tail_amount, 2)
1307
1292
return data.read(tail_amount)
1338
1327
'# Bazaar revision bundle v0.9\n#\n')
1329
# The requests to the old server will be redirected to the new server
1330
self.old_transport = self._transport(self.old_server.get_url())
1341
1332
def test_redirected(self):
1342
self.assertRaises(errors.RedirectRequested,
1343
self.get_old_transport().get, 'a')
1344
self.assertEqual('0123456789', self.get_new_transport().get('a').read())
1333
self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1334
t = self._transport(self.new_server.get_url())
1335
self.assertEqual('0123456789', t.get('a').read())
1337
def test_read_redirected_bundle_from_url(self):
1338
from bzrlib.bundle import read_bundle_from_url
1339
url = self.old_transport.abspath('bundle')
1340
bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1341
read_bundle_from_url, url)
1342
# If read_bundle_from_url was successful we get an empty bundle
1343
self.assertEqual([], bundle.revisions)
1347
1346
class RedirectedRequest(_urllib2_wrappers.Request):
1425
1397
('5/a', 'redirected 5 times'),
1400
self.old_transport = self._transport(self.old_server.get_url())
1402
def create_transport_secondary_server(self):
1403
"""Create the secondary server, redirections are defined in the tests"""
1404
return http_utils.HTTPServerRedirecting(
1405
protocol_version=self._protocol_version)
1428
1407
def test_one_redirection(self):
1429
t = self.get_old_transport()
1430
req = RedirectedRequest('GET', t._remote_path('a'))
1408
t = self.old_transport
1410
req = RedirectedRequest('GET', t.abspath('a'))
1431
1411
new_prefix = 'http://%s:%s' % (self.new_server.host,
1432
1412
self.new_server.port)
1433
1413
self.old_server.redirections = \
1434
1414
[('(.*)', r'%s/1\1' % (new_prefix), 301),]
1435
self.assertEqual('redirected once', t._perform(req).read())
1415
self.assertEqual('redirected once',t._perform(req).read())
1437
1417
def test_five_redirections(self):
1438
t = self.get_old_transport()
1439
req = RedirectedRequest('GET', t._remote_path('a'))
1418
t = self.old_transport
1420
req = RedirectedRequest('GET', t.abspath('a'))
1440
1421
old_prefix = 'http://%s:%s' % (self.old_server.host,
1441
1422
self.old_server.port)
1442
1423
new_prefix = 'http://%s:%s' % (self.new_server.host,
1448
1429
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1449
1430
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1451
self.assertEqual('redirected 5 times', t._perform(req).read())
1432
self.assertEqual('redirected 5 times',t._perform(req).read())
1454
1435
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1455
1436
"""Test transport.do_catching_redirections."""
1457
scenarios = multiply_scenarios(
1458
vary_by_http_client_implementation(),
1459
vary_by_http_protocol_version(),
1462
1438
def setUp(self):
1463
1439
super(TestDoCatchRedirections, self).setUp()
1464
1440
self.build_tree_contents([('a', '0123456789'),],)
1465
cleanup_http_redirection_connections(self)
1467
self.old_transport = self.get_old_transport()
1442
self.old_transport = self._transport(self.old_server.get_url())
1444
def get_a(self, transport):
1445
return transport.get('a')
1472
1447
def test_no_redirection(self):
1473
t = self.get_new_transport()
1448
t = self._transport(self.new_server.get_url())
1475
1450
# We use None for redirected so that we fail if redirected
1476
1451
self.assertEqual('0123456789',
1503
1478
self.get_a, self.old_transport, redirected)
1506
def _setup_authentication_config(**kwargs):
1507
conf = config.AuthenticationConfig()
1508
conf._get_config().update({'httptest': kwargs})
1512
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1513
"""Unit tests for glue by which urllib2 asks us for authentication"""
1515
def test_get_user_password_without_port(self):
1516
"""We cope if urllib2 doesn't tell us the port.
1518
See https://bugs.launchpad.net/bzr/+bug/654684
1522
_setup_authentication_config(scheme='http', host='localhost',
1523
user=user, password=password)
1524
handler = _urllib2_wrappers.HTTPAuthHandler()
1525
got_pass = handler.get_user_password(dict(
1532
self.assertEquals((user, password), got_pass)
1535
1481
class TestAuth(http_utils.TestCaseWithWebserver):
1536
1482
"""Test authentication scheme"""
1538
scenarios = multiply_scenarios(
1539
vary_by_http_client_implementation(),
1540
vary_by_http_protocol_version(),
1541
vary_by_http_auth_scheme(),
1484
_auth_header = 'Authorization'
1485
_password_prompt_prefix = ''
1486
_username_prompt_prefix = ''
1544
1490
def setUp(self):
1545
1491
super(TestAuth, self).setUp()
1696
1642
# Only one 'Authentication Required' error should occur
1697
1643
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)
1699
1664
def test_changing_nonce(self):
1700
1665
if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1701
1666
http_utils.ProxyDigestAuthServer):
1717
1682
# initial 'who are you' and a second 'who are you' with the new nonce)
1718
1683
self.assertEqual(2, self.server.auth_required_errors)
1720
def test_user_from_auth_conf(self):
1721
if self._testing_pycurl():
1722
raise tests.TestNotApplicable(
1723
'pycurl does not support authentication.conf')
1726
self.server.add_user(user, password)
1727
_setup_authentication_config(scheme='http', port=self.server.port,
1728
user=user, password=password)
1729
t = self.get_user_transport(None, None)
1730
# Issue a request to the server to connect
1731
self.assertEqual('contents of a\n', t.get('a').read())
1732
# Only one 'Authentication Required' error should occur
1733
self.assertEqual(1, self.server.auth_required_errors)
1735
def test_no_credential_leaks_in_log(self):
1736
self.overrideAttr(debug, 'debug_flags', set(['http']))
1738
password = 'very-sensitive-password'
1739
self.server.add_user(user, password)
1740
t = self.get_user_transport(user, password)
1741
# Capture the debug calls to mutter
1744
lines = args[0] % args[1:]
1745
# Some calls output multiple lines, just split them now since we
1746
# care about a single one later.
1747
self.mutters.extend(lines.splitlines())
1748
self.overrideAttr(trace, 'mutter', mutter)
1749
# Issue a request to the server to connect
1750
self.assertEqual(True, t.has('a'))
1751
# Only one 'Authentication Required' error should occur
1752
self.assertEqual(1, self.server.auth_required_errors)
1753
# Since the authentification succeeded, there should be a corresponding
1755
sent_auth_headers = [line for line in self.mutters
1756
if line.startswith('> %s' % (self._auth_header,))]
1757
self.assertLength(1, sent_auth_headers)
1758
self.assertStartsWith(sent_auth_headers[0],
1759
'> %s: <masked>' % (self._auth_header,))
1762
1687
class TestProxyAuth(TestAuth):
1763
"""Test proxy authentication schemes.
1765
This inherits from TestAuth to tweak the setUp and filter some failing
1769
scenarios = multiply_scenarios(
1770
vary_by_http_client_implementation(),
1771
vary_by_http_protocol_version(),
1772
vary_by_http_proxy_auth_scheme(),
1688
"""Test proxy authentication schemes."""
1690
_auth_header = 'Proxy-authorization'
1691
_password_prompt_prefix = 'Proxy '
1692
_username_prompt_prefix = 'Proxy '
1775
1694
def setUp(self):
1776
1695
super(TestProxyAuth, self).setUp()
1697
self.addCleanup(self._restore_env)
1777
1698
# Override the contents to avoid false positives
1778
1699
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1779
1700
('b', 'not proxied contents of b\n'),
1820
1748
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1822
scenarios = multiply_scenarios(
1823
vary_by_http_client_implementation(),
1824
vary_by_http_protocol_version(),
1827
1750
def setUp(self):
1828
1751
super(SmartHTTPTunnellingTest, self).setUp()
1829
1752
# We use the VFS layer as part of HTTP tunnelling tests.
1830
self.overrideEnv('BZR_NO_SMART_VFS', None)
1753
self._captureVar('BZR_NO_SMART_VFS', None)
1831
1754
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1832
self.http_server = self.get_readonly_server()
1834
1756
def create_transport_readonly_server(self):
1835
server = http_utils.HTTPServerWithSmarts(
1757
return http_utils.HTTPServerWithSmarts(
1836
1758
protocol_version=self._protocol_version)
1837
server._url_protocol = self._url_protocol
1840
1760
def test_open_bzrdir(self):
1841
1761
branch = self.make_branch('relpath')
1842
url = self.http_server.get_url() + 'relpath'
1762
http_server = self.get_readonly_server()
1763
url = http_server.get_url() + 'relpath'
1843
1764
bd = bzrdir.BzrDir.open(url)
1844
self.addCleanup(bd.transport.disconnect)
1845
1765
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1847
1767
def test_bulk_data(self):
2037
1957
tests.TestCase.setUp(self)
2038
1958
self.server = self._activity_server(self._protocol_version)
2039
1959
self.server.start_server()
2040
_activities = {} # Don't close over self and create a cycle
1960
self.activities = {}
2041
1961
def report_activity(t, bytes, direction):
2042
count = _activities.get(direction, 0)
1962
count = self.activities.get(direction, 0)
2044
_activities[direction] = count
2045
self.activities = _activities
1964
self.activities[direction] = count
2047
1966
# We override at class level because constructors may propagate the
2048
1967
# bound method and render instance overriding ineffective (an
2049
1968
# alternative would be to define a specific ui factory instead...)
2050
self.overrideAttr(self._transport, '_report_activity', report_activity)
2051
self.addCleanup(self.server.stop_server)
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)
2053
1977
def get_transport(self):
2054
t = self._transport(self.server.get_url())
2055
# FIXME: Needs cleanup -- vila 20100611
1978
return self._transport(self.server.get_url())
2058
1980
def assertActivitiesMatch(self):
2059
1981
self.assertEqual(self.server.bytes_read,
2173
2095
class TestActivity(tests.TestCase, TestActivityMixin):
2175
scenarios = multiply_scenarios(
2176
vary_by_http_activity(),
2177
vary_by_http_protocol_version(),
2180
2097
def setUp(self):
2181
TestActivityMixin.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)
2184
2119
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2186
# Unlike TestActivity, we are really testing ReportingFileSocket and
2187
# ReportingSocket, so we don't need all the parametrization. Since
2188
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2189
# test them through their use by the transport than directly (that's a
2190
# bit less clean but far more simpler and effective).
2191
_activity_server = ActivityHTTPServer
2192
_protocol_version = 'HTTP/1.1'
2194
2121
def setUp(self):
2195
self._transport =_urllib.HttpTransport_urllib
2196
TestActivityMixin.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)
2198
2144
def assertActivitiesMatch(self):
2199
2145
# Nothing to check here
2221
2176
self.new_server.port)
2222
2177
self.old_server.redirections = [
2223
2178
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2224
self.old_transport = self.get_old_transport()
2179
self.old_transport = self._transport(self.old_server.get_url())
2225
2180
self.new_server.add_user('joe', 'foo')
2226
cleanup_http_redirection_connections(self)
2228
def create_transport_readonly_server(self):
2229
server = self._auth_server(protocol_version=self._protocol_version)
2230
server._url_protocol = self._url_protocol
2182
def get_a(self, transport):
2183
return transport.get('a')
2236
2185
def test_auth_on_redirected_via_do_catching_redirections(self):
2237
2186
self.redirections = 0
2239
def redirected(t, exception, redirection_notice):
2188
def redirected(transport, exception, redirection_notice):
2240
2189
self.redirections += 1
2241
redirected_t = t._redirected_to(exception.source, exception.target)
2242
self.addCleanup(redirected_t.disconnect)
2190
dir, file = urlutils.split(exception.target)
2191
return self._transport(dir)
2245
2193
stdout = tests.StringIOWrapper()
2246
2194
stderr = tests.StringIOWrapper()