66
if features.pycurl.available():
67
62
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."""
75
transport_scenarios = [
76
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
77
_server=http_server.HttpServer_urllib,
78
_url_protocol='http+urllib',)),
80
if features.pycurl.available():
81
transport_scenarios.append(
82
('pycurl', dict(_transport=PyCurlTransport,
83
_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')),
96
def vary_by_http_auth_scheme():
98
('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
99
('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():
127
activity_scenarios = [
128
('urllib,http', dict(_activity_server=ActivityHTTPServer,
129
_transport=_urllib.HttpTransport_urllib,)),
131
if features.HTTPSServerFeature.available():
132
activity_scenarios.append(
133
('urllib,https', dict(_activity_server=ActivityHTTPSServer,
134
_transport=_urllib.HttpTransport_urllib,)),)
135
if features.pycurl.available():
136
activity_scenarios.append(
137
('pycurl,http', dict(_activity_server=ActivityHTTPServer,
138
_transport=PyCurlTransport,)),)
139
if features.HTTPSServerFeature.available():
140
from bzrlib.tests import (
64
except errors.DependencyNotPresent:
65
pycurl_present = False
68
class TransportAdapter(tests.TestScenarioApplier):
69
"""Generate the same test for each transport implementation."""
72
transport_scenarios = [
73
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
74
_server=http_server.HttpServer_urllib,
75
_qualified_prefix='http+urllib',)),
78
transport_scenarios.append(
79
('pycurl', dict(_transport=PyCurlTransport,
80
_server=http_server.HttpServer_PyCurl,
81
_qualified_prefix='http+pycurl',)))
82
self.scenarios = transport_scenarios
85
class TransportProtocolAdapter(TransportAdapter):
86
"""Generate the same test for each protocol implementation.
88
In addition to the transport adaptatation that we inherit from.
92
super(TransportProtocolAdapter, self).__init__()
93
protocol_scenarios = [
94
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
95
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
97
self.scenarios = tests.multiply_scenarios(self.scenarios,
101
class TransportProtocolAuthenticationAdapter(TransportProtocolAdapter):
102
"""Generate the same test for each authentication scheme implementation.
104
In addition to the protocol adaptatation that we inherit from.
108
super(TransportProtocolAuthenticationAdapter, self).__init__()
109
auth_scheme_scenarios = [
110
('basic', dict(_auth_scheme='basic')),
111
('digest', dict(_auth_scheme='digest')),
114
self.scenarios = tests.multiply_scenarios(self.scenarios,
115
auth_scheme_scenarios)
117
def load_tests(standard_tests, module, loader):
118
"""Multiply tests for http clients and protocol versions."""
119
# one for each transport
120
t_adapter = TransportAdapter()
121
t_classes= (TestHttpTransportRegistration,
122
TestHttpTransportUrls,
143
# FIXME: Until we have a better way to handle self-signed
144
# certificates (like allowing them in a test specific
145
# authentication.conf for example), we need some specialized pycurl
146
# transport for tests.
147
class HTTPS_pycurl_transport(PyCurlTransport):
149
def __init__(self, base, _from_transport=None):
150
super(HTTPS_pycurl_transport, self).__init__(
151
base, _from_transport)
152
self.cabundle = str(ssl_certs.build_path('ca.crt'))
154
activity_scenarios.append(
155
('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
156
_transport=HTTPS_pycurl_transport,)),)
157
return activity_scenarios
124
is_testing_for_transports = tests.condition_isinstance(t_classes)
126
# multiplied by one for each protocol version
127
tp_adapter = TransportProtocolAdapter()
128
tp_classes= (SmartHTTPTunnellingTest,
129
TestDoCatchRedirections,
131
TestHTTPRedirections,
132
TestHTTPSilentRedirections,
133
TestLimitedRangeRequestServer,
137
TestSpecificRequestHandler,
139
is_also_testing_for_protocols = tests.condition_isinstance(tp_classes)
141
# multiplied by one for each authentication scheme
142
tpa_adapter = TransportProtocolAuthenticationAdapter()
143
tpa_classes = (TestAuth,
145
is_also_testing_for_authentication = tests.condition_isinstance(
148
result = loader.suiteClass()
149
for test_class in tests.iter_suite_tests(standard_tests):
150
# Each test class is either standalone or testing for some combination
151
# of transport, protocol version, authentication scheme. Use the right
152
# adpater (or none) depending on the class.
153
if is_testing_for_transports(test_class):
154
result.addTests(t_adapter.adapt(test_class))
155
elif is_also_testing_for_protocols(test_class):
156
result.addTests(tp_adapter.adapt(test_class))
157
elif is_also_testing_for_authentication(test_class):
158
result.addTests(tpa_adapter.adapt(test_class))
160
result.addTest(test_class)
160
164
class FakeManager(object):
185
189
self.received_bytes = ''
189
return '%s://%s:%s/' % (self.scheme, self.host, self.port)
191
def start_server(self):
192
192
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
193
193
self._sock.bind(('127.0.0.1', 0))
194
194
self.host, self.port = self._sock.getsockname()
195
195
self._ready = threading.Event()
196
self._thread = test_server.TestThread(
197
sync_event=self._ready, target=self._accept_read_and_reply)
196
self._thread = threading.Thread(target=self._accept_read_and_reply)
197
self._thread.setDaemon(True)
198
198
self._thread.start()
199
if 'threads' in tests.selftest_debug_flags:
200
sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
203
201
def _accept_read_and_reply(self):
204
202
self._sock.listen(1)
205
203
self._ready.set()
206
conn, address = self._sock.accept()
207
if self._expect_body_tail is not None:
204
self._sock.settimeout(5)
206
conn, address = self._sock.accept()
207
# On win32, the accepted connection will be non-blocking to start
208
# with because we're using settimeout.
209
conn.setblocking(True)
208
210
while not self.received_bytes.endswith(self._expect_body_tail):
209
211
self.received_bytes += conn.recv(4096)
210
212
conn.sendall('HTTP/1.1 200 OK\r\n')
213
except socket.timeout:
214
# Make sure the client isn't stuck waiting for us to e.g. accept.
212
215
self._sock.close()
213
216
except socket.error:
214
217
# The client may have already closed the socket.
217
def stop_server(self):
219
# Issue a fake connection to wake up the server and allow it to
221
fake_conn = osutils.connect_socket((self.host, self.port))
223
223
except socket.error:
224
224
# We might have already closed it. We don't care.
229
if 'threads' in tests.selftest_debug_flags:
230
sys.stderr.write('Thread joined: %s\n' % (self._thread.ident,))
233
class TestAuthHeader(tests.TestCase):
235
def parse_header(self, header, auth_handler_class=None):
236
if auth_handler_class is None:
237
auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
238
self.auth_handler = auth_handler_class()
239
return self.auth_handler._parse_auth_header(header)
241
def test_empty_header(self):
242
scheme, remainder = self.parse_header('')
243
self.assertEqual('', scheme)
244
self.assertIs(None, remainder)
246
def test_negotiate_header(self):
247
scheme, remainder = self.parse_header('Negotiate')
248
self.assertEqual('negotiate', scheme)
249
self.assertIs(None, remainder)
251
def test_basic_header(self):
252
scheme, remainder = self.parse_header(
253
'Basic realm="Thou should not pass"')
254
self.assertEqual('basic', scheme)
255
self.assertEqual('realm="Thou should not pass"', remainder)
257
def test_basic_extract_realm(self):
258
scheme, remainder = self.parse_header(
259
'Basic realm="Thou should not pass"',
260
_urllib2_wrappers.BasicAuthHandler)
261
match, realm = self.auth_handler.extract_realm(remainder)
262
self.assertTrue(match is not None)
263
self.assertEqual('Thou should not pass', realm)
265
def test_digest_header(self):
266
scheme, remainder = self.parse_header(
267
'Digest realm="Thou should not pass"')
268
self.assertEqual('digest', scheme)
269
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
230
class TestHTTPServer(tests.TestCase):
386
324
def test_url_parsing(self):
387
325
f = FakeManager()
388
326
url = http.extract_auth('http://example.com', f)
389
self.assertEqual('http://example.com', url)
390
self.assertEqual(0, len(f.credentials))
327
self.assertEquals('http://example.com', url)
328
self.assertEquals(0, len(f.credentials))
391
329
url = http.extract_auth(
392
'http://user:pass@example.com/bzr/bzr.dev', f)
393
self.assertEqual('http://example.com/bzr/bzr.dev', url)
394
self.assertEqual(1, len(f.credentials))
395
self.assertEqual([None, 'example.com', 'user', 'pass'],
330
'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
331
self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
332
self.assertEquals(1, len(f.credentials))
333
self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
399
337
class TestHttpTransportUrls(tests.TestCase):
400
338
"""Test the http urls."""
402
scenarios = vary_by_http_client_implementation()
404
340
def test_abs_url(self):
405
341
"""Construction of absolute http URLs"""
406
t = self._transport('http://example.com/bzr/bzr.dev/')
342
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
343
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')
344
eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
345
eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
346
eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
411
347
eq(t.abspath('.bzr/1//2/./3'),
412
'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
348
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
414
350
def test_invalid_http_urls(self):
415
351
"""Trap invalid construction of urls"""
416
self._transport('http://example.com/bzr/bzr.dev/')
352
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
353
self.assertRaises(errors.InvalidURL,
419
'http://http://example.com/bzr/bzr.dev/')
355
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
421
357
def test_http_root_urls(self):
422
358
"""Construction of URLs from server root"""
423
t = self._transport('http://example.com/')
359
t = self._transport('http://bzr.ozlabs.org/')
424
360
eq = self.assertEqualDiff
425
361
eq(t.abspath('.bzr/tree-version'),
426
'http://example.com/.bzr/tree-version')
362
'http://bzr.ozlabs.org/.bzr/tree-version')
428
364
def test_http_impl_urls(self):
429
365
"""There are servers which ask for particular clients to connect"""
430
366
server = self._server()
431
server.start_server()
433
369
url = server.get_url()
434
self.assertTrue(url.startswith('%s://' % self._url_protocol))
370
self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
439
375
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
1048
982
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
984
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1118
985
"""Errors out when range specifiers exceed the limit"""
1188
1053
Only the urllib implementation is tested here.
1057
tests.TestCase.setUp(self)
1062
tests.TestCase.tearDown(self)
1064
def _install_env(self, env):
1065
for name, value in env.iteritems():
1066
self._old_env[name] = osutils.set_or_unset_env(name, value)
1068
def _restore_env(self):
1069
for name, value in self._old_env.iteritems():
1070
osutils.set_or_unset_env(name, value)
1191
1072
def _proxied_request(self):
1192
1073
handler = _urllib2_wrappers.ProxyHandler()
1193
request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1074
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1194
1075
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
1078
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')
1079
self._install_env({'http_proxy': 'http://bar.com'})
1210
1080
request = self._proxied_request()
1211
1081
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1213
1083
def test_invalid_proxy(self):
1214
1084
"""A proxy env variable without scheme"""
1215
self.overrideEnv('http_proxy', 'host:1234')
1085
self._install_env({'http_proxy': 'host:1234'})
1216
1086
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
1089
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1240
1090
"""Tests proxy server.
1245
1095
to the file names).
1248
scenarios = multiply_scenarios(
1249
vary_by_http_client_implementation(),
1250
vary_by_http_protocol_version(),
1253
1098
# FIXME: We don't have an https server available, so we don't
1254
# test https connections. --vila toolongago
1099
# test https connections.
1256
1101
def setUp(self):
1257
1102
super(TestProxyHttpServer, self).setUp()
1258
self.transport_secondary_server = http_utils.ProxyServer
1259
1103
self.build_tree_contents([('foo', 'contents of foo\n'),
1260
1104
('foo-proxied', 'proxied contents of foo\n')])
1261
1105
# Let's setup some attributes for tests
1262
server = self.get_readonly_server()
1263
self.server_host_port = '%s:%d' % (server.host, server.port)
1106
self.server = self.get_readonly_server()
1107
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1264
1108
if self._testing_pycurl():
1265
1109
# Oh my ! pycurl does not check for the port as part of
1266
1110
# no_proxy :-( So we just test the host part
1267
self.no_proxy_host = server.host
1111
self.no_proxy_host = 'localhost'
1269
self.no_proxy_host = self.server_host_port
1113
self.no_proxy_host = self.proxy_address
1270
1114
# The secondary server is the proxy
1271
self.proxy_url = self.get_secondary_url()
1115
self.proxy = self.get_secondary_server()
1116
self.proxy_url = self.proxy.get_url()
1273
1119
def _testing_pycurl(self):
1274
# TODO: This is duplicated for lots of the classes in this file
1275
return (features.pycurl.available()
1276
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())
1120
return pycurl_present and self._transport == PyCurlTransport
1122
def create_transport_secondary_server(self):
1123
"""Creates an http server that will serve files with
1124
'-proxied' appended to their names.
1126
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1128
def _install_env(self, env):
1129
for name, value in env.iteritems():
1130
self._old_env[name] = osutils.set_or_unset_env(name, value)
1132
def _restore_env(self):
1133
for name, value in self._old_env.iteritems():
1134
osutils.set_or_unset_env(name, value)
1136
def proxied_in_env(self, env):
1137
self._install_env(env)
1138
url = self.server.get_url()
1139
t = self._transport(url)
1141
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1145
def not_proxied_in_env(self, env):
1146
self._install_env(env)
1147
url = self.server.get_url()
1148
t = self._transport(url)
1150
self.assertEqual('contents of foo\n', t.get('foo').read())
1286
1154
def test_http_proxy(self):
1287
self.overrideEnv('http_proxy', self.proxy_url)
1288
self.assertProxied()
1155
self.proxied_in_env({'http_proxy': self.proxy_url})
1290
1157
def test_HTTP_PROXY(self):
1291
1158
if self._testing_pycurl():
1294
1161
# about. Should we ?)
1295
1162
raise tests.TestNotApplicable(
1296
1163
'pycurl does not check HTTP_PROXY for security reasons')
1297
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1298
self.assertProxied()
1164
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1300
1166
def test_all_proxy(self):
1301
self.overrideEnv('all_proxy', self.proxy_url)
1302
self.assertProxied()
1167
self.proxied_in_env({'all_proxy': self.proxy_url})
1304
1169
def test_ALL_PROXY(self):
1305
self.overrideEnv('ALL_PROXY', self.proxy_url)
1306
self.assertProxied()
1170
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1308
1172
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()
1173
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1174
'no_proxy': self.no_proxy_host})
1313
1176
def test_HTTP_PROXY_with_NO_PROXY(self):
1314
1177
if self._testing_pycurl():
1315
1178
raise tests.TestNotApplicable(
1316
1179
'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()
1180
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1181
'NO_PROXY': self.no_proxy_host})
1321
1183
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()
1184
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1185
'no_proxy': self.no_proxy_host})
1326
1187
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()
1188
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1189
'NO_PROXY': self.no_proxy_host})
1331
1191
def test_http_proxy_without_scheme(self):
1332
self.overrideEnv('http_proxy', self.server_host_port)
1333
1192
if self._testing_pycurl():
1334
1193
# pycurl *ignores* invalid proxy env variables. If that ever change
1335
1194
# in the future, this test will fail indicating that pycurl do not
1336
1195
# ignore anymore such variables.
1337
self.assertNotProxied()
1196
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1339
self.assertRaises(errors.InvalidURL, self.assertProxied)
1198
self.assertRaises(errors.InvalidURL,
1199
self.proxied_in_env,
1200
{'http_proxy': self.proxy_address})
1342
1203
class TestRanges(http_utils.TestCaseWithWebserver):
1343
1204
"""Test the Range header in GET methods."""
1345
scenarios = multiply_scenarios(
1346
vary_by_http_client_implementation(),
1347
vary_by_http_protocol_version(),
1350
1206
def setUp(self):
1351
1207
http_utils.TestCaseWithWebserver.setUp(self)
1352
1208
self.build_tree_contents([('a', '0123456789')],)
1209
server = self.get_readonly_server()
1210
self.transport = self._transport(server.get_url())
1354
1212
def create_transport_readonly_server(self):
1355
1213
return http_server.HttpServer(protocol_version=self._protocol_version)
1357
1215
def _file_contents(self, relpath, ranges):
1358
t = self.get_readonly_transport()
1359
1216
offsets = [ (start, end - start + 1) for start, end in ranges]
1360
coalesce = t._coalesce_offsets
1217
coalesce = self.transport._coalesce_offsets
1361
1218
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1362
code, data = t._get(relpath, coalesced)
1219
code, data = self.transport._get(relpath, coalesced)
1363
1220
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1364
1221
for start, end in ranges:
1365
1222
data.seek(start)
1366
1223
yield data.read(end - start + 1)
1368
1225
def _file_tail(self, relpath, tail_amount):
1369
t = self.get_readonly_transport()
1370
code, data = t._get(relpath, [], tail_amount)
1226
code, data = self.transport._get(relpath, [], tail_amount)
1371
1227
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1372
1228
data.seek(-tail_amount, 2)
1373
1229
return data.read(tail_amount)
1783
1576
# initial 'who are you' and a second 'who are you' with the new nonce)
1784
1577
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
1581
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(),
1582
"""Test proxy authentication schemes."""
1584
_auth_header = 'Proxy-authorization'
1585
_password_prompt_prefix='Proxy '
1841
1587
def setUp(self):
1842
1588
super(TestProxyAuth, self).setUp()
1590
self.addCleanup(self._restore_env)
1843
1591
# Override the contents to avoid false positives
1844
1592
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1845
1593
('b', 'not proxied contents of b\n'),
1975
1736
def test_probe_smart_server(self):
1976
1737
"""Test error handling against server refusing smart requests."""
1977
t = self.get_readonly_transport()
1738
server = self.get_readonly_server()
1739
t = self._transport(server.get_url())
1978
1740
# No need to build a valid smart request here, the server will not even
1979
1741
# try to interpret it.
1980
1742
self.assertRaises(errors.SmartProtocolError,
1981
1743
t.get_smart_medium().send_http_smart_request,
1985
class Test_redirected_to(tests.TestCase):
1987
scenarios = vary_by_http_client_implementation()
1989
def test_redirected_to_subdir(self):
1990
t = self._transport('http://www.example.com/foo')
1991
r = t._redirected_to('http://www.example.com/foo',
1992
'http://www.example.com/foo/subdir')
1993
self.assertIsInstance(r, type(t))
1994
# Both transports share the some connection
1995
self.assertEqual(t._get_connection(), r._get_connection())
1997
def test_redirected_to_self_with_slash(self):
1998
t = self._transport('http://www.example.com/foo')
1999
r = t._redirected_to('http://www.example.com/foo',
2000
'http://www.example.com/foo/')
2001
self.assertIsInstance(r, type(t))
2002
# Both transports share the some connection (one can argue that we
2003
# should return the exact same transport here, but that seems
2005
self.assertEqual(t._get_connection(), r._get_connection())
2007
def test_redirected_to_host(self):
2008
t = self._transport('http://www.example.com/foo')
2009
r = t._redirected_to('http://www.example.com/foo',
2010
'http://foo.example.com/foo/subdir')
2011
self.assertIsInstance(r, type(t))
2013
def test_redirected_to_same_host_sibling_protocol(self):
2014
t = self._transport('http://www.example.com/foo')
2015
r = t._redirected_to('http://www.example.com/foo',
2016
'https://www.example.com/foo')
2017
self.assertIsInstance(r, type(t))
2019
def test_redirected_to_same_host_different_protocol(self):
2020
t = self._transport('http://www.example.com/foo')
2021
r = t._redirected_to('http://www.example.com/foo',
2022
'ftp://www.example.com/foo')
2023
self.assertNotEquals(type(r), type(t))
2025
def test_redirected_to_different_host_same_user(self):
2026
t = self._transport('http://joe@www.example.com/foo')
2027
r = t._redirected_to('http://www.example.com/foo',
2028
'https://foo.example.com/foo')
2029
self.assertIsInstance(r, type(t))
2030
self.assertEqual(t._parsed_url.user, r._parsed_url.user)
2033
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
2034
"""Request handler for a unique and pre-defined request.
2036
The only thing we care about here is how many bytes travel on the wire. But
2037
since we want to measure it for a real http client, we have to send it
2040
We expect to receive a *single* request nothing more (and we won't even
2041
check what request it is, we just measure the bytes read until an empty
2045
def _handle_one_request(self):
2046
tcs = self.server.test_case_server
2047
requestline = self.rfile.readline()
2048
headers = self.MessageClass(self.rfile, 0)
2049
# We just read: the request, the headers, an empty line indicating the
2050
# end of the headers.
2051
bytes_read = len(requestline)
2052
for line in headers.headers:
2053
bytes_read += len(line)
2054
bytes_read += len('\r\n')
2055
if requestline.startswith('POST'):
2056
# The body should be a single line (or we don't know where it ends
2057
# and we don't want to issue a blocking read)
2058
body = self.rfile.readline()
2059
bytes_read += len(body)
2060
tcs.bytes_read = bytes_read
2062
# We set the bytes written *before* issuing the write, the client is
2063
# supposed to consume every produced byte *before* checking that value.
2065
# Doing the oppposite may lead to test failure: we may be interrupted
2066
# after the write but before updating the value. The client can then
2067
# continue and read the value *before* we can update it. And yes,
2068
# this has been observed -- vila 20090129
2069
tcs.bytes_written = len(tcs.canned_response)
2070
self.wfile.write(tcs.canned_response)
2073
class ActivityServerMixin(object):
2075
def __init__(self, protocol_version):
2076
super(ActivityServerMixin, self).__init__(
2077
request_handler=PredefinedRequestHandler,
2078
protocol_version=protocol_version)
2079
# Bytes read and written by the server
2081
self.bytes_written = 0
2082
self.canned_response = None
2085
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
2089
if features.HTTPSServerFeature.available():
2090
from bzrlib.tests import https_server
2091
class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
2095
class TestActivityMixin(object):
2096
"""Test socket activity reporting.
2098
We use a special purpose server to control the bytes sent and received and
2099
be able to predict the activity on the client socket.
2103
tests.TestCase.setUp(self)
2104
self.server = self._activity_server(self._protocol_version)
2105
self.server.start_server()
2106
_activities = {} # Don't close over self and create a cycle
2107
def report_activity(t, bytes, direction):
2108
count = _activities.get(direction, 0)
2110
_activities[direction] = count
2111
self.activities = _activities
2113
# We override at class level because constructors may propagate the
2114
# bound method and render instance overriding ineffective (an
2115
# 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)
2119
def get_transport(self):
2120
t = self._transport(self.server.get_url())
2121
# FIXME: Needs cleanup -- vila 20100611
2124
def assertActivitiesMatch(self):
2125
self.assertEqual(self.server.bytes_read,
2126
self.activities.get('write', 0), 'written bytes')
2127
self.assertEqual(self.server.bytes_written,
2128
self.activities.get('read', 0), 'read bytes')
2131
self.server.canned_response = '''HTTP/1.1 200 OK\r
2132
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2133
Server: Apache/2.0.54 (Fedora)\r
2134
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2135
ETag: "56691-23-38e9ae00"\r
2136
Accept-Ranges: bytes\r
2137
Content-Length: 35\r
2139
Content-Type: text/plain; charset=UTF-8\r
2141
Bazaar-NG meta directory, format 1
2143
t = self.get_transport()
2144
self.assertEqual('Bazaar-NG meta directory, format 1\n',
2145
t.get('foo/bar').read())
2146
self.assertActivitiesMatch()
2149
self.server.canned_response = '''HTTP/1.1 200 OK\r
2150
Server: SimpleHTTP/0.6 Python/2.5.2\r
2151
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2152
Content-type: application/octet-stream\r
2153
Content-Length: 20\r
2154
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2157
t = self.get_transport()
2158
self.assertTrue(t.has('foo/bar'))
2159
self.assertActivitiesMatch()
2161
def test_readv(self):
2162
self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2163
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2164
Server: Apache/2.0.54 (Fedora)\r
2165
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2166
ETag: "238a3c-16ec2-805c5540"\r
2167
Accept-Ranges: bytes\r
2168
Content-Length: 1534\r
2170
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2173
--418470f848b63279b\r
2174
Content-type: text/plain; charset=UTF-8\r
2175
Content-range: bytes 0-254/93890\r
2177
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2178
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2179
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2180
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2181
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2183
--418470f848b63279b\r
2184
Content-type: text/plain; charset=UTF-8\r
2185
Content-range: bytes 1000-2049/93890\r
2188
mbp@sourcefrog.net-20050311063625-07858525021f270b
2189
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2190
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2191
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2192
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2193
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2194
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2195
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2196
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2197
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2198
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2199
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2200
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2201
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2202
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2203
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2204
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2205
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2206
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2207
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2209
--418470f848b63279b--\r
2211
t = self.get_transport()
2212
# Remember that the request is ignored and that the ranges below
2213
# doesn't have to match the canned response.
2214
l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2215
self.assertEqual(2, len(l))
2216
self.assertActivitiesMatch()
2218
def test_post(self):
2219
self.server.canned_response = '''HTTP/1.1 200 OK\r
2220
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2221
Server: Apache/2.0.54 (Fedora)\r
2222
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2223
ETag: "56691-23-38e9ae00"\r
2224
Accept-Ranges: bytes\r
2225
Content-Length: 35\r
2227
Content-Type: text/plain; charset=UTF-8\r
2229
lalala whatever as long as itsssss
2231
t = self.get_transport()
2232
# We must send a single line of body bytes, see
2233
# PredefinedRequestHandler._handle_one_request
2234
code, f = t._post('abc def end-of-body\n')
2235
self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2236
self.assertActivitiesMatch()
2239
class TestActivity(tests.TestCase, TestActivityMixin):
2241
scenarios = multiply_scenarios(
2242
vary_by_http_activity(),
2243
vary_by_http_protocol_version(),
2247
TestActivityMixin.setUp(self)
2250
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'
2261
self._transport =_urllib.HttpTransport_urllib
2262
TestActivityMixin.setUp(self)
2264
def assertActivitiesMatch(self):
2265
# Nothing to check here
2269
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2270
"""Test authentication on the redirected http server."""
2272
scenarios = vary_by_http_protocol_version()
2274
_auth_header = 'Authorization'
2275
_password_prompt_prefix = ''
2276
_username_prompt_prefix = ''
2277
_auth_server = http_utils.HTTPBasicAuthServer
2278
_transport = _urllib.HttpTransport_urllib
2281
super(TestAuthOnRedirected, self).setUp()
2282
self.build_tree_contents([('a','a'),
2284
('1/a', 'redirected once'),
2286
new_prefix = 'http://%s:%s' % (self.new_server.host,
2287
self.new_server.port)
2288
self.old_server.redirections = [
2289
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2290
self.old_transport = self.get_old_transport()
2291
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
2302
def test_auth_on_redirected_via_do_catching_redirections(self):
2303
self.redirections = 0
2305
def redirected(t, exception, redirection_notice):
2306
self.redirections += 1
2307
redirected_t = t._redirected_to(exception.source, exception.target)
2308
self.addCleanup(redirected_t.disconnect)
2311
stdout = tests.StringIOWrapper()
2312
stderr = tests.StringIOWrapper()
2313
ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2314
stdout=stdout, stderr=stderr)
2315
self.assertEqual('redirected once',
2316
transport.do_catching_redirections(
2317
self.get_a, self.old_transport, redirected).read())
2318
self.assertEqual(1, self.redirections)
2319
# stdin should be empty
2320
self.assertEqual('', ui.ui_factory.stdin.readline())
2321
# stdout should be empty, stderr will contains the prompts
2322
self.assertEqual('', stdout.getvalue())
2324
def test_auth_on_redirected_via_following_redirections(self):
2325
self.new_server.add_user('joe', 'foo')
2326
stdout = tests.StringIOWrapper()
2327
stderr = tests.StringIOWrapper()
2328
ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2329
stdout=stdout, stderr=stderr)
2330
t = self.old_transport
2331
req = RedirectedRequest('GET', t.abspath('a'))
2332
new_prefix = 'http://%s:%s' % (self.new_server.host,
2333
self.new_server.port)
2334
self.old_server.redirections = [
2335
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2336
self.assertEqual('redirected once', t._perform(req).read())
2337
# stdin should be empty
2338
self.assertEqual('', ui.ui_factory.stdin.readline())
2339
# stdout should be empty, stderr will contains the prompts
2340
self.assertEqual('', stdout.getvalue())