~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: John Arbash Meinel
  • Date: 2008-10-04 14:10:13 UTC
  • mto: This revision was merged to the branch mainline in revision 3805.
  • Revision ID: john@arbash-meinel.com-20081004141013-yskxjlwtuy2k18ue
Playing around with expanding requests for btree index nodes into neighboring nodes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for HTTP implementations.
18
18
 
23
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
24
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
25
25
 
 
26
from cStringIO import StringIO
26
27
import httplib
 
28
import os
 
29
import select
27
30
import SimpleHTTPServer
28
31
import socket
29
32
import sys
32
35
import bzrlib
33
36
from bzrlib import (
34
37
    bzrdir,
35
 
    cethread,
36
38
    config,
37
 
    debug,
38
39
    errors,
39
40
    osutils,
40
41
    remote as _mod_remote,
41
42
    tests,
42
 
    trace,
43
43
    transport,
44
44
    ui,
 
45
    urlutils,
45
46
    )
46
47
from bzrlib.tests import (
47
 
    features,
48
48
    http_server,
49
49
    http_utils,
50
 
    test_server,
51
 
    )
52
 
from bzrlib.tests.scenarios import (
53
 
    load_tests_apply_scenarios,
54
 
    multiply_scenarios,
55
50
    )
56
51
from bzrlib.transport import (
57
52
    http,
63
58
    )
64
59
 
65
60
 
66
 
if features.pycurl.available():
 
61
try:
67
62
    from bzrlib.transport.http._pycurl import PyCurlTransport
68
 
 
69
 
 
70
 
load_tests = load_tests_apply_scenarios
71
 
 
72
 
 
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',)),
79
 
        ]
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
86
 
 
87
 
 
88
 
def vary_by_http_protocol_version():
89
 
    """Test on http/1.0 and 1.1"""
90
 
    return [
91
 
        ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
92
 
        ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
93
 
        ]
94
 
 
95
 
 
96
 
def vary_by_http_auth_scheme():
97
 
    scenarios = [
98
 
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
99
 
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
100
 
        ('basicdigest',
101
 
            dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
102
 
        ]
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='')
108
 
    return scenarios
109
 
 
110
 
 
111
 
def vary_by_http_proxy_auth_scheme():
112
 
    scenarios = [
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)),
117
 
        ]
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 ')
123
 
    return scenarios
124
 
 
125
 
 
126
 
def vary_by_http_activity():
127
 
    activity_scenarios = [
128
 
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
129
 
                            _transport=_urllib.HttpTransport_urllib,)),
130
 
        ]
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 (
141
 
                ssl_certs,
 
63
    pycurl_present = True
 
64
except errors.DependencyNotPresent:
 
65
    pycurl_present = False
 
66
 
 
67
 
 
68
class TransportAdapter(tests.TestScenarioApplier):
 
69
    """Generate the same test for each transport implementation."""
 
70
 
 
71
    def __init__(self):
 
72
        transport_scenarios = [
 
73
            ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
 
74
                            _server=http_server.HttpServer_urllib,
 
75
                            _qualified_prefix='http+urllib',)),
 
76
            ]
 
77
        if pycurl_present:
 
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
 
83
 
 
84
 
 
85
class TransportProtocolAdapter(TransportAdapter):
 
86
    """Generate the same test for each protocol implementation.
 
87
 
 
88
    In addition to the transport adaptatation that we inherit from.
 
89
    """
 
90
 
 
91
    def __init__(self):
 
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')),
 
96
            ]
 
97
        self.scenarios = tests.multiply_scenarios(self.scenarios,
 
98
                                                  protocol_scenarios)
 
99
 
 
100
 
 
101
class TransportProtocolAuthenticationAdapter(TransportProtocolAdapter):
 
102
    """Generate the same test for each authentication scheme implementation.
 
103
 
 
104
    In addition to the protocol adaptatation that we inherit from.
 
105
    """
 
106
 
 
107
    def __init__(self):
 
108
        super(TransportProtocolAuthenticationAdapter, self).__init__()
 
109
        auth_scheme_scenarios = [
 
110
            ('basic', dict(_auth_scheme='basic')),
 
111
            ('digest', dict(_auth_scheme='digest')),
 
112
            ]
 
113
 
 
114
        self.scenarios = tests.multiply_scenarios(self.scenarios,
 
115
                                                  auth_scheme_scenarios)
 
116
 
 
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,
142
123
                )
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):
148
 
 
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'))
153
 
 
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)
 
125
 
 
126
    # multiplied by one for each protocol version
 
127
    tp_adapter = TransportProtocolAdapter()
 
128
    tp_classes= (SmartHTTPTunnellingTest,
 
129
                 TestDoCatchRedirections,
 
130
                 TestHTTPConnections,
 
131
                 TestHTTPRedirections,
 
132
                 TestHTTPSilentRedirections,
 
133
                 TestLimitedRangeRequestServer,
 
134
                 TestPost,
 
135
                 TestProxyHttpServer,
 
136
                 TestRanges,
 
137
                 TestSpecificRequestHandler,
 
138
                 )
 
139
    is_also_testing_for_protocols = tests.condition_isinstance(tp_classes)
 
140
 
 
141
    # multiplied by one for each authentication scheme
 
142
    tpa_adapter = TransportProtocolAuthenticationAdapter()
 
143
    tpa_classes = (TestAuth,
 
144
                   )
 
145
    is_also_testing_for_authentication = tests.condition_isinstance(
 
146
        tpa_classes)
 
147
 
 
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))
 
159
        else:
 
160
            result.addTest(test_class)
 
161
    return result
158
162
 
159
163
 
160
164
class FakeManager(object):
168
172
 
169
173
class RecordingServer(object):
170
174
    """A fake HTTP server.
171
 
 
 
175
    
172
176
    It records the bytes sent to it, and replies with a 200.
173
177
    """
174
178
 
175
 
    def __init__(self, expect_body_tail=None, scheme=''):
 
179
    def __init__(self, expect_body_tail=None):
176
180
        """Constructor.
177
181
 
178
182
        :type expect_body_tail: str
183
187
        self.host = None
184
188
        self.port = None
185
189
        self.received_bytes = ''
186
 
        self.scheme = scheme
187
 
 
188
 
    def get_url(self):
189
 
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
190
 
 
191
 
    def start_server(self):
 
190
 
 
191
    def setUp(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,))
201
 
        self._ready.wait()
 
199
        self._ready.wait(5)
202
200
 
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)
 
205
        try:
 
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')
211
 
        try:
 
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.
215
218
            pass
216
219
 
217
 
    def stop_server(self):
 
220
    def tearDown(self):
218
221
        try:
219
 
            # Issue a fake connection to wake up the server and allow it to
220
 
            # finish quickly
221
 
            fake_conn = osutils.connect_socket((self.host, self.port))
222
 
            fake_conn.close()
 
222
            self._sock.close()
223
223
        except socket.error:
224
224
            # We might have already closed it.  We don't care.
225
225
            pass
226
226
        self.host = None
227
227
        self.port = None
228
 
        self._thread.join()
229
 
        if 'threads' in tests.selftest_debug_flags:
230
 
            sys.stderr.write('Thread  joined: %s\n' % (self._thread.ident,))
231
 
 
232
 
 
233
 
class TestAuthHeader(tests.TestCase):
234
 
 
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)
240
 
 
241
 
    def test_empty_header(self):
242
 
        scheme, remainder = self.parse_header('')
243
 
        self.assertEqual('', scheme)
244
 
        self.assertIs(None, remainder)
245
 
 
246
 
    def test_negotiate_header(self):
247
 
        scheme, remainder = self.parse_header('Negotiate')
248
 
        self.assertEqual('negotiate', scheme)
249
 
        self.assertIs(None, remainder)
250
 
 
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)
256
 
 
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)
264
 
 
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)
270
 
 
271
 
 
272
 
class TestHTTPRangeParsing(tests.TestCase):
273
 
 
274
 
    def setUp(self):
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
281
 
 
282
 
        self.req_handler = RequestHandler(None, None, None)
283
 
 
284
 
    def assertRanges(self, ranges, header, file_size):
285
 
        self.assertEquals(ranges,
286
 
                          self.req_handler._parse_ranges(header, file_size))
287
 
 
288
 
    def test_simple_range(self):
289
 
        self.assertRanges([(0,2)], 'bytes=0-2', 12)
290
 
 
291
 
    def test_tail(self):
292
 
        self.assertRanges([(8, 11)], 'bytes=-4', 12)
293
 
 
294
 
    def test_tail_bigger_than_file(self):
295
 
        self.assertRanges([(0, 11)], 'bytes=-99', 12)
296
 
 
297
 
    def test_range_without_end(self):
298
 
        self.assertRanges([(4, 11)], 'bytes=4-', 12)
299
 
 
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)
304
228
 
305
229
 
306
230
class TestHTTPServer(tests.TestCase):
311
235
 
312
236
            protocol_version = 'HTTP/0.1'
313
237
 
314
 
        self.assertRaises(httplib.UnknownProtocol,
315
 
                          http_server.HttpServer, BogusRequestHandler)
 
238
        server = http_server.HttpServer(BogusRequestHandler)
 
239
        try:
 
240
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
241
        except:
 
242
            server.tearDown()
 
243
            self.fail('HTTP Server creation did not raise UnknownProtocol')
316
244
 
317
245
    def test_force_invalid_protocol(self):
318
 
        self.assertRaises(httplib.UnknownProtocol,
319
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
246
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
247
        try:
 
248
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
249
        except:
 
250
            server.tearDown()
 
251
            self.fail('HTTP Server creation did not raise UnknownProtocol')
320
252
 
321
253
    def test_server_start_and_stop(self):
322
254
        server = http_server.HttpServer()
323
 
        self.addCleanup(server.stop_server)
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)
 
255
        server.setUp()
 
256
        self.assertTrue(server._http_running)
 
257
        server.tearDown()
 
258
        self.assertFalse(server._http_running)
328
259
 
329
260
    def test_create_http_server_one_zero(self):
330
261
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
332
263
            protocol_version = 'HTTP/1.0'
333
264
 
334
265
        server = http_server.HttpServer(RequestHandlerOneZero)
335
 
        self.start_server(server)
336
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
266
        server.setUp()
 
267
        self.addCleanup(server.tearDown)
 
268
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
337
269
 
338
270
    def test_create_http_server_one_one(self):
339
271
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
341
273
            protocol_version = 'HTTP/1.1'
342
274
 
343
275
        server = http_server.HttpServer(RequestHandlerOneOne)
344
 
        self.start_server(server)
345
 
        self.assertIsInstance(server.server,
 
276
        server.setUp()
 
277
        self.addCleanup(server.tearDown)
 
278
        self.assertIsInstance(server._httpd,
346
279
                              http_server.TestingThreadingHTTPServer)
347
280
 
348
281
    def test_create_http_server_force_one_one(self):
352
285
 
353
286
        server = http_server.HttpServer(RequestHandlerOneZero,
354
287
                                        protocol_version='HTTP/1.1')
355
 
        self.start_server(server)
356
 
        self.assertIsInstance(server.server,
 
288
        server.setUp()
 
289
        self.addCleanup(server.tearDown)
 
290
        self.assertIsInstance(server._httpd,
357
291
                              http_server.TestingThreadingHTTPServer)
358
292
 
359
293
    def test_create_http_server_force_one_zero(self):
363
297
 
364
298
        server = http_server.HttpServer(RequestHandlerOneOne,
365
299
                                        protocol_version='HTTP/1.0')
366
 
        self.start_server(server)
367
 
        self.assertIsInstance(server.server,
 
300
        server.setUp()
 
301
        self.addCleanup(server.tearDown)
 
302
        self.assertIsInstance(server._httpd,
368
303
                              http_server.TestingHTTPServer)
369
304
 
370
305
 
372
307
    """Test case to inherit from if pycurl is present"""
373
308
 
374
309
    def _get_pycurl_maybe(self):
375
 
        self.requireFeature(features.pycurl)
376
 
        return PyCurlTransport
 
310
        try:
 
311
            from bzrlib.transport.http._pycurl import PyCurlTransport
 
312
            return PyCurlTransport
 
313
        except errors.DependencyNotPresent:
 
314
            raise tests.TestSkipped('pycurl not present')
377
315
 
378
316
    _transport = property(_get_pycurl_maybe)
379
317
 
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'],
396
 
                         f.credentials[0])
 
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'],
 
334
                          f.credentials[0])
397
335
 
398
336
 
399
337
class TestHttpTransportUrls(tests.TestCase):
400
338
    """Test the http urls."""
401
339
 
402
 
    scenarios = vary_by_http_client_implementation()
403
 
 
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')
413
349
 
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,
418
354
                          self._transport,
419
 
                          'http://http://example.com/bzr/bzr.dev/')
 
355
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
420
356
 
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')
427
363
 
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()
432
367
        try:
 
368
            server.setUp()
433
369
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
370
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
371
        finally:
436
 
            server.stop_server()
 
372
            server.tearDown()
437
373
 
438
374
 
439
375
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
448
384
        https by supplying a fake version_info that do not
449
385
        support it.
450
386
        """
451
 
        self.requireFeature(features.pycurl)
452
 
        # Import the module locally now that we now it's available.
453
 
        pycurl = features.pycurl.module
 
387
        try:
 
388
            import pycurl
 
389
        except ImportError:
 
390
            raise tests.TestSkipped('pycurl not present')
454
391
 
455
 
        self.overrideAttr(pycurl, 'version_info',
456
 
                          # Fake the pycurl version_info This was taken from
457
 
                          # a windows pycurl without SSL (thanks to bialix)
458
 
                          lambda : (2,
459
 
                                    '7.13.2',
460
 
                                    462082,
461
 
                                    'i386-pc-win32',
462
 
                                    2576,
463
 
                                    None,
464
 
                                    0,
465
 
                                    None,
466
 
                                    ('ftp', 'gopher', 'telnet',
467
 
                                     'dict', 'ldap', 'http', 'file'),
468
 
                                    None,
469
 
                                    0,
470
 
                                    None))
471
 
        self.assertRaises(errors.DependencyNotPresent, self._transport,
472
 
                          'https://launchpad.net')
 
392
        version_info_orig = pycurl.version_info
 
393
        try:
 
394
            # Now that we have pycurl imported, we can fake its version_info
 
395
            # This was taken from a windows pycurl without SSL
 
396
            # (thanks to bialix)
 
397
            pycurl.version_info = lambda : (2,
 
398
                                            '7.13.2',
 
399
                                            462082,
 
400
                                            'i386-pc-win32',
 
401
                                            2576,
 
402
                                            None,
 
403
                                            0,
 
404
                                            None,
 
405
                                            ('ftp', 'gopher', 'telnet',
 
406
                                             'dict', 'ldap', 'http', 'file'),
 
407
                                            None,
 
408
                                            0,
 
409
                                            None)
 
410
            self.assertRaises(errors.DependencyNotPresent, self._transport,
 
411
                              'https://launchpad.net')
 
412
        finally:
 
413
            # Restore the right function
 
414
            pycurl.version_info = version_info_orig
473
415
 
474
416
 
475
417
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
476
418
    """Test the http connections."""
477
419
 
478
 
    scenarios = multiply_scenarios(
479
 
        vary_by_http_client_implementation(),
480
 
        vary_by_http_protocol_version(),
481
 
        )
482
 
 
483
420
    def setUp(self):
484
421
        http_utils.TestCaseWithWebserver.setUp(self)
485
422
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
487
424
 
488
425
    def test_http_has(self):
489
426
        server = self.get_readonly_server()
490
 
        t = self.get_readonly_transport()
 
427
        t = self._transport(server.get_url())
491
428
        self.assertEqual(t.has('foo/bar'), True)
492
429
        self.assertEqual(len(server.logs), 1)
493
430
        self.assertContainsRe(server.logs[0],
495
432
 
496
433
    def test_http_has_not_found(self):
497
434
        server = self.get_readonly_server()
498
 
        t = self.get_readonly_transport()
 
435
        t = self._transport(server.get_url())
499
436
        self.assertEqual(t.has('not-found'), False)
500
437
        self.assertContainsRe(server.logs[1],
501
438
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
502
439
 
503
440
    def test_http_get(self):
504
441
        server = self.get_readonly_server()
505
 
        t = self.get_readonly_transport()
 
442
        t = self._transport(server.get_url())
506
443
        fp = t.get('foo/bar')
507
444
        self.assertEqualDiff(
508
445
            fp.read(),
530
467
class TestHttpTransportRegistration(tests.TestCase):
531
468
    """Test registrations of various http implementations"""
532
469
 
533
 
    scenarios = vary_by_http_client_implementation()
534
 
 
535
470
    def test_http_registered(self):
536
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
471
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
537
472
        self.assertIsInstance(t, transport.Transport)
538
473
        self.assertIsInstance(t, self._transport)
539
474
 
540
475
 
541
476
class TestPost(tests.TestCase):
542
477
 
543
 
    scenarios = multiply_scenarios(
544
 
        vary_by_http_client_implementation(),
545
 
        vary_by_http_protocol_version(),
546
 
        )
547
 
 
548
478
    def test_post_body_is_received(self):
549
 
        server = RecordingServer(expect_body_tail='end-of-body',
550
 
                                 scheme=self._url_protocol)
551
 
        self.start_server(server)
552
 
        url = server.get_url()
553
 
        # FIXME: needs a cleanup -- vila 20100611
554
 
        http_transport = transport.get_transport(url)
 
479
        server = RecordingServer(expect_body_tail='end-of-body')
 
480
        server.setUp()
 
481
        self.addCleanup(server.tearDown)
 
482
        scheme = self._qualified_prefix
 
483
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
 
484
        http_transport = self._transport(url)
555
485
        code, response = http_transport._post('abc def end-of-body')
556
486
        self.assertTrue(
557
487
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
558
488
        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
489
        # The transport should not be assuming that the server can accept
562
490
        # chunked encoding the first time it connects, because HTTP/1.1, so we
563
491
        # check for the literal string.
599
527
    Daughter classes are expected to override _req_handler_class
600
528
    """
601
529
 
602
 
    scenarios = multiply_scenarios(
603
 
        vary_by_http_client_implementation(),
604
 
        vary_by_http_protocol_version(),
605
 
        )
606
 
 
607
530
    # Provide a useful default
608
531
    _req_handler_class = http_server.TestingHTTPRequestHandler
609
532
 
610
533
    def create_transport_readonly_server(self):
611
 
        server = http_server.HttpServer(self._req_handler_class,
612
 
                                        protocol_version=self._protocol_version)
613
 
        server._url_protocol = self._url_protocol
614
 
        return server
 
534
        return http_server.HttpServer(self._req_handler_class,
 
535
                                      protocol_version=self._protocol_version)
615
536
 
616
537
    def _testing_pycurl(self):
617
 
        # TODO: This is duplicated for lots of the classes in this file
618
 
        return (features.pycurl.available()
619
 
                and self._transport == PyCurlTransport)
 
538
        return pycurl_present and self._transport == PyCurlTransport
620
539
 
621
540
 
622
541
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
623
542
    """Whatever request comes in, close the connection"""
624
543
 
625
 
    def _handle_one_request(self):
 
544
    def handle_one_request(self):
626
545
        """Handle a single HTTP request, by abruptly closing the connection"""
627
546
        self.close_connection = 1
628
547
 
633
552
    _req_handler_class = WallRequestHandler
634
553
 
635
554
    def test_http_has(self):
636
 
        t = self.get_readonly_transport()
 
555
        server = self.get_readonly_server()
 
556
        t = self._transport(server.get_url())
637
557
        # Unfortunately httplib (see HTTPResponse._read_status
638
558
        # for details) make no distinction between a closed
639
559
        # socket and badly formatted status line, so we can't
640
560
        # just test for ConnectionError, we have to test
641
 
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
642
 
        # instead of ConnectionError too.
643
 
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
644
 
                            errors.InvalidHttpResponse),
 
561
        # InvalidHttpResponse too.
 
562
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
645
563
                          t.has, 'foo/bar')
646
564
 
647
565
    def test_http_get(self):
648
 
        t = self.get_readonly_transport()
649
 
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
650
 
                           errors.InvalidHttpResponse),
 
566
        server = self.get_readonly_server()
 
567
        t = self._transport(server.get_url())
 
568
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
651
569
                          t.get, 'foo/bar')
652
570
 
653
571
 
668
586
    _req_handler_class = BadStatusRequestHandler
669
587
 
670
588
    def test_http_has(self):
671
 
        t = self.get_readonly_transport()
 
589
        server = self.get_readonly_server()
 
590
        t = self._transport(server.get_url())
672
591
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
673
592
 
674
593
    def test_http_get(self):
675
 
        t = self.get_readonly_transport()
 
594
        server = self.get_readonly_server()
 
595
        t = self._transport(server.get_url())
676
596
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
677
597
 
678
598
 
683
603
        """Fakes handling a single HTTP request, returns a bad status"""
684
604
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
685
605
        self.wfile.write("Invalid status line\r\n")
686
 
        # If we don't close the connection pycurl will hang. Since this is a
687
 
        # stress test we don't *have* to respect the protocol, but we don't
688
 
        # have to sabotage it too much either.
689
 
        self.close_connection = True
690
606
        return False
691
607
 
692
608
 
698
614
 
699
615
    _req_handler_class = InvalidStatusRequestHandler
700
616
 
 
617
    def test_http_has(self):
 
618
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
619
            raise tests.KnownFailure(
 
620
                'pycurl hangs if the server send back garbage')
 
621
        super(TestInvalidStatusServer, self).test_http_has()
 
622
 
 
623
    def test_http_get(self):
 
624
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
625
            raise tests.KnownFailure(
 
626
                'pycurl hangs if the server send back garbage')
 
627
        super(TestInvalidStatusServer, self).test_http_get()
 
628
 
701
629
 
702
630
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
703
631
    """Whatever request comes in, returns a bad protocol version"""
719
647
    _req_handler_class = BadProtocolRequestHandler
720
648
 
721
649
    def setUp(self):
722
 
        if self._testing_pycurl():
 
650
        if pycurl_present and self._transport == PyCurlTransport:
723
651
            raise tests.TestNotApplicable(
724
652
                "pycurl doesn't check the protocol version")
725
653
        super(TestBadProtocolServer, self).setUp()
726
654
 
727
655
    def test_http_has(self):
728
 
        t = self.get_readonly_transport()
 
656
        server = self.get_readonly_server()
 
657
        t = self._transport(server.get_url())
729
658
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
730
659
 
731
660
    def test_http_get(self):
732
 
        t = self.get_readonly_transport()
 
661
        server = self.get_readonly_server()
 
662
        t = self._transport(server.get_url())
733
663
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
734
664
 
735
665
 
749
679
    _req_handler_class = ForbiddenRequestHandler
750
680
 
751
681
    def test_http_has(self):
752
 
        t = self.get_readonly_transport()
 
682
        server = self.get_readonly_server()
 
683
        t = self._transport(server.get_url())
753
684
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
754
685
 
755
686
    def test_http_get(self):
756
 
        t = self.get_readonly_transport()
 
687
        server = self.get_readonly_server()
 
688
        t = self._transport(server.get_url())
757
689
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
758
690
 
759
691
 
765
697
        self.assertEqual(None, server.host)
766
698
        self.assertEqual(None, server.port)
767
699
 
768
 
    def test_setUp_and_stop(self):
 
700
    def test_setUp_and_tearDown(self):
769
701
        server = RecordingServer(expect_body_tail=None)
770
 
        server.start_server()
 
702
        server.setUp()
771
703
        try:
772
704
            self.assertNotEqual(None, server.host)
773
705
            self.assertNotEqual(None, server.port)
774
706
        finally:
775
 
            server.stop_server()
 
707
            server.tearDown()
776
708
        self.assertEqual(None, server.host)
777
709
        self.assertEqual(None, server.port)
778
710
 
779
711
    def test_send_receive_bytes(self):
780
 
        server = RecordingServer(expect_body_tail='c', scheme='http')
781
 
        self.start_server(server)
 
712
        server = RecordingServer(expect_body_tail='c')
 
713
        server.setUp()
 
714
        self.addCleanup(server.tearDown)
782
715
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
783
716
        sock.connect((server.host, server.port))
784
717
        sock.sendall('abc')
798
731
        self.build_tree_contents([('a', '0123456789')],)
799
732
 
800
733
    def test_readv(self):
801
 
        t = self.get_readonly_transport()
 
734
        server = self.get_readonly_server()
 
735
        t = self._transport(server.get_url())
802
736
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
803
737
        self.assertEqual(l[0], (0, '0'))
804
738
        self.assertEqual(l[1], (1, '1'))
806
740
        self.assertEqual(l[3], (9, '9'))
807
741
 
808
742
    def test_readv_out_of_order(self):
809
 
        t = self.get_readonly_transport()
 
743
        server = self.get_readonly_server()
 
744
        t = self._transport(server.get_url())
810
745
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
811
746
        self.assertEqual(l[0], (1, '1'))
812
747
        self.assertEqual(l[1], (9, '9'))
814
749
        self.assertEqual(l[3], (3, '34'))
815
750
 
816
751
    def test_readv_invalid_ranges(self):
817
 
        t = self.get_readonly_transport()
 
752
        server = self.get_readonly_server()
 
753
        t = self._transport(server.get_url())
818
754
 
819
755
        # This is intentionally reading off the end of the file
820
756
        # since we are sure that it cannot get there
828
764
 
829
765
    def test_readv_multiple_get_requests(self):
830
766
        server = self.get_readonly_server()
831
 
        t = self.get_readonly_transport()
 
767
        t = self._transport(server.get_url())
832
768
        # force transport to issue multiple requests
833
769
        t._max_readv_combine = 1
834
770
        t._max_get_ranges = 1
842
778
 
843
779
    def test_readv_get_max_size(self):
844
780
        server = self.get_readonly_server()
845
 
        t = self.get_readonly_transport()
 
781
        t = self._transport(server.get_url())
846
782
        # force transport to issue multiple requests by limiting the number of
847
783
        # bytes by request. Note that this apply to coalesced offsets only, a
848
784
        # single range will keep its size even if bigger than the limit.
857
793
 
858
794
    def test_complete_readv_leave_pipe_clean(self):
859
795
        server = self.get_readonly_server()
860
 
        t = self.get_readonly_transport()
 
796
        t = self._transport(server.get_url())
861
797
        # force transport to issue multiple requests
862
798
        t._get_max_size = 2
863
 
        list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
 
799
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
864
800
        # The server should have issued 3 requests
865
801
        self.assertEqual(3, server.GET_request_nb)
866
802
        self.assertEqual('0123456789', t.get_bytes('a'))
868
804
 
869
805
    def test_incomplete_readv_leave_pipe_clean(self):
870
806
        server = self.get_readonly_server()
871
 
        t = self.get_readonly_transport()
 
807
        t = self._transport(server.get_url())
872
808
        # force transport to issue multiple requests
873
809
        t._get_max_size = 2
874
810
        # Don't collapse readv results into a list so that we leave unread
875
811
        # bytes on the socket
876
812
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
877
813
        self.assertEqual((0, '0'), ireadv.next())
878
 
        # The server should have issued one request so far
 
814
        # The server should have issued one request so far 
879
815
        self.assertEqual(1, server.GET_request_nb)
880
816
        self.assertEqual('0123456789', t.get_bytes('a'))
881
817
        # get_bytes issued an additional request, the readv pending ones are
943
879
    def get_multiple_ranges(self, file, file_size, ranges):
944
880
        self.send_response(206)
945
881
        self.send_header('Accept-Ranges', 'bytes')
946
 
        # XXX: this is strange; the 'random' name below seems undefined and
947
 
        # yet the tests pass -- mbp 2010-10-11 bug 658773
948
882
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
949
883
        self.send_header("Content-Type",
950
884
                         "multipart/byteranges; boundary=%s" % boundary)
1012
946
                return
1013
947
            self.send_range_content(file, start, end - start + 1)
1014
948
            cur += 1
1015
 
        # Final boundary
 
949
        # No final boundary
1016
950
        self.wfile.write(boundary_line)
1017
951
 
1018
952
 
1026
960
 
1027
961
    def test_readv_with_short_reads(self):
1028
962
        server = self.get_readonly_server()
1029
 
        t = self.get_readonly_transport()
 
963
        t = self._transport(server.get_url())
1030
964
        # Force separate ranges for each offset
1031
965
        t._bytes_to_read_before_seek = 0
1032
966
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1047
981
        # that mode
1048
982
        self.assertEqual('single', t._range_hint)
1049
983
 
1050
 
 
1051
 
class TruncatedBeforeBoundaryRequestHandler(
1052
 
    http_server.TestingHTTPRequestHandler):
1053
 
    """Truncation before a boundary, like in bug 198646"""
1054
 
 
1055
 
    _truncated_ranges = 1
1056
 
 
1057
 
    def get_multiple_ranges(self, file, file_size, ranges):
1058
 
        self.send_response(206)
1059
 
        self.send_header('Accept-Ranges', 'bytes')
1060
 
        boundary = 'tagada'
1061
 
        self.send_header('Content-Type',
1062
 
                         'multipart/byteranges; boundary=%s' % boundary)
1063
 
        boundary_line = '--%s\r\n' % boundary
1064
 
        # Calculate the Content-Length
1065
 
        content_length = 0
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)
1076
 
        self.end_headers()
1077
 
 
1078
 
        # Send the multipart body
1079
 
        cur = 0
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
1084
 
                return
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))
1089
 
            self.end_headers()
1090
 
            self.send_range_content(file, start, end - start + 1)
1091
 
            cur += 1
1092
 
        # Final boundary
1093
 
        self.wfile.write(boundary_line)
1094
 
 
1095
 
 
1096
 
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1097
 
    """Tests the case of bug 198646, disconnecting before a boundary."""
1098
 
 
1099
 
    _req_handler_class = TruncatedBeforeBoundaryRequestHandler
1100
 
 
1101
 
    def setUp(self):
1102
 
        super(TestTruncatedBeforeBoundary, self).setUp()
1103
 
        self.build_tree_contents([('a', '0123456789')],)
1104
 
 
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())
1115
 
 
1116
 
 
1117
984
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1118
985
    """Errors out when range specifiers exceed the limit"""
1119
986
 
1143
1010
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1144
1011
    """Tests readv requests against a server erroring out on too much ranges."""
1145
1012
 
1146
 
    scenarios = multiply_scenarios(
1147
 
        vary_by_http_client_implementation(),
1148
 
        vary_by_http_protocol_version(),
1149
 
        )
1150
 
 
1151
1013
    # Requests with more range specifiers will error out
1152
1014
    range_limit = 3
1153
1015
 
1155
1017
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1156
1018
                                      protocol_version=self._protocol_version)
1157
1019
 
 
1020
    def get_transport(self):
 
1021
        return self._transport(self.get_readonly_server().get_url())
 
1022
 
1158
1023
    def setUp(self):
1159
1024
        http_utils.TestCaseWithWebserver.setUp(self)
1160
1025
        # We need to manipulate ranges that correspond to real chunks in the
1164
1029
        self.build_tree_contents([('a', content)],)
1165
1030
 
1166
1031
    def test_few_ranges(self):
1167
 
        t = self.get_readonly_transport()
 
1032
        t = self.get_transport()
1168
1033
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1169
1034
        self.assertEqual(l[0], (0, '0000'))
1170
1035
        self.assertEqual(l[1], (1024, '0001'))
1171
1036
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1172
1037
 
1173
1038
    def test_more_ranges(self):
1174
 
        t = self.get_readonly_transport()
 
1039
        t = self.get_transport()
1175
1040
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1176
1041
        self.assertEqual(l[0], (0, '0000'))
1177
1042
        self.assertEqual(l[1], (1024, '0001'))
1188
1053
    Only the urllib implementation is tested here.
1189
1054
    """
1190
1055
 
 
1056
    def setUp(self):
 
1057
        tests.TestCase.setUp(self)
 
1058
        self._old_env = {}
 
1059
 
 
1060
    def tearDown(self):
 
1061
        self._restore_env()
 
1062
        tests.TestCase.tearDown(self)
 
1063
 
 
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)
 
1067
 
 
1068
    def _restore_env(self):
 
1069
        for name, value in self._old_env.iteritems():
 
1070
            osutils.set_or_unset_env(name, value)
 
1071
 
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')
1195
1076
        return request
1196
1077
 
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))
1201
 
 
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'))
1206
 
 
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'))
1212
1082
 
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)
1217
1087
 
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')
1222
 
 
1223
 
    def test_evaluate_proxy_bypass_false(self):
1224
 
        """The host is proxied"""
1225
 
        self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1226
 
 
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')
1231
 
 
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')
1237
 
 
1238
1088
 
1239
1089
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1240
1090
    """Tests proxy server.
1245
1095
    to the file names).
1246
1096
    """
1247
1097
 
1248
 
    scenarios = multiply_scenarios(
1249
 
        vary_by_http_client_implementation(),
1250
 
        vary_by_http_protocol_version(),
1251
 
        )
1252
 
 
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.
1255
1100
 
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'
1268
1112
        else:
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()
 
1117
        self._old_env = {}
1272
1118
 
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)
1277
 
 
1278
 
    def assertProxied(self):
1279
 
        t = self.get_readonly_transport()
1280
 
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1281
 
 
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
 
1121
 
 
1122
    def create_transport_secondary_server(self):
 
1123
        """Creates an http server that will serve files with
 
1124
        '-proxied' appended to their names.
 
1125
        """
 
1126
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
 
1127
 
 
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)
 
1131
 
 
1132
    def _restore_env(self):
 
1133
        for name, value in self._old_env.iteritems():
 
1134
            osutils.set_or_unset_env(name, value)
 
1135
 
 
1136
    def proxied_in_env(self, env):
 
1137
        self._install_env(env)
 
1138
        url = self.server.get_url()
 
1139
        t = self._transport(url)
 
1140
        try:
 
1141
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
 
1142
        finally:
 
1143
            self._restore_env()
 
1144
 
 
1145
    def not_proxied_in_env(self, env):
 
1146
        self._install_env(env)
 
1147
        url = self.server.get_url()
 
1148
        t = self._transport(url)
 
1149
        try:
 
1150
            self.assertEqual('contents of foo\n', t.get('foo').read())
 
1151
        finally:
 
1152
            self._restore_env()
1285
1153
 
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})
1289
1156
 
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})
1299
1165
 
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})
1303
1168
 
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})
1307
1171
 
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})
1312
1175
 
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})
1320
1182
 
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})
1325
1186
 
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})
1330
1190
 
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})
1338
1197
        else:
1339
 
            self.assertRaises(errors.InvalidURL, self.assertProxied)
 
1198
            self.assertRaises(errors.InvalidURL,
 
1199
                              self.proxied_in_env,
 
1200
                              {'http_proxy': self.proxy_address})
1340
1201
 
1341
1202
 
1342
1203
class TestRanges(http_utils.TestCaseWithWebserver):
1343
1204
    """Test the Range header in GET methods."""
1344
1205
 
1345
 
    scenarios = multiply_scenarios(
1346
 
        vary_by_http_client_implementation(),
1347
 
        vary_by_http_protocol_version(),
1348
 
        )
1349
 
 
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())
1353
1211
 
1354
1212
    def create_transport_readonly_server(self):
1355
1213
        return http_server.HttpServer(protocol_version=self._protocol_version)
1356
1214
 
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)
1367
1224
 
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)
1392
1248
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1393
1249
    """Test redirection between http servers."""
1394
1250
 
1395
 
    scenarios = multiply_scenarios(
1396
 
        vary_by_http_client_implementation(),
1397
 
        vary_by_http_protocol_version(),
1398
 
        )
 
1251
    def create_transport_secondary_server(self):
 
1252
        """Create the secondary server redirecting to the primary server"""
 
1253
        new = self.get_readonly_server()
 
1254
 
 
1255
        redirecting = http_utils.HTTPServerRedirecting(
 
1256
            protocol_version=self._protocol_version)
 
1257
        redirecting.redirect_to(new.host, new.port)
 
1258
        return redirecting
1399
1259
 
1400
1260
    def setUp(self):
1401
1261
        super(TestHTTPRedirections, self).setUp()
1404
1264
                                  '# Bazaar revision bundle v0.9\n#\n')
1405
1265
                                  ],)
1406
1266
 
 
1267
        self.old_transport = self._transport(self.old_server.get_url())
 
1268
 
1407
1269
    def test_redirected(self):
1408
 
        self.assertRaises(errors.RedirectRequested,
1409
 
                          self.get_old_transport().get, 'a')
1410
 
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
 
1270
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1271
        t = self._transport(self.new_server.get_url())
 
1272
        self.assertEqual('0123456789', t.get('a').read())
 
1273
 
 
1274
    def test_read_redirected_bundle_from_url(self):
 
1275
        from bzrlib.bundle import read_bundle_from_url
 
1276
        url = self.old_transport.abspath('bundle')
 
1277
        bundle = read_bundle_from_url(url)
 
1278
        # If read_bundle_from_url was successful we get an empty bundle
 
1279
        self.assertEqual([], bundle.revisions)
1411
1280
 
1412
1281
 
1413
1282
class RedirectedRequest(_urllib2_wrappers.Request):
1422
1291
        # Since the tests using this class will replace
1423
1292
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1424
1293
        # or we'll loop.
1425
 
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
 
1294
        RedirectedRequest.init_orig(self, method, url, args, kwargs)
1426
1295
        self.follow_redirections = True
1427
1296
 
1428
1297
 
1429
 
def install_redirected_request(test):
1430
 
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1431
 
 
1432
 
 
1433
 
def cleanup_http_redirection_connections(test):
1434
 
    # Some sockets are opened but never seen by _urllib, so we trap them at
1435
 
    # the _urllib2_wrappers level to be able to clean them up.
1436
 
    def socket_disconnect(sock):
1437
 
        try:
1438
 
            sock.shutdown(socket.SHUT_RDWR)
1439
 
            sock.close()
1440
 
        except socket.error:
1441
 
            pass
1442
 
    def connect(connection):
1443
 
        test.http_connect_orig(connection)
1444
 
        test.addCleanup(socket_disconnect, connection.sock)
1445
 
    test.http_connect_orig = test.overrideAttr(
1446
 
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1447
 
    def connect(connection):
1448
 
        test.https_connect_orig(connection)
1449
 
        test.addCleanup(socket_disconnect, connection.sock)
1450
 
    test.https_connect_orig = test.overrideAttr(
1451
 
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1452
 
 
1453
 
 
1454
1298
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1455
1299
    """Test redirections.
1456
1300
 
1465
1309
    -- vila 20070212
1466
1310
    """
1467
1311
 
1468
 
    scenarios = multiply_scenarios(
1469
 
        vary_by_http_client_implementation(),
1470
 
        vary_by_http_protocol_version(),
1471
 
        )
1472
 
 
1473
1312
    def setUp(self):
1474
 
        if (features.pycurl.available()
1475
 
            and self._transport == PyCurlTransport):
 
1313
        if pycurl_present and self._transport == PyCurlTransport:
1476
1314
            raise tests.TestNotApplicable(
1477
 
                "pycurl doesn't redirect silently anymore")
 
1315
                "pycurl doesn't redirect silently annymore")
1478
1316
        super(TestHTTPSilentRedirections, self).setUp()
1479
 
        install_redirected_request(self)
1480
 
        cleanup_http_redirection_connections(self)
 
1317
        self.setup_redirected_request()
 
1318
        self.addCleanup(self.cleanup_redirected_request)
1481
1319
        self.build_tree_contents([('a','a'),
1482
1320
                                  ('1/',),
1483
1321
                                  ('1/a', 'redirected once'),
1491
1329
                                  ('5/a', 'redirected 5 times'),
1492
1330
                                  ],)
1493
1331
 
 
1332
        self.old_transport = self._transport(self.old_server.get_url())
 
1333
 
 
1334
    def setup_redirected_request(self):
 
1335
        self.original_class = _urllib2_wrappers.Request
 
1336
        _urllib2_wrappers.Request = RedirectedRequest
 
1337
 
 
1338
    def cleanup_redirected_request(self):
 
1339
        _urllib2_wrappers.Request = self.original_class
 
1340
 
 
1341
    def create_transport_secondary_server(self):
 
1342
        """Create the secondary server, redirections are defined in the tests"""
 
1343
        return http_utils.HTTPServerRedirecting(
 
1344
            protocol_version=self._protocol_version)
 
1345
 
1494
1346
    def test_one_redirection(self):
1495
 
        t = self.get_old_transport()
1496
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1347
        t = self.old_transport
 
1348
 
 
1349
        req = RedirectedRequest('GET', t.abspath('a'))
 
1350
        req.follow_redirections = True
1497
1351
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1498
1352
                                       self.new_server.port)
1499
1353
        self.old_server.redirections = \
1500
1354
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1501
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1355
        self.assertEquals('redirected once',t._perform(req).read())
1502
1356
 
1503
1357
    def test_five_redirections(self):
1504
 
        t = self.get_old_transport()
1505
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1358
        t = self.old_transport
 
1359
 
 
1360
        req = RedirectedRequest('GET', t.abspath('a'))
 
1361
        req.follow_redirections = True
1506
1362
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1507
1363
                                       self.old_server.port)
1508
1364
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1514
1370
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1515
1371
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1516
1372
            ]
1517
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1373
        self.assertEquals('redirected 5 times',t._perform(req).read())
1518
1374
 
1519
1375
 
1520
1376
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1521
1377
    """Test transport.do_catching_redirections."""
1522
1378
 
1523
 
    scenarios = multiply_scenarios(
1524
 
        vary_by_http_client_implementation(),
1525
 
        vary_by_http_protocol_version(),
1526
 
        )
1527
 
 
1528
1379
    def setUp(self):
1529
1380
        super(TestDoCatchRedirections, self).setUp()
1530
1381
        self.build_tree_contents([('a', '0123456789'),],)
1531
 
        cleanup_http_redirection_connections(self)
1532
 
 
1533
 
        self.old_transport = self.get_old_transport()
1534
 
 
1535
 
    def get_a(self, t):
1536
 
        return t.get('a')
 
1382
 
 
1383
        self.old_transport = self._transport(self.old_server.get_url())
 
1384
 
 
1385
    def get_a(self, transport):
 
1386
        return transport.get('a')
1537
1387
 
1538
1388
    def test_no_redirection(self):
1539
 
        t = self.get_new_transport()
 
1389
        t = self._transport(self.new_server.get_url())
1540
1390
 
1541
1391
        # We use None for redirected so that we fail if redirected
1542
 
        self.assertEqual('0123456789',
1543
 
                         transport.do_catching_redirections(
 
1392
        self.assertEquals('0123456789',
 
1393
                          transport.do_catching_redirections(
1544
1394
                self.get_a, t, None).read())
1545
1395
 
1546
1396
    def test_one_redirection(self):
1547
1397
        self.redirections = 0
1548
1398
 
1549
 
        def redirected(t, exception, redirection_notice):
 
1399
        def redirected(transport, exception, redirection_notice):
1550
1400
            self.redirections += 1
1551
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1552
 
            return redirected_t
 
1401
            dir, file = urlutils.split(exception.target)
 
1402
            return self._transport(dir)
1553
1403
 
1554
 
        self.assertEqual('0123456789',
1555
 
                         transport.do_catching_redirections(
 
1404
        self.assertEquals('0123456789',
 
1405
                          transport.do_catching_redirections(
1556
1406
                self.get_a, self.old_transport, redirected).read())
1557
 
        self.assertEqual(1, self.redirections)
 
1407
        self.assertEquals(1, self.redirections)
1558
1408
 
1559
1409
    def test_redirection_loop(self):
1560
1410
 
1569
1419
                          self.get_a, self.old_transport, redirected)
1570
1420
 
1571
1421
 
1572
 
def _setup_authentication_config(**kwargs):
1573
 
    conf = config.AuthenticationConfig()
1574
 
    conf._get_config().update({'httptest': kwargs})
1575
 
    conf._save()
1576
 
 
1577
 
 
1578
 
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1579
 
    """Unit tests for glue by which urllib2 asks us for authentication"""
1580
 
 
1581
 
    def test_get_user_password_without_port(self):
1582
 
        """We cope if urllib2 doesn't tell us the port.
1583
 
 
1584
 
        See https://bugs.launchpad.net/bzr/+bug/654684
1585
 
        """
1586
 
        user = 'joe'
1587
 
        password = 'foo'
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(
1592
 
            user='joe',
1593
 
            protocol='http',
1594
 
            host='localhost',
1595
 
            path='/',
1596
 
            realm='Realm',
1597
 
            ))
1598
 
        self.assertEquals((user, password), got_pass)
1599
 
 
1600
 
 
1601
1422
class TestAuth(http_utils.TestCaseWithWebserver):
1602
1423
    """Test authentication scheme"""
1603
1424
 
1604
 
    scenarios = multiply_scenarios(
1605
 
        vary_by_http_client_implementation(),
1606
 
        vary_by_http_protocol_version(),
1607
 
        vary_by_http_auth_scheme(),
1608
 
        )
 
1425
    _auth_header = 'Authorization'
 
1426
    _password_prompt_prefix = ''
1609
1427
 
1610
1428
    def setUp(self):
1611
1429
        super(TestAuth, self).setUp()
1614
1432
                                  ('b', 'contents of b\n'),])
1615
1433
 
1616
1434
    def create_transport_readonly_server(self):
1617
 
        server = self._auth_server(protocol_version=self._protocol_version)
1618
 
        server._url_protocol = self._url_protocol
 
1435
        if self._auth_scheme == 'basic':
 
1436
            server = http_utils.HTTPBasicAuthServer(
 
1437
                protocol_version=self._protocol_version)
 
1438
        else:
 
1439
            if self._auth_scheme != 'digest':
 
1440
                raise AssertionError('Unknown auth scheme: %r'
 
1441
                                     % self._auth_scheme)
 
1442
            server = http_utils.HTTPDigestAuthServer(
 
1443
                protocol_version=self._protocol_version)
1619
1444
        return server
1620
1445
 
1621
1446
    def _testing_pycurl(self):
1622
 
        # TODO: This is duplicated for lots of the classes in this file
1623
 
        return (features.pycurl.available()
1624
 
                and self._transport == PyCurlTransport)
 
1447
        return pycurl_present and self._transport == PyCurlTransport
1625
1448
 
1626
 
    def get_user_url(self, user, password):
 
1449
    def get_user_url(self, user=None, password=None):
1627
1450
        """Build an url embedding user and password"""
1628
1451
        url = '%s://' % self.server._url_protocol
1629
1452
        if user is not None:
1634
1457
        url += '%s:%s/' % (self.server.host, self.server.port)
1635
1458
        return url
1636
1459
 
1637
 
    def get_user_transport(self, user, password):
1638
 
        t = transport.get_transport(self.get_user_url(user, password))
1639
 
        return t
 
1460
    def get_user_transport(self, user=None, password=None):
 
1461
        return self._transport(self.get_user_url(user, password))
1640
1462
 
1641
1463
    def test_no_user(self):
1642
1464
        self.server.add_user('joe', 'foo')
1643
 
        t = self.get_user_transport(None, None)
 
1465
        t = self.get_user_transport()
1644
1466
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1645
1467
        # Only one 'Authentication Required' error should occur
1646
1468
        self.assertEqual(1, self.server.auth_required_errors)
1676
1498
        # initial 'who are you' and 'this is not you, who are you')
1677
1499
        self.assertEqual(2, self.server.auth_required_errors)
1678
1500
 
1679
 
    def test_prompt_for_username(self):
1680
 
        if self._testing_pycurl():
1681
 
            raise tests.TestNotApplicable(
1682
 
                'pycurl cannot prompt, it handles auth by embedding'
1683
 
                ' user:pass in urls only')
1684
 
 
1685
 
        self.server.add_user('joe', 'foo')
1686
 
        t = self.get_user_transport(None, None)
1687
 
        stdout = tests.StringIOWrapper()
1688
 
        stderr = tests.StringIOWrapper()
1689
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1690
 
                                            stdout=stdout, stderr=stderr)
1691
 
        self.assertEqual('contents of a\n',t.get('a').read())
1692
 
        # stdin should be empty
1693
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
1694
 
        stderr.seek(0)
1695
 
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1696
 
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1697
 
        self.assertEqual('', stdout.getvalue())
1698
 
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1699
 
                                    stderr.readline())
1700
 
 
1701
1501
    def test_prompt_for_password(self):
1702
1502
        if self._testing_pycurl():
1703
1503
            raise tests.TestNotApplicable(
1707
1507
        self.server.add_user('joe', 'foo')
1708
1508
        t = self.get_user_transport('joe', None)
1709
1509
        stdout = tests.StringIOWrapper()
1710
 
        stderr = tests.StringIOWrapper()
1711
 
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1712
 
                                            stdout=stdout, stderr=stderr)
1713
 
        self.assertEqual('contents of a\n', t.get('a').read())
 
1510
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
 
1511
        self.assertEqual('contents of a\n',t.get('a').read())
1714
1512
        # stdin should be empty
1715
1513
        self.assertEqual('', ui.ui_factory.stdin.readline())
1716
1514
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1717
 
                                    stderr.getvalue())
1718
 
        self.assertEqual('', stdout.getvalue())
 
1515
                                    stdout.getvalue())
1719
1516
        # And we shouldn't prompt again for a different request
1720
1517
        # against the same transport.
1721
1518
        self.assertEqual('contents of b\n',t.get('b').read())
1731
1528
                              % (scheme.upper(),
1732
1529
                                 user, self.server.host, self.server.port,
1733
1530
                                 self.server.auth_realm)))
1734
 
        self.assertEqual(expected_prompt, actual_prompt)
1735
 
 
1736
 
    def _expected_username_prompt(self, scheme):
1737
 
        return (self._username_prompt_prefix
1738
 
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1739
 
                                 self.server.host, self.server.port,
1740
 
                                 self.server.auth_realm))
 
1531
        self.assertEquals(expected_prompt, actual_prompt)
1741
1532
 
1742
1533
    def test_no_prompt_for_password_when_using_auth_config(self):
1743
1534
        if self._testing_pycurl():
1751
1542
        self.server.add_user(user, password)
1752
1543
        t = self.get_user_transport(user, None)
1753
1544
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1754
 
                                            stderr=tests.StringIOWrapper())
 
1545
                                            stdout=tests.StringIOWrapper())
1755
1546
        # Create a minimal config file with the right password
1756
 
        _setup_authentication_config(scheme='http', port=self.server.port,
1757
 
                                     user=user, password=password)
 
1547
        conf = config.AuthenticationConfig()
 
1548
        conf._get_config().update(
 
1549
            {'httptest': {'scheme': 'http', 'port': self.server.port,
 
1550
                          'user': user, 'password': password}})
 
1551
        conf._save()
1758
1552
        # Issue a request to the server to connect
1759
1553
        self.assertEqual('contents of a\n',t.get('a').read())
1760
1554
        # stdin should have  been left untouched
1763
1557
        self.assertEqual(1, self.server.auth_required_errors)
1764
1558
 
1765
1559
    def test_changing_nonce(self):
1766
 
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1767
 
                                     http_utils.ProxyDigestAuthServer):
1768
 
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
 
1560
        if self._auth_scheme != 'digest':
 
1561
            raise tests.TestNotApplicable('HTTP auth digest only test')
1769
1562
        if self._testing_pycurl():
1770
 
            self.knownFailure(
 
1563
            raise tests.KnownFailure(
1771
1564
                'pycurl does not handle a nonce change')
1772
1565
        self.server.add_user('joe', 'foo')
1773
1566
        t = self.get_user_transport('joe', 'foo')
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)
1785
1578
 
1786
 
    def test_user_from_auth_conf(self):
1787
 
        if self._testing_pycurl():
1788
 
            raise tests.TestNotApplicable(
1789
 
                'pycurl does not support authentication.conf')
1790
 
        user = 'joe'
1791
 
        password = 'foo'
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)
1800
 
 
1801
 
    def test_no_credential_leaks_in_log(self):
1802
 
        self.overrideAttr(debug, 'debug_flags', set(['http']))
1803
 
        user = 'joe'
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
1808
 
        self.mutters = []
1809
 
        def mutter(*args):
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
1820
 
        # debug line
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,))
1826
1579
 
1827
1580
 
1828
1581
class TestProxyAuth(TestAuth):
1829
 
    """Test proxy authentication schemes.
1830
 
 
1831
 
    This inherits from TestAuth to tweak the setUp and filter some failing
1832
 
    tests.
1833
 
    """
1834
 
 
1835
 
    scenarios = multiply_scenarios(
1836
 
        vary_by_http_client_implementation(),
1837
 
        vary_by_http_protocol_version(),
1838
 
        vary_by_http_proxy_auth_scheme(),
1839
 
        )
 
1582
    """Test proxy authentication schemes."""
 
1583
 
 
1584
    _auth_header = 'Proxy-authorization'
 
1585
    _password_prompt_prefix='Proxy '
1840
1586
 
1841
1587
    def setUp(self):
1842
1588
        super(TestProxyAuth, self).setUp()
 
1589
        self._old_env = {}
 
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'),
1847
1595
                                  ('b-proxied', 'contents of b\n'),
1848
1596
                                  ])
1849
1597
 
1850
 
    def get_user_transport(self, user, password):
1851
 
        self.overrideEnv('all_proxy', self.get_user_url(user, password))
1852
 
        return TestAuth.get_user_transport(self, user, password)
 
1598
    def create_transport_readonly_server(self):
 
1599
        if self._auth_scheme == 'basic':
 
1600
            server = http_utils.ProxyBasicAuthServer(
 
1601
                protocol_version=self._protocol_version)
 
1602
        else:
 
1603
            if self._auth_scheme != 'digest':
 
1604
                raise AssertionError('Unknown auth scheme: %r'
 
1605
                                     % self._auth_scheme)
 
1606
            server = http_utils.ProxyDigestAuthServer(
 
1607
                protocol_version=self._protocol_version)
 
1608
        return server
 
1609
 
 
1610
    def get_user_transport(self, user=None, password=None):
 
1611
        self._install_env({'all_proxy': self.get_user_url(user, password)})
 
1612
        return self._transport(self.server.get_url())
 
1613
 
 
1614
    def _install_env(self, env):
 
1615
        for name, value in env.iteritems():
 
1616
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1617
 
 
1618
    def _restore_env(self):
 
1619
        for name, value in self._old_env.iteritems():
 
1620
            osutils.set_or_unset_env(name, value)
1853
1621
 
1854
1622
    def test_empty_pass(self):
1855
1623
        if self._testing_pycurl():
1856
1624
            import pycurl
1857
1625
            if pycurl.version_info()[1] < '7.16.0':
1858
 
                self.knownFailure(
 
1626
                raise tests.KnownFailure(
1859
1627
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1860
1628
        super(TestProxyAuth, self).test_empty_pass()
1861
1629
 
1874
1642
        self.readfile = StringIO(socket_read_content)
1875
1643
        self.writefile = StringIO()
1876
1644
        self.writefile.close = lambda: None
1877
 
        self.close = lambda: None
1878
1645
 
1879
1646
    def makefile(self, mode='r', bufsize=None):
1880
1647
        if 'r' in mode:
1885
1652
 
1886
1653
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1887
1654
 
1888
 
    scenarios = multiply_scenarios(
1889
 
        vary_by_http_client_implementation(),
1890
 
        vary_by_http_protocol_version(),
1891
 
        )
1892
 
 
1893
1655
    def setUp(self):
1894
1656
        super(SmartHTTPTunnellingTest, self).setUp()
1895
1657
        # We use the VFS layer as part of HTTP tunnelling tests.
1896
 
        self.overrideEnv('BZR_NO_SMART_VFS', None)
 
1658
        self._captureVar('BZR_NO_SMART_VFS', None)
1897
1659
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1898
 
        self.http_server = self.get_readonly_server()
1899
1660
 
1900
1661
    def create_transport_readonly_server(self):
1901
 
        server = http_utils.HTTPServerWithSmarts(
 
1662
        return http_utils.HTTPServerWithSmarts(
1902
1663
            protocol_version=self._protocol_version)
1903
 
        server._url_protocol = self._url_protocol
1904
 
        return server
1905
1664
 
1906
1665
    def test_open_bzrdir(self):
1907
1666
        branch = self.make_branch('relpath')
1908
 
        url = self.http_server.get_url() + 'relpath'
 
1667
        http_server = self.get_readonly_server()
 
1668
        url = http_server.get_url() + 'relpath'
1909
1669
        bd = bzrdir.BzrDir.open(url)
1910
 
        self.addCleanup(bd.transport.disconnect)
1911
1670
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1912
1671
 
1913
1672
    def test_bulk_data(self):
1915
1674
        # The 'readv' command in the smart protocol both sends and receives
1916
1675
        # bulk data, so we use that.
1917
1676
        self.build_tree(['data-file'])
1918
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1677
        http_server = self.get_readonly_server()
 
1678
        http_transport = self._transport(http_server.get_url())
1919
1679
        medium = http_transport.get_smart_medium()
1920
1680
        # Since we provide the medium, the url below will be mostly ignored
1921
1681
        # during the test, as long as the path is '/'.
1929
1689
        post_body = 'hello\n'
1930
1690
        expected_reply_body = 'ok\x012\n'
1931
1691
 
1932
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1692
        http_server = self.get_readonly_server()
 
1693
        http_transport = self._transport(http_server.get_url())
1933
1694
        medium = http_transport.get_smart_medium()
1934
1695
        response = medium.send_http_smart_request(post_body)
1935
1696
        reply_body = response.read()
1936
1697
        self.assertEqual(expected_reply_body, reply_body)
1937
1698
 
1938
1699
    def test_smart_http_server_post_request_handler(self):
1939
 
        httpd = self.http_server.server
 
1700
        httpd = self.get_readonly_server()._get_httpd()
1940
1701
 
1941
1702
        socket = SampleSocket(
1942
1703
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1974
1735
 
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,
1982
1744
                          'whatever')
1983
1745
 
1984
 
 
1985
 
class Test_redirected_to(tests.TestCase):
1986
 
 
1987
 
    scenarios = vary_by_http_client_implementation()
1988
 
 
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())
1996
 
 
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
2004
 
        # overkill).
2005
 
        self.assertEqual(t._get_connection(), r._get_connection())
2006
 
 
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))
2012
 
 
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))
2018
 
 
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))
2024
 
 
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)
2031
 
 
2032
 
 
2033
 
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
2034
 
    """Request handler for a unique and pre-defined request.
2035
 
 
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
2038
 
    correct responses.
2039
 
 
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
2042
 
    line.
2043
 
    """
2044
 
 
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
2061
 
 
2062
 
        # We set the bytes written *before* issuing the write, the client is
2063
 
        # supposed to consume every produced byte *before* checking that value.
2064
 
 
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)
2071
 
 
2072
 
 
2073
 
class ActivityServerMixin(object):
2074
 
 
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
2080
 
        self.bytes_read = 0
2081
 
        self.bytes_written = 0
2082
 
        self.canned_response = None
2083
 
 
2084
 
 
2085
 
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
2086
 
    pass
2087
 
 
2088
 
 
2089
 
if features.HTTPSServerFeature.available():
2090
 
    from bzrlib.tests import https_server
2091
 
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
2092
 
        pass
2093
 
 
2094
 
 
2095
 
class TestActivityMixin(object):
2096
 
    """Test socket activity reporting.
2097
 
 
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.
2100
 
    """
2101
 
 
2102
 
    def setUp(self):
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)
2109
 
            count += bytes
2110
 
            _activities[direction] = count
2111
 
        self.activities = _activities
2112
 
 
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)
2118
 
 
2119
 
    def get_transport(self):
2120
 
        t = self._transport(self.server.get_url())
2121
 
        # FIXME: Needs cleanup -- vila 20100611
2122
 
        return t
2123
 
 
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')
2129
 
 
2130
 
    def test_get(self):
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
2138
 
Connection: close\r
2139
 
Content-Type: text/plain; charset=UTF-8\r
2140
 
\r
2141
 
Bazaar-NG meta directory, format 1
2142
 
'''
2143
 
        t = self.get_transport()
2144
 
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
2145
 
                         t.get('foo/bar').read())
2146
 
        self.assertActivitiesMatch()
2147
 
 
2148
 
    def test_has(self):
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
2155
 
\r
2156
 
'''
2157
 
        t = self.get_transport()
2158
 
        self.assertTrue(t.has('foo/bar'))
2159
 
        self.assertActivitiesMatch()
2160
 
 
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
2169
 
Connection: close\r
2170
 
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2171
 
\r
2172
 
\r
2173
 
--418470f848b63279b\r
2174
 
Content-type: text/plain; charset=UTF-8\r
2175
 
Content-range: bytes 0-254/93890\r
2176
 
\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
2182
 
\r
2183
 
--418470f848b63279b\r
2184
 
Content-type: text/plain; charset=UTF-8\r
2185
 
Content-range: bytes 1000-2049/93890\r
2186
 
\r
2187
 
40-fd4ec249b6b139ab
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
2208
 
mbp@source\r
2209
 
--418470f848b63279b--\r
2210
 
'''
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()
2217
 
 
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
2226
 
Connection: close\r
2227
 
Content-Type: text/plain; charset=UTF-8\r
2228
 
\r
2229
 
lalala whatever as long as itsssss
2230
 
'''
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()
2237
 
 
2238
 
 
2239
 
class TestActivity(tests.TestCase, TestActivityMixin):
2240
 
 
2241
 
    scenarios = multiply_scenarios(
2242
 
        vary_by_http_activity(),
2243
 
        vary_by_http_protocol_version(),
2244
 
        )
2245
 
 
2246
 
    def setUp(self):
2247
 
        TestActivityMixin.setUp(self)
2248
 
 
2249
 
 
2250
 
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2251
 
 
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'
2259
 
 
2260
 
    def setUp(self):
2261
 
        self._transport =_urllib.HttpTransport_urllib
2262
 
        TestActivityMixin.setUp(self)
2263
 
 
2264
 
    def assertActivitiesMatch(self):
2265
 
        # Nothing to check here
2266
 
        pass
2267
 
 
2268
 
 
2269
 
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2270
 
    """Test authentication on the redirected http server."""
2271
 
 
2272
 
    scenarios = vary_by_http_protocol_version()
2273
 
 
2274
 
    _auth_header = 'Authorization'
2275
 
    _password_prompt_prefix = ''
2276
 
    _username_prompt_prefix = ''
2277
 
    _auth_server = http_utils.HTTPBasicAuthServer
2278
 
    _transport = _urllib.HttpTransport_urllib
2279
 
 
2280
 
    def setUp(self):
2281
 
        super(TestAuthOnRedirected, self).setUp()
2282
 
        self.build_tree_contents([('a','a'),
2283
 
                                  ('1/',),
2284
 
                                  ('1/a', 'redirected once'),
2285
 
                                  ],)
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)
2293
 
 
2294
 
    def create_transport_readonly_server(self):
2295
 
        server = self._auth_server(protocol_version=self._protocol_version)
2296
 
        server._url_protocol = self._url_protocol
2297
 
        return server
2298
 
 
2299
 
    def get_a(self, t):
2300
 
        return t.get('a')
2301
 
 
2302
 
    def test_auth_on_redirected_via_do_catching_redirections(self):
2303
 
        self.redirections = 0
2304
 
 
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)
2309
 
            return redirected_t
2310
 
 
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())
2323
 
 
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())
2341