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
if features.HTTPSServerFeature.available():
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,)),)
139
if features.HTTPSServerFeature.available():
160
_transport=PyCurlTransport,)),)
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.
1048
1043
self.assertEqual('single', t._range_hint)
1051
class TruncatedBeforeBoundaryRequestHandler(
1052
http_server.TestingHTTPRequestHandler):
1053
"""Truncation before a boundary, like in bug 198646"""
1055
_truncated_ranges = 1
1057
def get_multiple_ranges(self, file, file_size, ranges):
1058
self.send_response(206)
1059
self.send_header('Accept-Ranges', 'bytes')
1061
self.send_header('Content-Type',
1062
'multipart/byteranges; boundary=%s' % boundary)
1063
boundary_line = '--%s\r\n' % boundary
1064
# Calculate the Content-Length
1066
for (start, end) in ranges:
1067
content_length += len(boundary_line)
1068
content_length += self._header_line_length(
1069
'Content-type', 'application/octet-stream')
1070
content_length += self._header_line_length(
1071
'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
1072
content_length += len('\r\n') # end headers
1073
content_length += end - start # + 1
1074
content_length += len(boundary_line)
1075
self.send_header('Content-length', content_length)
1078
# Send the multipart body
1080
for (start, end) in ranges:
1081
if cur + self._truncated_ranges >= len(ranges):
1082
# Abruptly ends the response and close the connection
1083
self.close_connection = 1
1085
self.wfile.write(boundary_line)
1086
self.send_header('Content-type', 'application/octet-stream')
1087
self.send_header('Content-Range', 'bytes %d-%d/%d'
1088
% (start, end, file_size))
1090
self.send_range_content(file, start, end - start + 1)
1093
self.wfile.write(boundary_line)
1096
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1097
"""Tests the case of bug 198646, disconnecting before a boundary."""
1099
_req_handler_class = TruncatedBeforeBoundaryRequestHandler
1102
super(TestTruncatedBeforeBoundary, self).setUp()
1103
self.build_tree_contents([('a', '0123456789')],)
1105
def test_readv_with_short_reads(self):
1106
server = self.get_readonly_server()
1107
t = self.get_readonly_transport()
1108
# Force separate ranges for each offset
1109
t._bytes_to_read_before_seek = 0
1110
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1111
self.assertEqual((0, '0'), ireadv.next())
1112
self.assertEqual((2, '2'), ireadv.next())
1113
self.assertEqual((4, '45'), ireadv.next())
1114
self.assertEqual((9, '9'), ireadv.next())
1117
1045
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1118
1046
"""Errors out when range specifiers exceed the limit"""
1188
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)
1191
1133
def _proxied_request(self):
1192
1134
handler = _urllib2_wrappers.ProxyHandler()
1193
request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1135
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1194
1136
handler.set_proxy(request, 'http')
1197
def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1198
handler = _urllib2_wrappers.ProxyHandler()
1199
self.assertEquals(expected,
1200
handler.evaluate_proxy_bypass(host, no_proxy))
1202
1139
def test_empty_user(self):
1203
self.overrideEnv('http_proxy', 'http://bar.com')
1204
request = self._proxied_request()
1205
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1207
def test_user_with_at(self):
1208
self.overrideEnv('http_proxy',
1209
'http://username@domain:password@proxy_host:1234')
1140
self._install_env({'http_proxy': 'http://bar.com'})
1210
1141
request = self._proxied_request()
1211
1142
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1213
1144
def test_invalid_proxy(self):
1214
1145
"""A proxy env variable without scheme"""
1215
self.overrideEnv('http_proxy', 'host:1234')
1146
self._install_env({'http_proxy': 'host:1234'})
1216
1147
self.assertRaises(errors.InvalidURL, self._proxied_request)
1218
def test_evaluate_proxy_bypass_true(self):
1219
"""The host is not proxied"""
1220
self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1221
self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1223
def test_evaluate_proxy_bypass_false(self):
1224
"""The host is proxied"""
1225
self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1227
def test_evaluate_proxy_bypass_unknown(self):
1228
"""The host is not explicitly proxied"""
1229
self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1230
self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1232
def test_evaluate_proxy_bypass_empty_entries(self):
1233
"""Ignore empty entries"""
1234
self.assertEvaluateProxyBypass(None, 'example.com', '')
1235
self.assertEvaluateProxyBypass(None, 'example.com', ',')
1236
self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1239
1150
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1240
1151
"""Tests proxy server.
1245
1156
to the file names).
1248
scenarios = multiply_scenarios(
1249
vary_by_http_client_implementation(),
1250
vary_by_http_protocol_version(),
1253
1159
# FIXME: We don't have an https server available, so we don't
1254
# test https connections. --vila toolongago
1160
# test https connections.
1256
1162
def setUp(self):
1257
1163
super(TestProxyHttpServer, self).setUp()
1258
self.transport_secondary_server = http_utils.ProxyServer
1259
1164
self.build_tree_contents([('foo', 'contents of foo\n'),
1260
1165
('foo-proxied', 'proxied contents of foo\n')])
1261
1166
# Let's setup some attributes for tests
1262
server = self.get_readonly_server()
1263
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)
1264
1169
if self._testing_pycurl():
1265
1170
# Oh my ! pycurl does not check for the port as part of
1266
1171
# no_proxy :-( So we just test the host part
1267
self.no_proxy_host = server.host
1172
self.no_proxy_host = self.server.host
1269
self.no_proxy_host = self.server_host_port
1174
self.no_proxy_host = self.proxy_address
1270
1175
# The secondary server is the proxy
1271
self.proxy_url = self.get_secondary_url()
1176
self.proxy = self.get_secondary_server()
1177
self.proxy_url = self.proxy.get_url()
1273
1180
def _testing_pycurl(self):
1274
1181
# TODO: This is duplicated for lots of the classes in this file
1275
1182
return (features.pycurl.available()
1276
1183
and self._transport == PyCurlTransport)
1278
def assertProxied(self):
1279
t = self.get_readonly_transport()
1280
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1282
def assertNotProxied(self):
1283
t = self.get_readonly_transport()
1284
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())
1286
1217
def test_http_proxy(self):
1287
self.overrideEnv('http_proxy', self.proxy_url)
1288
self.assertProxied()
1218
self.proxied_in_env({'http_proxy': self.proxy_url})
1290
1220
def test_HTTP_PROXY(self):
1291
1221
if self._testing_pycurl():
1294
1224
# about. Should we ?)
1295
1225
raise tests.TestNotApplicable(
1296
1226
'pycurl does not check HTTP_PROXY for security reasons')
1297
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1298
self.assertProxied()
1227
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1300
1229
def test_all_proxy(self):
1301
self.overrideEnv('all_proxy', self.proxy_url)
1302
self.assertProxied()
1230
self.proxied_in_env({'all_proxy': self.proxy_url})
1304
1232
def test_ALL_PROXY(self):
1305
self.overrideEnv('ALL_PROXY', self.proxy_url)
1306
self.assertProxied()
1233
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1308
1235
def test_http_proxy_with_no_proxy(self):
1309
self.overrideEnv('no_proxy', self.no_proxy_host)
1310
self.overrideEnv('http_proxy', self.proxy_url)
1311
self.assertNotProxied()
1236
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1237
'no_proxy': self.no_proxy_host})
1313
1239
def test_HTTP_PROXY_with_NO_PROXY(self):
1314
1240
if self._testing_pycurl():
1315
1241
raise tests.TestNotApplicable(
1316
1242
'pycurl does not check HTTP_PROXY for security reasons')
1317
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1318
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1319
self.assertNotProxied()
1243
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1244
'NO_PROXY': self.no_proxy_host})
1321
1246
def test_all_proxy_with_no_proxy(self):
1322
self.overrideEnv('no_proxy', self.no_proxy_host)
1323
self.overrideEnv('all_proxy', self.proxy_url)
1324
self.assertNotProxied()
1247
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1248
'no_proxy': self.no_proxy_host})
1326
1250
def test_ALL_PROXY_with_NO_PROXY(self):
1327
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1328
self.overrideEnv('ALL_PROXY', self.proxy_url)
1329
self.assertNotProxied()
1251
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1252
'NO_PROXY': self.no_proxy_host})
1331
1254
def test_http_proxy_without_scheme(self):
1332
self.overrideEnv('http_proxy', self.server_host_port)
1333
1255
if self._testing_pycurl():
1334
1256
# pycurl *ignores* invalid proxy env variables. If that ever change
1335
1257
# in the future, this test will fail indicating that pycurl do not
1336
1258
# ignore anymore such variables.
1337
self.assertNotProxied()
1259
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1339
self.assertRaises(errors.InvalidURL, self.assertProxied)
1261
self.assertRaises(errors.InvalidURL,
1262
self.proxied_in_env,
1263
{'http_proxy': self.proxy_address})
1342
1266
class TestRanges(http_utils.TestCaseWithWebserver):
1343
1267
"""Test the Range header in GET methods."""
1345
scenarios = multiply_scenarios(
1346
vary_by_http_client_implementation(),
1347
vary_by_http_protocol_version(),
1350
1269
def setUp(self):
1351
1270
http_utils.TestCaseWithWebserver.setUp(self)
1352
1271
self.build_tree_contents([('a', '0123456789')],)
1272
server = self.get_readonly_server()
1273
self.transport = self._transport(server.get_url())
1354
1275
def create_transport_readonly_server(self):
1355
1276
return http_server.HttpServer(protocol_version=self._protocol_version)
1357
1278
def _file_contents(self, relpath, ranges):
1358
t = self.get_readonly_transport()
1359
1279
offsets = [ (start, end - start + 1) for start, end in ranges]
1360
coalesce = t._coalesce_offsets
1280
coalesce = self.transport._coalesce_offsets
1361
1281
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1362
code, data = t._get(relpath, coalesced)
1282
code, data = self.transport._get(relpath, coalesced)
1363
1283
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1364
1284
for start, end in ranges:
1365
1285
data.seek(start)
1366
1286
yield data.read(end - start + 1)
1368
1288
def _file_tail(self, relpath, tail_amount):
1369
t = self.get_readonly_transport()
1370
code, data = t._get(relpath, [], tail_amount)
1289
code, data = self.transport._get(relpath, [], tail_amount)
1371
1290
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1372
1291
data.seek(-tail_amount, 2)
1373
1292
return data.read(tail_amount)
1491
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)
1494
1407
def test_one_redirection(self):
1495
t = self.get_old_transport()
1496
req = RedirectedRequest('GET', t._remote_path('a'))
1408
t = self.old_transport
1410
req = RedirectedRequest('GET', t.abspath('a'))
1497
1411
new_prefix = 'http://%s:%s' % (self.new_server.host,
1498
1412
self.new_server.port)
1499
1413
self.old_server.redirections = \
1500
1414
[('(.*)', r'%s/1\1' % (new_prefix), 301),]
1501
self.assertEqual('redirected once', t._perform(req).read())
1415
self.assertEqual('redirected once',t._perform(req).read())
1503
1417
def test_five_redirections(self):
1504
t = self.get_old_transport()
1505
req = RedirectedRequest('GET', t._remote_path('a'))
1418
t = self.old_transport
1420
req = RedirectedRequest('GET', t.abspath('a'))
1506
1421
old_prefix = 'http://%s:%s' % (self.old_server.host,
1507
1422
self.old_server.port)
1508
1423
new_prefix = 'http://%s:%s' % (self.new_server.host,
1514
1429
('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1515
1430
('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1517
self.assertEqual('redirected 5 times', t._perform(req).read())
1432
self.assertEqual('redirected 5 times',t._perform(req).read())
1520
1435
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1521
1436
"""Test transport.do_catching_redirections."""
1523
scenarios = multiply_scenarios(
1524
vary_by_http_client_implementation(),
1525
vary_by_http_protocol_version(),
1528
1438
def setUp(self):
1529
1439
super(TestDoCatchRedirections, self).setUp()
1530
1440
self.build_tree_contents([('a', '0123456789'),],)
1531
cleanup_http_redirection_connections(self)
1533
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')
1538
1447
def test_no_redirection(self):
1539
t = self.get_new_transport()
1448
t = self._transport(self.new_server.get_url())
1541
1450
# We use None for redirected so that we fail if redirected
1542
1451
self.assertEqual('0123456789',
1569
1478
self.get_a, self.old_transport, redirected)
1572
def _setup_authentication_config(**kwargs):
1573
conf = config.AuthenticationConfig()
1574
conf._get_config().update({'httptest': kwargs})
1578
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1579
"""Unit tests for glue by which urllib2 asks us for authentication"""
1581
def test_get_user_password_without_port(self):
1582
"""We cope if urllib2 doesn't tell us the port.
1584
See https://bugs.launchpad.net/bzr/+bug/654684
1588
_setup_authentication_config(scheme='http', host='localhost',
1589
user=user, password=password)
1590
handler = _urllib2_wrappers.HTTPAuthHandler()
1591
got_pass = handler.get_user_password(dict(
1598
self.assertEquals((user, password), got_pass)
1601
1481
class TestAuth(http_utils.TestCaseWithWebserver):
1602
1482
"""Test authentication scheme"""
1604
scenarios = multiply_scenarios(
1605
vary_by_http_client_implementation(),
1606
vary_by_http_protocol_version(),
1607
vary_by_http_auth_scheme(),
1484
_auth_header = 'Authorization'
1485
_password_prompt_prefix = ''
1486
_username_prompt_prefix = ''
1610
1490
def setUp(self):
1611
1491
super(TestAuth, self).setUp()
1762
1642
# Only one 'Authentication Required' error should occur
1763
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)
1765
1664
def test_changing_nonce(self):
1766
1665
if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1767
1666
http_utils.ProxyDigestAuthServer):
1768
1667
raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
1769
1668
if self._testing_pycurl():
1669
raise tests.KnownFailure(
1771
1670
'pycurl does not handle a nonce change')
1772
1671
self.server.add_user('joe', 'foo')
1773
1672
t = self.get_user_transport('joe', 'foo')
1783
1682
# initial 'who are you' and a second 'who are you' with the new nonce)
1784
1683
self.assertEqual(2, self.server.auth_required_errors)
1786
def test_user_from_auth_conf(self):
1787
if self._testing_pycurl():
1788
raise tests.TestNotApplicable(
1789
'pycurl does not support authentication.conf')
1792
self.server.add_user(user, password)
1793
_setup_authentication_config(scheme='http', port=self.server.port,
1794
user=user, password=password)
1795
t = self.get_user_transport(None, None)
1796
# Issue a request to the server to connect
1797
self.assertEqual('contents of a\n', t.get('a').read())
1798
# Only one 'Authentication Required' error should occur
1799
self.assertEqual(1, self.server.auth_required_errors)
1801
def test_no_credential_leaks_in_log(self):
1802
self.overrideAttr(debug, 'debug_flags', set(['http']))
1804
password = 'very-sensitive-password'
1805
self.server.add_user(user, password)
1806
t = self.get_user_transport(user, password)
1807
# Capture the debug calls to mutter
1810
lines = args[0] % args[1:]
1811
# Some calls output multiple lines, just split them now since we
1812
# care about a single one later.
1813
self.mutters.extend(lines.splitlines())
1814
self.overrideAttr(trace, 'mutter', mutter)
1815
# Issue a request to the server to connect
1816
self.assertEqual(True, t.has('a'))
1817
# Only one 'Authentication Required' error should occur
1818
self.assertEqual(1, self.server.auth_required_errors)
1819
# Since the authentification succeeded, there should be a corresponding
1821
sent_auth_headers = [line for line in self.mutters
1822
if line.startswith('> %s' % (self._auth_header,))]
1823
self.assertLength(1, sent_auth_headers)
1824
self.assertStartsWith(sent_auth_headers[0],
1825
'> %s: <masked>' % (self._auth_header,))
1828
1687
class TestProxyAuth(TestAuth):
1829
"""Test proxy authentication schemes.
1831
This inherits from TestAuth to tweak the setUp and filter some failing
1835
scenarios = multiply_scenarios(
1836
vary_by_http_client_implementation(),
1837
vary_by_http_protocol_version(),
1838
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 '
1841
1694
def setUp(self):
1842
1695
super(TestProxyAuth, self).setUp()
1697
self.addCleanup(self._restore_env)
1843
1698
# Override the contents to avoid false positives
1844
1699
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1845
1700
('b', 'not proxied contents of b\n'),
1886
1748
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1888
scenarios = multiply_scenarios(
1889
vary_by_http_client_implementation(),
1890
vary_by_http_protocol_version(),
1893
1750
def setUp(self):
1894
1751
super(SmartHTTPTunnellingTest, self).setUp()
1895
1752
# We use the VFS layer as part of HTTP tunnelling tests.
1896
self.overrideEnv('BZR_NO_SMART_VFS', None)
1753
self._captureVar('BZR_NO_SMART_VFS', None)
1897
1754
self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1898
self.http_server = self.get_readonly_server()
1900
1756
def create_transport_readonly_server(self):
1901
server = http_utils.HTTPServerWithSmarts(
1757
return http_utils.HTTPServerWithSmarts(
1902
1758
protocol_version=self._protocol_version)
1903
server._url_protocol = self._url_protocol
1906
1760
def test_open_bzrdir(self):
1907
1761
branch = self.make_branch('relpath')
1908
url = self.http_server.get_url() + 'relpath'
1762
http_server = self.get_readonly_server()
1763
url = http_server.get_url() + 'relpath'
1909
1764
bd = bzrdir.BzrDir.open(url)
1910
self.addCleanup(bd.transport.disconnect)
1911
1765
self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1913
1767
def test_bulk_data(self):
2103
1957
tests.TestCase.setUp(self)
2104
1958
self.server = self._activity_server(self._protocol_version)
2105
1959
self.server.start_server()
2106
_activities = {} # Don't close over self and create a cycle
1960
self.activities = {}
2107
1961
def report_activity(t, bytes, direction):
2108
count = _activities.get(direction, 0)
1962
count = self.activities.get(direction, 0)
2110
_activities[direction] = count
2111
self.activities = _activities
1964
self.activities[direction] = count
2113
1966
# We override at class level because constructors may propagate the
2114
1967
# bound method and render instance overriding ineffective (an
2115
1968
# alternative would be to define a specific ui factory instead...)
2116
self.overrideAttr(self._transport, '_report_activity', report_activity)
2117
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)
2119
1977
def get_transport(self):
2120
t = self._transport(self.server.get_url())
2121
# FIXME: Needs cleanup -- vila 20100611
1978
return self._transport(self.server.get_url())
2124
1980
def assertActivitiesMatch(self):
2125
1981
self.assertEqual(self.server.bytes_read,
2239
2095
class TestActivity(tests.TestCase, TestActivityMixin):
2241
scenarios = multiply_scenarios(
2242
vary_by_http_activity(),
2243
vary_by_http_protocol_version(),
2246
2097
def setUp(self):
2247
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)
2250
2119
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2252
# Unlike TestActivity, we are really testing ReportingFileSocket and
2253
# ReportingSocket, so we don't need all the parametrization. Since
2254
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2255
# test them through their use by the transport than directly (that's a
2256
# bit less clean but far more simpler and effective).
2257
_activity_server = ActivityHTTPServer
2258
_protocol_version = 'HTTP/1.1'
2260
2121
def setUp(self):
2261
self._transport =_urllib.HttpTransport_urllib
2262
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)
2264
2144
def assertActivitiesMatch(self):
2265
2145
# Nothing to check here
2287
2176
self.new_server.port)
2288
2177
self.old_server.redirections = [
2289
2178
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2290
self.old_transport = self.get_old_transport()
2179
self.old_transport = self._transport(self.old_server.get_url())
2291
2180
self.new_server.add_user('joe', 'foo')
2292
cleanup_http_redirection_connections(self)
2294
def create_transport_readonly_server(self):
2295
server = self._auth_server(protocol_version=self._protocol_version)
2296
server._url_protocol = self._url_protocol
2182
def get_a(self, transport):
2183
return transport.get('a')
2302
2185
def test_auth_on_redirected_via_do_catching_redirections(self):
2303
2186
self.redirections = 0
2305
def redirected(t, exception, redirection_notice):
2188
def redirected(transport, exception, redirection_notice):
2306
2189
self.redirections += 1
2307
redirected_t = t._redirected_to(exception.source, exception.target)
2308
self.addCleanup(redirected_t.disconnect)
2190
dir, file = urlutils.split(exception.target)
2191
return self._transport(dir)
2311
2193
stdout = tests.StringIOWrapper()
2312
2194
stderr = tests.StringIOWrapper()