66
if features.pycurl.available():
67
60
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 (
62
except errors.DependencyNotPresent:
63
pycurl_present = False
66
class TransportAdapter(tests.TestScenarioApplier):
67
"""Generate the same test for each transport implementation."""
70
transport_scenarios = [
71
('urllib', dict(_transport=_urllib.HttpTransport_urllib,
72
_server=http_server.HttpServer_urllib,
73
_qualified_prefix='http+urllib',)),
76
transport_scenarios.append(
77
('pycurl', dict(_transport=PyCurlTransport,
78
_server=http_server.HttpServer_PyCurl,
79
_qualified_prefix='http+pycurl',)))
80
self.scenarios = transport_scenarios
83
class TransportProtocolAdapter(TransportAdapter):
84
"""Generate the same test for each protocol implementation.
86
In addition to the transport adaptatation that we inherit from.
90
super(TransportProtocolAdapter, self).__init__()
91
protocol_scenarios = [
92
('HTTP/1.0', dict(_protocol_version='HTTP/1.0')),
93
('HTTP/1.1', dict(_protocol_version='HTTP/1.1')),
95
self.scenarios = tests.multiply_scenarios(self.scenarios,
99
class TransportProtocolAuthenticationAdapter(TransportProtocolAdapter):
100
"""Generate the same test for each authentication scheme implementation.
102
In addition to the protocol adaptatation that we inherit from.
106
super(TransportProtocolAuthenticationAdapter, self).__init__()
107
auth_scheme_scenarios = [
108
('basic', dict(_auth_scheme='basic')),
109
('digest', dict(_auth_scheme='digest')),
112
self.scenarios = tests.multiply_scenarios(self.scenarios,
113
auth_scheme_scenarios)
115
def load_tests(standard_tests, module, loader):
116
"""Multiply tests for http clients and protocol versions."""
117
# one for each transport
118
t_adapter = TransportAdapter()
119
t_classes= (TestHttpTransportRegistration,
120
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
122
is_testing_for_transports = tests.condition_isinstance(t_classes)
124
# multiplied by one for each protocol version
125
tp_adapter = TransportProtocolAdapter()
126
tp_classes= (SmartHTTPTunnellingTest,
127
TestDoCatchRedirections,
129
TestHTTPRedirections,
130
TestHTTPSilentRedirections,
131
TestLimitedRangeRequestServer,
135
TestSpecificRequestHandler,
137
is_also_testing_for_protocols = tests.condition_isinstance(tp_classes)
139
# multiplied by one for each authentication scheme
140
tpa_adapter = TransportProtocolAuthenticationAdapter()
141
tpa_classes = (TestAuth,
143
is_also_testing_for_authentication = tests.condition_isinstance(
146
result = loader.suiteClass()
147
for test_class in tests.iter_suite_tests(standard_tests):
148
# Each test class is either standalone or testing for some combination
149
# of transport, protocol version, authentication scheme. Use the right
150
# adpater (or none) depending on the class.
151
if is_testing_for_transports(test_class):
152
result.addTests(t_adapter.adapt(test_class))
153
elif is_also_testing_for_protocols(test_class):
154
result.addTests(tp_adapter.adapt(test_class))
155
elif is_also_testing_for_authentication(test_class):
156
result.addTests(tpa_adapter.adapt(test_class))
158
result.addTest(test_class)
160
162
class FakeManager(object):
185
187
self.received_bytes = ''
189
return '%s://%s:%s/' % (self.scheme, self.host, self.port)
191
def start_server(self):
192
190
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
193
191
self._sock.bind(('127.0.0.1', 0))
194
192
self.host, self.port = self._sock.getsockname()
195
193
self._ready = threading.Event()
196
self._thread = test_server.TestThread(
197
sync_event=self._ready, target=self._accept_read_and_reply)
194
self._thread = threading.Thread(target=self._accept_read_and_reply)
195
self._thread.setDaemon(True)
198
196
self._thread.start()
199
if 'threads' in tests.selftest_debug_flags:
200
sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
203
199
def _accept_read_and_reply(self):
204
200
self._sock.listen(1)
205
201
self._ready.set()
206
conn, address = self._sock.accept()
207
if self._expect_body_tail is not None:
202
self._sock.settimeout(5)
204
conn, address = self._sock.accept()
205
# On win32, the accepted connection will be non-blocking to start
206
# with because we're using settimeout.
207
conn.setblocking(True)
208
208
while not self.received_bytes.endswith(self._expect_body_tail):
209
209
self.received_bytes += conn.recv(4096)
210
210
conn.sendall('HTTP/1.1 200 OK\r\n')
211
except socket.timeout:
212
# Make sure the client isn't stuck waiting for us to e.g. accept.
212
213
self._sock.close()
213
214
except socket.error:
214
215
# 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
221
except socket.error:
224
222
# 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
228
class TestHTTPServer(tests.TestCase):
386
322
def test_url_parsing(self):
387
323
f = FakeManager()
388
324
url = http.extract_auth('http://example.com', f)
389
self.assertEqual('http://example.com', url)
390
self.assertEqual(0, len(f.credentials))
325
self.assertEquals('http://example.com', url)
326
self.assertEquals(0, len(f.credentials))
391
327
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'],
328
'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
329
self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
330
self.assertEquals(1, len(f.credentials))
331
self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
399
335
class TestHttpTransportUrls(tests.TestCase):
400
336
"""Test the http urls."""
402
scenarios = vary_by_http_client_implementation()
404
338
def test_abs_url(self):
405
339
"""Construction of absolute http URLs"""
406
t = self._transport('http://example.com/bzr/bzr.dev/')
340
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
341
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')
342
eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
343
eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
344
eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
411
345
eq(t.abspath('.bzr/1//2/./3'),
412
'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
346
'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
414
348
def test_invalid_http_urls(self):
415
349
"""Trap invalid construction of urls"""
416
self._transport('http://example.com/bzr/bzr.dev/')
350
t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
351
self.assertRaises(errors.InvalidURL,
419
'http://http://example.com/bzr/bzr.dev/')
353
'http://http://bazaar-vcs.org/bzr/bzr.dev/')
421
355
def test_http_root_urls(self):
422
356
"""Construction of URLs from server root"""
423
t = self._transport('http://example.com/')
357
t = self._transport('http://bzr.ozlabs.org/')
424
358
eq = self.assertEqualDiff
425
359
eq(t.abspath('.bzr/tree-version'),
426
'http://example.com/.bzr/tree-version')
360
'http://bzr.ozlabs.org/.bzr/tree-version')
428
362
def test_http_impl_urls(self):
429
363
"""There are servers which ask for particular clients to connect"""
430
364
server = self._server()
431
server.start_server()
433
367
url = server.get_url()
434
self.assertTrue(url.startswith('%s://' % self._url_protocol))
368
self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
439
373
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
1049
987
self.assertEqual('single', t._range_hint)
1052
class TruncatedBeforeBoundaryRequestHandler(
1053
http_server.TestingHTTPRequestHandler):
1054
"""Truncation before a boundary, like in bug 198646"""
1056
_truncated_ranges = 1
1058
def get_multiple_ranges(self, file, file_size, ranges):
1059
self.send_response(206)
1060
self.send_header('Accept-Ranges', 'bytes')
1062
self.send_header('Content-Type',
1063
'multipart/byteranges; boundary=%s' % boundary)
1064
boundary_line = '--%s\r\n' % boundary
1065
# Calculate the Content-Length
1067
for (start, end) in ranges:
1068
content_length += len(boundary_line)
1069
content_length += self._header_line_length(
1070
'Content-type', 'application/octet-stream')
1071
content_length += self._header_line_length(
1072
'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
1073
content_length += len('\r\n') # end headers
1074
content_length += end - start # + 1
1075
content_length += len(boundary_line)
1076
self.send_header('Content-length', content_length)
1079
# Send the multipart body
1081
for (start, end) in ranges:
1082
if cur + self._truncated_ranges >= len(ranges):
1083
# Abruptly ends the response and close the connection
1084
self.close_connection = 1
1086
self.wfile.write(boundary_line)
1087
self.send_header('Content-type', 'application/octet-stream')
1088
self.send_header('Content-Range', 'bytes %d-%d/%d'
1089
% (start, end, file_size))
1091
self.send_range_content(file, start, end - start + 1)
1094
self.wfile.write(boundary_line)
1097
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1098
"""Tests the case of bug 198646, disconnecting before a boundary."""
1100
_req_handler_class = TruncatedBeforeBoundaryRequestHandler
1103
super(TestTruncatedBeforeBoundary, self).setUp()
1104
self.build_tree_contents([('a', '0123456789')],)
1106
def test_readv_with_short_reads(self):
1107
server = self.get_readonly_server()
1108
t = self.get_readonly_transport()
1109
# Force separate ranges for each offset
1110
t._bytes_to_read_before_seek = 0
1111
ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1112
self.assertEqual((0, '0'), ireadv.next())
1113
self.assertEqual((2, '2'), ireadv.next())
1114
self.assertEqual((4, '45'), ireadv.next())
1115
self.assertEqual((9, '9'), ireadv.next())
1118
989
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1119
990
"""Errors out when range specifiers exceed the limit"""
1189
1058
Only the urllib implementation is tested here.
1062
tests.TestCase.setUp(self)
1067
tests.TestCase.tearDown(self)
1069
def _install_env(self, env):
1070
for name, value in env.iteritems():
1071
self._old_env[name] = osutils.set_or_unset_env(name, value)
1073
def _restore_env(self):
1074
for name, value in self._old_env.iteritems():
1075
osutils.set_or_unset_env(name, value)
1192
1077
def _proxied_request(self):
1193
1078
handler = _urllib2_wrappers.ProxyHandler()
1194
request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1079
request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1195
1080
handler.set_proxy(request, 'http')
1198
def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1199
handler = _urllib2_wrappers.ProxyHandler()
1200
self.assertEquals(expected,
1201
handler.evaluate_proxy_bypass(host, no_proxy))
1203
1083
def test_empty_user(self):
1204
self.overrideEnv('http_proxy', 'http://bar.com')
1205
request = self._proxied_request()
1206
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1208
def test_user_with_at(self):
1209
self.overrideEnv('http_proxy',
1210
'http://username@domain:password@proxy_host:1234')
1084
self._install_env({'http_proxy': 'http://bar.com'})
1211
1085
request = self._proxied_request()
1212
1086
self.assertFalse(request.headers.has_key('Proxy-authorization'))
1214
1088
def test_invalid_proxy(self):
1215
1089
"""A proxy env variable without scheme"""
1216
self.overrideEnv('http_proxy', 'host:1234')
1090
self._install_env({'http_proxy': 'host:1234'})
1217
1091
self.assertRaises(errors.InvalidURL, self._proxied_request)
1219
def test_evaluate_proxy_bypass_true(self):
1220
"""The host is not proxied"""
1221
self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1222
self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1224
def test_evaluate_proxy_bypass_false(self):
1225
"""The host is proxied"""
1226
self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1228
def test_evaluate_proxy_bypass_unknown(self):
1229
"""The host is not explicitly proxied"""
1230
self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1231
self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1233
def test_evaluate_proxy_bypass_empty_entries(self):
1234
"""Ignore empty entries"""
1235
self.assertEvaluateProxyBypass(None, 'example.com', '')
1236
self.assertEvaluateProxyBypass(None, 'example.com', ',')
1237
self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1240
1094
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1241
1095
"""Tests proxy server.
1246
1100
to the file names).
1249
scenarios = multiply_scenarios(
1250
vary_by_http_client_implementation(),
1251
vary_by_http_protocol_version(),
1254
1103
# FIXME: We don't have an https server available, so we don't
1255
# test https connections. --vila toolongago
1104
# test https connections.
1257
1106
def setUp(self):
1258
1107
super(TestProxyHttpServer, self).setUp()
1259
self.transport_secondary_server = http_utils.ProxyServer
1260
1108
self.build_tree_contents([('foo', 'contents of foo\n'),
1261
1109
('foo-proxied', 'proxied contents of foo\n')])
1262
1110
# Let's setup some attributes for tests
1263
server = self.get_readonly_server()
1264
self.server_host_port = '%s:%d' % (server.host, server.port)
1111
self.server = self.get_readonly_server()
1112
self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1265
1113
if self._testing_pycurl():
1266
1114
# Oh my ! pycurl does not check for the port as part of
1267
1115
# no_proxy :-( So we just test the host part
1268
self.no_proxy_host = server.host
1116
self.no_proxy_host = 'localhost'
1270
self.no_proxy_host = self.server_host_port
1118
self.no_proxy_host = self.proxy_address
1271
1119
# The secondary server is the proxy
1272
self.proxy_url = self.get_secondary_url()
1120
self.proxy = self.get_secondary_server()
1121
self.proxy_url = self.proxy.get_url()
1274
1124
def _testing_pycurl(self):
1275
# TODO: This is duplicated for lots of the classes in this file
1276
return (features.pycurl.available()
1277
and self._transport == PyCurlTransport)
1279
def assertProxied(self):
1280
t = self.get_readonly_transport()
1281
self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1283
def assertNotProxied(self):
1284
t = self.get_readonly_transport()
1285
self.assertEqual('contents of foo\n', t.get('foo').read())
1125
return pycurl_present and self._transport == PyCurlTransport
1127
def create_transport_secondary_server(self):
1128
"""Creates an http server that will serve files with
1129
'-proxied' appended to their names.
1131
return http_utils.ProxyServer(protocol_version=self._protocol_version)
1133
def _install_env(self, env):
1134
for name, value in env.iteritems():
1135
self._old_env[name] = osutils.set_or_unset_env(name, value)
1137
def _restore_env(self):
1138
for name, value in self._old_env.iteritems():
1139
osutils.set_or_unset_env(name, value)
1141
def proxied_in_env(self, env):
1142
self._install_env(env)
1143
url = self.server.get_url()
1144
t = self._transport(url)
1146
self.assertEqual(t.get('foo').read(), 'proxied contents of foo\n')
1150
def not_proxied_in_env(self, env):
1151
self._install_env(env)
1152
url = self.server.get_url()
1153
t = self._transport(url)
1155
self.assertEqual(t.get('foo').read(), 'contents of foo\n')
1287
1159
def test_http_proxy(self):
1288
self.overrideEnv('http_proxy', self.proxy_url)
1289
self.assertProxied()
1160
self.proxied_in_env({'http_proxy': self.proxy_url})
1291
1162
def test_HTTP_PROXY(self):
1292
1163
if self._testing_pycurl():
1295
1166
# about. Should we ?)
1296
1167
raise tests.TestNotApplicable(
1297
1168
'pycurl does not check HTTP_PROXY for security reasons')
1298
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1299
self.assertProxied()
1169
self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1301
1171
def test_all_proxy(self):
1302
self.overrideEnv('all_proxy', self.proxy_url)
1303
self.assertProxied()
1172
self.proxied_in_env({'all_proxy': self.proxy_url})
1305
1174
def test_ALL_PROXY(self):
1306
self.overrideEnv('ALL_PROXY', self.proxy_url)
1307
self.assertProxied()
1175
self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1309
1177
def test_http_proxy_with_no_proxy(self):
1310
self.overrideEnv('no_proxy', self.no_proxy_host)
1311
self.overrideEnv('http_proxy', self.proxy_url)
1312
self.assertNotProxied()
1178
self.not_proxied_in_env({'http_proxy': self.proxy_url,
1179
'no_proxy': self.no_proxy_host})
1314
1181
def test_HTTP_PROXY_with_NO_PROXY(self):
1315
1182
if self._testing_pycurl():
1316
1183
raise tests.TestNotApplicable(
1317
1184
'pycurl does not check HTTP_PROXY for security reasons')
1318
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1319
self.overrideEnv('HTTP_PROXY', self.proxy_url)
1320
self.assertNotProxied()
1185
self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1186
'NO_PROXY': self.no_proxy_host})
1322
1188
def test_all_proxy_with_no_proxy(self):
1323
self.overrideEnv('no_proxy', self.no_proxy_host)
1324
self.overrideEnv('all_proxy', self.proxy_url)
1325
self.assertNotProxied()
1189
self.not_proxied_in_env({'all_proxy': self.proxy_url,
1190
'no_proxy': self.no_proxy_host})
1327
1192
def test_ALL_PROXY_with_NO_PROXY(self):
1328
self.overrideEnv('NO_PROXY', self.no_proxy_host)
1329
self.overrideEnv('ALL_PROXY', self.proxy_url)
1330
self.assertNotProxied()
1193
self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1194
'NO_PROXY': self.no_proxy_host})
1332
1196
def test_http_proxy_without_scheme(self):
1333
self.overrideEnv('http_proxy', self.server_host_port)
1334
1197
if self._testing_pycurl():
1335
1198
# pycurl *ignores* invalid proxy env variables. If that ever change
1336
1199
# in the future, this test will fail indicating that pycurl do not
1337
1200
# ignore anymore such variables.
1338
self.assertNotProxied()
1201
self.not_proxied_in_env({'http_proxy': self.proxy_address})
1340
self.assertRaises(errors.InvalidURL, self.assertProxied)
1203
self.assertRaises(errors.InvalidURL,
1204
self.proxied_in_env,
1205
{'http_proxy': self.proxy_address})
1343
1208
class TestRanges(http_utils.TestCaseWithWebserver):
1344
1209
"""Test the Range header in GET methods."""
1346
scenarios = multiply_scenarios(
1347
vary_by_http_client_implementation(),
1348
vary_by_http_protocol_version(),
1351
1211
def setUp(self):
1352
1212
http_utils.TestCaseWithWebserver.setUp(self)
1353
1213
self.build_tree_contents([('a', '0123456789')],)
1214
server = self.get_readonly_server()
1215
self.transport = self._transport(server.get_url())
1355
1217
def create_transport_readonly_server(self):
1356
1218
return http_server.HttpServer(protocol_version=self._protocol_version)
1358
1220
def _file_contents(self, relpath, ranges):
1359
t = self.get_readonly_transport()
1360
1221
offsets = [ (start, end - start + 1) for start, end in ranges]
1361
coalesce = t._coalesce_offsets
1222
coalesce = self.transport._coalesce_offsets
1362
1223
coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1363
code, data = t._get(relpath, coalesced)
1224
code, data = self.transport._get(relpath, coalesced)
1364
1225
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1365
1226
for start, end in ranges:
1366
1227
data.seek(start)
1367
1228
yield data.read(end - start + 1)
1369
1230
def _file_tail(self, relpath, tail_amount):
1370
t = self.get_readonly_transport()
1371
code, data = t._get(relpath, [], tail_amount)
1231
code, data = self.transport._get(relpath, [], tail_amount)
1372
1232
self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1373
1233
data.seek(-tail_amount, 2)
1374
1234
return data.read(tail_amount)
1785
1581
# initial 'who are you' and a second 'who are you' with the new nonce)
1786
1582
self.assertEqual(2, self.server.auth_required_errors)
1788
def test_user_from_auth_conf(self):
1789
if self._testing_pycurl():
1790
raise tests.TestNotApplicable(
1791
'pycurl does not support authentication.conf')
1794
self.server.add_user(user, password)
1795
_setup_authentication_config(scheme='http', port=self.server.port,
1796
user=user, password=password)
1797
t = self.get_user_transport(None, None)
1798
# Issue a request to the server to connect
1799
self.assertEqual('contents of a\n', t.get('a').read())
1800
# Only one 'Authentication Required' error should occur
1801
self.assertEqual(1, self.server.auth_required_errors)
1803
def test_no_credential_leaks_in_log(self):
1804
self.overrideAttr(debug, 'debug_flags', set(['http']))
1806
password = 'very-sensitive-password'
1807
self.server.add_user(user, password)
1808
t = self.get_user_transport(user, password)
1809
# Capture the debug calls to mutter
1812
lines = args[0] % args[1:]
1813
# Some calls output multiple lines, just split them now since we
1814
# care about a single one later.
1815
self.mutters.extend(lines.splitlines())
1816
self.overrideAttr(trace, 'mutter', mutter)
1817
# Issue a request to the server to connect
1818
self.assertEqual(True, t.has('a'))
1819
# Only one 'Authentication Required' error should occur
1820
self.assertEqual(1, self.server.auth_required_errors)
1821
# Since the authentification succeeded, there should be a corresponding
1823
sent_auth_headers = [line for line in self.mutters
1824
if line.startswith('> %s' % (self._auth_header,))]
1825
self.assertLength(1, sent_auth_headers)
1826
self.assertStartsWith(sent_auth_headers[0],
1827
'> %s: <masked>' % (self._auth_header,))
1830
1586
class TestProxyAuth(TestAuth):
1831
"""Test proxy authentication schemes.
1833
This inherits from TestAuth to tweak the setUp and filter some failing
1837
scenarios = multiply_scenarios(
1838
vary_by_http_client_implementation(),
1839
vary_by_http_protocol_version(),
1840
vary_by_http_proxy_auth_scheme(),
1587
"""Test proxy authentication schemes."""
1589
_auth_header = 'Proxy-authorization'
1590
_password_prompt_prefix='Proxy '
1843
1592
def setUp(self):
1844
1593
super(TestProxyAuth, self).setUp()
1595
self.addCleanup(self._restore_env)
1845
1596
# Override the contents to avoid false positives
1846
1597
self.build_tree_contents([('a', 'not proxied contents of a\n'),
1847
1598
('b', 'not proxied contents of b\n'),
1964
1719
self.assertEndsWith(response, expected_end_of_response)
1967
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1968
"""No smart server here request handler."""
1971
self.send_error(403, "Forbidden")
1974
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1975
"""Test smart client behaviour against an http server without smarts."""
1977
_req_handler_class = ForbiddenRequestHandler
1979
def test_probe_smart_server(self):
1980
"""Test error handling against server refusing smart requests."""
1981
t = self.get_readonly_transport()
1982
# No need to build a valid smart request here, the server will not even
1983
# try to interpret it.
1984
self.assertRaises(errors.SmartProtocolError,
1985
t.get_smart_medium().send_http_smart_request,
1989
class Test_redirected_to(tests.TestCase):
1991
scenarios = vary_by_http_client_implementation()
1993
def test_redirected_to_subdir(self):
1994
t = self._transport('http://www.example.com/foo')
1995
r = t._redirected_to('http://www.example.com/foo',
1996
'http://www.example.com/foo/subdir')
1997
self.assertIsInstance(r, type(t))
1998
# Both transports share the some connection
1999
self.assertEqual(t._get_connection(), r._get_connection())
2000
self.assertEquals('http://www.example.com/foo/subdir/', r.base)
2002
def test_redirected_to_self_with_slash(self):
2003
t = self._transport('http://www.example.com/foo')
2004
r = t._redirected_to('http://www.example.com/foo',
2005
'http://www.example.com/foo/')
2006
self.assertIsInstance(r, type(t))
2007
# Both transports share the some connection (one can argue that we
2008
# should return the exact same transport here, but that seems
2010
self.assertEqual(t._get_connection(), r._get_connection())
2012
def test_redirected_to_host(self):
2013
t = self._transport('http://www.example.com/foo')
2014
r = t._redirected_to('http://www.example.com/foo',
2015
'http://foo.example.com/foo/subdir')
2016
self.assertIsInstance(r, type(t))
2017
self.assertEquals('http://foo.example.com/foo/subdir/',
2020
def test_redirected_to_same_host_sibling_protocol(self):
2021
t = self._transport('http://www.example.com/foo')
2022
r = t._redirected_to('http://www.example.com/foo',
2023
'https://www.example.com/foo')
2024
self.assertIsInstance(r, type(t))
2025
self.assertEquals('https://www.example.com/foo/',
2028
def test_redirected_to_same_host_different_protocol(self):
2029
t = self._transport('http://www.example.com/foo')
2030
r = t._redirected_to('http://www.example.com/foo',
2031
'ftp://www.example.com/foo')
2032
self.assertNotEquals(type(r), type(t))
2033
self.assertEquals('ftp://www.example.com/foo/', r.external_url())
2035
def test_redirected_to_same_host_specific_implementation(self):
2036
t = self._transport('http://www.example.com/foo')
2037
r = t._redirected_to('http://www.example.com/foo',
2038
'https+urllib://www.example.com/foo')
2039
self.assertEquals('https://www.example.com/foo/', r.external_url())
2041
def test_redirected_to_different_host_same_user(self):
2042
t = self._transport('http://joe@www.example.com/foo')
2043
r = t._redirected_to('http://www.example.com/foo',
2044
'https://foo.example.com/foo')
2045
self.assertIsInstance(r, type(t))
2046
self.assertEqual(t._parsed_url.user, r._parsed_url.user)
2047
self.assertEquals('https://joe@foo.example.com/foo/', r.external_url())
2050
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
2051
"""Request handler for a unique and pre-defined request.
2053
The only thing we care about here is how many bytes travel on the wire. But
2054
since we want to measure it for a real http client, we have to send it
2057
We expect to receive a *single* request nothing more (and we won't even
2058
check what request it is, we just measure the bytes read until an empty
2062
def _handle_one_request(self):
2063
tcs = self.server.test_case_server
2064
requestline = self.rfile.readline()
2065
headers = self.MessageClass(self.rfile, 0)
2066
# We just read: the request, the headers, an empty line indicating the
2067
# end of the headers.
2068
bytes_read = len(requestline)
2069
for line in headers.headers:
2070
bytes_read += len(line)
2071
bytes_read += len('\r\n')
2072
if requestline.startswith('POST'):
2073
# The body should be a single line (or we don't know where it ends
2074
# and we don't want to issue a blocking read)
2075
body = self.rfile.readline()
2076
bytes_read += len(body)
2077
tcs.bytes_read = bytes_read
2079
# We set the bytes written *before* issuing the write, the client is
2080
# supposed to consume every produced byte *before* checking that value.
2082
# Doing the oppposite may lead to test failure: we may be interrupted
2083
# after the write but before updating the value. The client can then
2084
# continue and read the value *before* we can update it. And yes,
2085
# this has been observed -- vila 20090129
2086
tcs.bytes_written = len(tcs.canned_response)
2087
self.wfile.write(tcs.canned_response)
2090
class ActivityServerMixin(object):
2092
def __init__(self, protocol_version):
2093
super(ActivityServerMixin, self).__init__(
2094
request_handler=PredefinedRequestHandler,
2095
protocol_version=protocol_version)
2096
# Bytes read and written by the server
2098
self.bytes_written = 0
2099
self.canned_response = None
2102
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
2106
if features.HTTPSServerFeature.available():
2107
from bzrlib.tests import https_server
2108
class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
2112
class TestActivityMixin(object):
2113
"""Test socket activity reporting.
2115
We use a special purpose server to control the bytes sent and received and
2116
be able to predict the activity on the client socket.
2120
tests.TestCase.setUp(self)
2121
self.server = self._activity_server(self._protocol_version)
2122
self.server.start_server()
2123
_activities = {} # Don't close over self and create a cycle
2124
def report_activity(t, bytes, direction):
2125
count = _activities.get(direction, 0)
2127
_activities[direction] = count
2128
self.activities = _activities
2130
# We override at class level because constructors may propagate the
2131
# bound method and render instance overriding ineffective (an
2132
# alternative would be to define a specific ui factory instead...)
2133
self.overrideAttr(self._transport, '_report_activity', report_activity)
2134
self.addCleanup(self.server.stop_server)
2136
def get_transport(self):
2137
t = self._transport(self.server.get_url())
2138
# FIXME: Needs cleanup -- vila 20100611
2141
def assertActivitiesMatch(self):
2142
self.assertEqual(self.server.bytes_read,
2143
self.activities.get('write', 0), 'written bytes')
2144
self.assertEqual(self.server.bytes_written,
2145
self.activities.get('read', 0), 'read bytes')
2148
self.server.canned_response = '''HTTP/1.1 200 OK\r
2149
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2150
Server: Apache/2.0.54 (Fedora)\r
2151
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2152
ETag: "56691-23-38e9ae00"\r
2153
Accept-Ranges: bytes\r
2154
Content-Length: 35\r
2156
Content-Type: text/plain; charset=UTF-8\r
2158
Bazaar-NG meta directory, format 1
2160
t = self.get_transport()
2161
self.assertEqual('Bazaar-NG meta directory, format 1\n',
2162
t.get('foo/bar').read())
2163
self.assertActivitiesMatch()
2166
self.server.canned_response = '''HTTP/1.1 200 OK\r
2167
Server: SimpleHTTP/0.6 Python/2.5.2\r
2168
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2169
Content-type: application/octet-stream\r
2170
Content-Length: 20\r
2171
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2174
t = self.get_transport()
2175
self.assertTrue(t.has('foo/bar'))
2176
self.assertActivitiesMatch()
2178
def test_readv(self):
2179
self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2180
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2181
Server: Apache/2.0.54 (Fedora)\r
2182
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2183
ETag: "238a3c-16ec2-805c5540"\r
2184
Accept-Ranges: bytes\r
2185
Content-Length: 1534\r
2187
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2190
--418470f848b63279b\r
2191
Content-type: text/plain; charset=UTF-8\r
2192
Content-range: bytes 0-254/93890\r
2194
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2195
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2196
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2197
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2198
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2200
--418470f848b63279b\r
2201
Content-type: text/plain; charset=UTF-8\r
2202
Content-range: bytes 1000-2049/93890\r
2205
mbp@sourcefrog.net-20050311063625-07858525021f270b
2206
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2207
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2208
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2209
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2210
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2211
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2212
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2213
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2214
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2215
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2216
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2217
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2218
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2219
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2220
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2221
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2222
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2223
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2224
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2226
--418470f848b63279b--\r
2228
t = self.get_transport()
2229
# Remember that the request is ignored and that the ranges below
2230
# doesn't have to match the canned response.
2231
l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2232
self.assertEqual(2, len(l))
2233
self.assertActivitiesMatch()
2235
def test_post(self):
2236
self.server.canned_response = '''HTTP/1.1 200 OK\r
2237
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2238
Server: Apache/2.0.54 (Fedora)\r
2239
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2240
ETag: "56691-23-38e9ae00"\r
2241
Accept-Ranges: bytes\r
2242
Content-Length: 35\r
2244
Content-Type: text/plain; charset=UTF-8\r
2246
lalala whatever as long as itsssss
2248
t = self.get_transport()
2249
# We must send a single line of body bytes, see
2250
# PredefinedRequestHandler._handle_one_request
2251
code, f = t._post('abc def end-of-body\n')
2252
self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2253
self.assertActivitiesMatch()
2256
class TestActivity(tests.TestCase, TestActivityMixin):
2258
scenarios = multiply_scenarios(
2259
vary_by_http_activity(),
2260
vary_by_http_protocol_version(),
2264
TestActivityMixin.setUp(self)
2267
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2269
# Unlike TestActivity, we are really testing ReportingFileSocket and
2270
# ReportingSocket, so we don't need all the parametrization. Since
2271
# ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2272
# test them through their use by the transport than directly (that's a
2273
# bit less clean but far more simpler and effective).
2274
_activity_server = ActivityHTTPServer
2275
_protocol_version = 'HTTP/1.1'
2278
self._transport =_urllib.HttpTransport_urllib
2279
TestActivityMixin.setUp(self)
2281
def assertActivitiesMatch(self):
2282
# Nothing to check here
2286
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2287
"""Test authentication on the redirected http server."""
2289
scenarios = vary_by_http_protocol_version()
2291
_auth_header = 'Authorization'
2292
_password_prompt_prefix = ''
2293
_username_prompt_prefix = ''
2294
_auth_server = http_utils.HTTPBasicAuthServer
2295
_transport = _urllib.HttpTransport_urllib
2298
super(TestAuthOnRedirected, self).setUp()
2299
self.build_tree_contents([('a','a'),
2301
('1/a', 'redirected once'),
2303
new_prefix = 'http://%s:%s' % (self.new_server.host,
2304
self.new_server.port)
2305
self.old_server.redirections = [
2306
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2307
self.old_transport = self.get_old_transport()
2308
self.new_server.add_user('joe', 'foo')
2309
cleanup_http_redirection_connections(self)
2311
def create_transport_readonly_server(self):
2312
server = self._auth_server(protocol_version=self._protocol_version)
2313
server._url_protocol = self._url_protocol
2319
def test_auth_on_redirected_via_do_catching_redirections(self):
2320
self.redirections = 0
2322
def redirected(t, exception, redirection_notice):
2323
self.redirections += 1
2324
redirected_t = t._redirected_to(exception.source, exception.target)
2325
self.addCleanup(redirected_t.disconnect)
2328
stdout = tests.StringIOWrapper()
2329
stderr = tests.StringIOWrapper()
2330
ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2331
stdout=stdout, stderr=stderr)
2332
self.assertEqual('redirected once',
2333
transport.do_catching_redirections(
2334
self.get_a, self.old_transport, redirected).read())
2335
self.assertEqual(1, self.redirections)
2336
# stdin should be empty
2337
self.assertEqual('', ui.ui_factory.stdin.readline())
2338
# stdout should be empty, stderr will contains the prompts
2339
self.assertEqual('', stdout.getvalue())
2341
def test_auth_on_redirected_via_following_redirections(self):
2342
self.new_server.add_user('joe', 'foo')
2343
stdout = tests.StringIOWrapper()
2344
stderr = tests.StringIOWrapper()
2345
ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2346
stdout=stdout, stderr=stderr)
2347
t = self.old_transport
2348
req = RedirectedRequest('GET', t.abspath('a'))
2349
new_prefix = 'http://%s:%s' % (self.new_server.host,
2350
self.new_server.port)
2351
self.old_server.redirections = [
2352
('(.*)', r'%s/1\1' % (new_prefix), 301),]
2353
self.assertEqual('redirected once', t._perform(req).read())
2354
# stdin should be empty
2355
self.assertEqual('', ui.ui_factory.stdin.readline())
2356
# stdout should be empty, stderr will contains the prompts
2357
self.assertEqual('', stdout.getvalue())