~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-03-16 16:58:03 UTC
  • mfrom: (3224.3.1 news-typo)
  • Revision ID: pqm@pqm.ubuntu.com-20080316165803-tisoc9mpob9z544o
(Matt Nordhoff) Trivial NEWS typo fix

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
31
34
 
32
35
import bzrlib
33
36
from bzrlib import (
34
 
    bzrdir,
35
 
    cethread,
36
37
    config,
37
 
    debug,
38
38
    errors,
39
39
    osutils,
40
 
    remote as _mod_remote,
41
40
    tests,
42
 
    trace,
43
41
    transport,
44
42
    ui,
 
43
    urlutils,
45
44
    )
46
45
from bzrlib.tests import (
47
 
    features,
48
46
    http_server,
49
47
    http_utils,
50
 
    test_server,
51
 
    )
52
 
from bzrlib.tests.scenarios import (
53
 
    load_tests_apply_scenarios,
54
 
    multiply_scenarios,
55
48
    )
56
49
from bzrlib.transport import (
57
50
    http,
63
56
    )
64
57
 
65
58
 
66
 
if features.pycurl.available():
 
59
try:
67
60
    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,
 
61
    pycurl_present = True
 
62
except errors.DependencyNotPresent:
 
63
    pycurl_present = False
 
64
 
 
65
 
 
66
class TransportAdapter(tests.TestScenarioApplier):
 
67
    """Generate the same test for each transport implementation."""
 
68
 
 
69
    def __init__(self):
 
70
        transport_scenarios = [
 
71
            ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
 
72
                            _server=http_server.HttpServer_urllib,
 
73
                            _qualified_prefix='http+urllib',)),
 
74
            ]
 
75
        if pycurl_present:
 
76
            transport_scenarios.append(
 
77
                ('pycurl', dict(_transport=PyCurlTransport,
 
78
                                _server=http_server.HttpServer_PyCurl,
 
79
                                _qualified_prefix='http+pycurl',)))
 
80
        self.scenarios = transport_scenarios
 
81
 
 
82
 
 
83
class TransportProtocolAdapter(TransportAdapter):
 
84
    """Generate the same test for each protocol implementation.
 
85
 
 
86
    In addition to the transport adaptatation that we inherit from.
 
87
    """
 
88
 
 
89
    def __init__(self):
 
90
        super(TransportProtocolAdapter, self).__init__()
 
91
        protocol_scenarios = [
 
92
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
 
93
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
94
            ]
 
95
        self.scenarios = tests.multiply_scenarios(self.scenarios,
 
96
                                                  protocol_scenarios)
 
97
 
 
98
 
 
99
class TransportProtocolAuthenticationAdapter(TransportProtocolAdapter):
 
100
    """Generate the same test for each authentication scheme implementation.
 
101
 
 
102
    In addition to the protocol adaptatation that we inherit from.
 
103
    """
 
104
 
 
105
    def __init__(self):
 
106
        super(TransportProtocolAuthenticationAdapter, self).__init__()
 
107
        auth_scheme_scenarios = [
 
108
            ('basic', dict(_auth_scheme='basic')),
 
109
            ('digest', dict(_auth_scheme='digest')),
 
110
            ]
 
111
 
 
112
        self.scenarios = tests.multiply_scenarios(self.scenarios,
 
113
                                                  auth_scheme_scenarios)
 
114
 
 
115
def load_tests(standard_tests, module, loader):
 
116
    """Multiply tests for http clients and protocol versions."""
 
117
    # one for each transport
 
118
    t_adapter = TransportAdapter()
 
119
    t_classes= (TestHttpTransportRegistration,
 
120
                TestHttpTransportUrls,
142
121
                )
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
 
122
    is_testing_for_transports = tests.condition_isinstance(t_classes)
 
123
 
 
124
    # multiplied by one for each protocol version
 
125
    tp_adapter = TransportProtocolAdapter()
 
126
    tp_classes= (SmartHTTPTunnellingTest,
 
127
                 TestDoCatchRedirections,
 
128
                 TestHTTPConnections,
 
129
                 TestHTTPRedirections,
 
130
                 TestHTTPSilentRedirections,
 
131
                 TestLimitedRangeRequestServer,
 
132
                 TestPost,
 
133
                 TestProxyHttpServer,
 
134
                 TestRanges,
 
135
                 TestSpecificRequestHandler,
 
136
                 )
 
137
    is_also_testing_for_protocols = tests.condition_isinstance(tp_classes)
 
138
 
 
139
    # multiplied by one for each authentication scheme
 
140
    tpa_adapter = TransportProtocolAuthenticationAdapter()
 
141
    tpa_classes = (TestAuth,
 
142
                   )
 
143
    is_also_testing_for_authentication = tests.condition_isinstance(
 
144
        tpa_classes)
 
145
 
 
146
    result = loader.suiteClass()
 
147
    for test_class in tests.iter_suite_tests(standard_tests):
 
148
        # Each test class is either standalone or testing for some combination
 
149
        # of transport, protocol version, authentication scheme. Use the right
 
150
        # adpater (or none) depending on the class.
 
151
        if is_testing_for_transports(test_class):
 
152
            result.addTests(t_adapter.adapt(test_class))
 
153
        elif is_also_testing_for_protocols(test_class):
 
154
            result.addTests(tp_adapter.adapt(test_class))
 
155
        elif is_also_testing_for_authentication(test_class):
 
156
            result.addTests(tpa_adapter.adapt(test_class))
 
157
        else:
 
158
            result.addTest(test_class)
 
159
    return result
158
160
 
159
161
 
160
162
class FakeManager(object):
168
170
 
169
171
class RecordingServer(object):
170
172
    """A fake HTTP server.
171
 
 
 
173
    
172
174
    It records the bytes sent to it, and replies with a 200.
173
175
    """
174
176
 
175
 
    def __init__(self, expect_body_tail=None, scheme=''):
 
177
    def __init__(self, expect_body_tail=None):
176
178
        """Constructor.
177
179
 
178
180
        :type expect_body_tail: str
183
185
        self.host = None
184
186
        self.port = None
185
187
        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):
 
188
 
 
189
    def setUp(self):
192
190
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
193
191
        self._sock.bind(('127.0.0.1', 0))
194
192
        self.host, self.port = self._sock.getsockname()
195
193
        self._ready = threading.Event()
196
 
        self._thread = test_server.TestThread(
197
 
            sync_event=self._ready, target=self._accept_read_and_reply)
 
194
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
195
        self._thread.setDaemon(True)
198
196
        self._thread.start()
199
 
        if 'threads' in tests.selftest_debug_flags:
200
 
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
201
 
        self._ready.wait()
 
197
        self._ready.wait(5)
202
198
 
203
199
    def _accept_read_and_reply(self):
204
200
        self._sock.listen(1)
205
201
        self._ready.set()
206
 
        conn, address = self._sock.accept()
207
 
        if self._expect_body_tail is not None:
 
202
        self._sock.settimeout(5)
 
203
        try:
 
204
            conn, address = self._sock.accept()
 
205
            # On win32, the accepted connection will be non-blocking to start
 
206
            # with because we're using settimeout.
 
207
            conn.setblocking(True)
208
208
            while not self.received_bytes.endswith(self._expect_body_tail):
209
209
                self.received_bytes += conn.recv(4096)
210
210
            conn.sendall('HTTP/1.1 200 OK\r\n')
211
 
        try:
 
211
        except socket.timeout:
 
212
            # Make sure the client isn't stuck waiting for us to e.g. accept.
212
213
            self._sock.close()
213
214
        except socket.error:
214
215
            # The client may have already closed the socket.
215
216
            pass
216
217
 
217
 
    def stop_server(self):
 
218
    def tearDown(self):
218
219
        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()
 
220
            self._sock.close()
223
221
        except socket.error:
224
222
            # We might have already closed it.  We don't care.
225
223
            pass
226
224
        self.host = None
227
225
        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
226
 
305
227
 
306
228
class TestHTTPServer(tests.TestCase):
311
233
 
312
234
            protocol_version = 'HTTP/0.1'
313
235
 
314
 
        self.assertRaises(httplib.UnknownProtocol,
315
 
                          http_server.HttpServer, BogusRequestHandler)
 
236
        server = http_server.HttpServer(BogusRequestHandler)
 
237
        try:
 
238
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
239
        except:
 
240
            server.tearDown()
 
241
            self.fail('HTTP Server creation did not raise UnknownProtocol')
316
242
 
317
243
    def test_force_invalid_protocol(self):
318
 
        self.assertRaises(httplib.UnknownProtocol,
319
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
244
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
245
        try:
 
246
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
247
        except:
 
248
            server.tearDown()
 
249
            self.fail('HTTP Server creation did not raise UnknownProtocol')
320
250
 
321
251
    def test_server_start_and_stop(self):
322
252
        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)
 
253
        server.setUp()
 
254
        self.assertTrue(server._http_running)
 
255
        server.tearDown()
 
256
        self.assertFalse(server._http_running)
328
257
 
329
258
    def test_create_http_server_one_zero(self):
330
259
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
332
261
            protocol_version = 'HTTP/1.0'
333
262
 
334
263
        server = http_server.HttpServer(RequestHandlerOneZero)
335
 
        self.start_server(server)
336
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
264
        server.setUp()
 
265
        self.addCleanup(server.tearDown)
 
266
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
337
267
 
338
268
    def test_create_http_server_one_one(self):
339
269
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
341
271
            protocol_version = 'HTTP/1.1'
342
272
 
343
273
        server = http_server.HttpServer(RequestHandlerOneOne)
344
 
        self.start_server(server)
345
 
        self.assertIsInstance(server.server,
 
274
        server.setUp()
 
275
        self.addCleanup(server.tearDown)
 
276
        self.assertIsInstance(server._httpd,
346
277
                              http_server.TestingThreadingHTTPServer)
347
278
 
348
279
    def test_create_http_server_force_one_one(self):
352
283
 
353
284
        server = http_server.HttpServer(RequestHandlerOneZero,
354
285
                                        protocol_version='HTTP/1.1')
355
 
        self.start_server(server)
356
 
        self.assertIsInstance(server.server,
 
286
        server.setUp()
 
287
        self.addCleanup(server.tearDown)
 
288
        self.assertIsInstance(server._httpd,
357
289
                              http_server.TestingThreadingHTTPServer)
358
290
 
359
291
    def test_create_http_server_force_one_zero(self):
363
295
 
364
296
        server = http_server.HttpServer(RequestHandlerOneOne,
365
297
                                        protocol_version='HTTP/1.0')
366
 
        self.start_server(server)
367
 
        self.assertIsInstance(server.server,
 
298
        server.setUp()
 
299
        self.addCleanup(server.tearDown)
 
300
        self.assertIsInstance(server._httpd,
368
301
                              http_server.TestingHTTPServer)
369
302
 
370
303
 
372
305
    """Test case to inherit from if pycurl is present"""
373
306
 
374
307
    def _get_pycurl_maybe(self):
375
 
        self.requireFeature(features.pycurl)
376
 
        return PyCurlTransport
 
308
        try:
 
309
            from bzrlib.transport.http._pycurl import PyCurlTransport
 
310
            return PyCurlTransport
 
311
        except errors.DependencyNotPresent:
 
312
            raise tests.TestSkipped('pycurl not present')
377
313
 
378
314
    _transport = property(_get_pycurl_maybe)
379
315
 
386
322
    def test_url_parsing(self):
387
323
        f = FakeManager()
388
324
        url = http.extract_auth('http://example.com', f)
389
 
        self.assertEqual('http://example.com', url)
390
 
        self.assertEqual(0, len(f.credentials))
 
325
        self.assertEquals('http://example.com', url)
 
326
        self.assertEquals(0, len(f.credentials))
391
327
        url = http.extract_auth(
392
 
            'http://user:pass@example.com/bzr/bzr.dev', f)
393
 
        self.assertEqual('http://example.com/bzr/bzr.dev', url)
394
 
        self.assertEqual(1, len(f.credentials))
395
 
        self.assertEqual([None, 'example.com', 'user', 'pass'],
396
 
                         f.credentials[0])
 
328
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
 
329
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
 
330
        self.assertEquals(1, len(f.credentials))
 
331
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
 
332
                          f.credentials[0])
397
333
 
398
334
 
399
335
class TestHttpTransportUrls(tests.TestCase):
400
336
    """Test the http urls."""
401
337
 
402
 
    scenarios = vary_by_http_client_implementation()
403
 
 
404
338
    def test_abs_url(self):
405
339
        """Construction of absolute http URLs"""
406
 
        t = self._transport('http://example.com/bzr/bzr.dev/')
 
340
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
341
        eq = self.assertEqualDiff
408
 
        eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
409
 
        eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
410
 
        eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
 
342
        eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
 
343
        eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
 
344
        eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
411
345
        eq(t.abspath('.bzr/1//2/./3'),
412
 
           'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
 
346
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
413
347
 
414
348
    def test_invalid_http_urls(self):
415
349
        """Trap invalid construction of urls"""
416
 
        self._transport('http://example.com/bzr/bzr.dev/')
 
350
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
351
        self.assertRaises(errors.InvalidURL,
418
352
                          self._transport,
419
 
                          'http://http://example.com/bzr/bzr.dev/')
 
353
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
420
354
 
421
355
    def test_http_root_urls(self):
422
356
        """Construction of URLs from server root"""
423
 
        t = self._transport('http://example.com/')
 
357
        t = self._transport('http://bzr.ozlabs.org/')
424
358
        eq = self.assertEqualDiff
425
359
        eq(t.abspath('.bzr/tree-version'),
426
 
           'http://example.com/.bzr/tree-version')
 
360
           'http://bzr.ozlabs.org/.bzr/tree-version')
427
361
 
428
362
    def test_http_impl_urls(self):
429
363
        """There are servers which ask for particular clients to connect"""
430
364
        server = self._server()
431
 
        server.start_server()
432
365
        try:
 
366
            server.setUp()
433
367
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
368
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
369
        finally:
436
 
            server.stop_server()
 
370
            server.tearDown()
437
371
 
438
372
 
439
373
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
448
382
        https by supplying a fake version_info that do not
449
383
        support it.
450
384
        """
451
 
        self.requireFeature(features.pycurl)
452
 
        # Import the module locally now that we now it's available.
453
 
        pycurl = features.pycurl.module
 
385
        try:
 
386
            import pycurl
 
387
        except ImportError:
 
388
            raise tests.TestSkipped('pycurl not present')
454
389
 
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')
 
390
        version_info_orig = pycurl.version_info
 
391
        try:
 
392
            # Now that we have pycurl imported, we can fake its version_info
 
393
            # This was taken from a windows pycurl without SSL
 
394
            # (thanks to bialix)
 
395
            pycurl.version_info = lambda : (2,
 
396
                                            '7.13.2',
 
397
                                            462082,
 
398
                                            'i386-pc-win32',
 
399
                                            2576,
 
400
                                            None,
 
401
                                            0,
 
402
                                            None,
 
403
                                            ('ftp', 'gopher', 'telnet',
 
404
                                             'dict', 'ldap', 'http', 'file'),
 
405
                                            None,
 
406
                                            0,
 
407
                                            None)
 
408
            self.assertRaises(errors.DependencyNotPresent, self._transport,
 
409
                              'https://launchpad.net')
 
410
        finally:
 
411
            # Restore the right function
 
412
            pycurl.version_info = version_info_orig
473
413
 
474
414
 
475
415
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
476
416
    """Test the http connections."""
477
417
 
478
 
    scenarios = multiply_scenarios(
479
 
        vary_by_http_client_implementation(),
480
 
        vary_by_http_protocol_version(),
481
 
        )
482
 
 
483
418
    def setUp(self):
484
419
        http_utils.TestCaseWithWebserver.setUp(self)
485
420
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
487
422
 
488
423
    def test_http_has(self):
489
424
        server = self.get_readonly_server()
490
 
        t = self.get_readonly_transport()
 
425
        t = self._transport(server.get_url())
491
426
        self.assertEqual(t.has('foo/bar'), True)
492
427
        self.assertEqual(len(server.logs), 1)
493
428
        self.assertContainsRe(server.logs[0],
495
430
 
496
431
    def test_http_has_not_found(self):
497
432
        server = self.get_readonly_server()
498
 
        t = self.get_readonly_transport()
 
433
        t = self._transport(server.get_url())
499
434
        self.assertEqual(t.has('not-found'), False)
500
435
        self.assertContainsRe(server.logs[1],
501
436
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
502
437
 
503
438
    def test_http_get(self):
504
439
        server = self.get_readonly_server()
505
 
        t = self.get_readonly_transport()
 
440
        t = self._transport(server.get_url())
506
441
        fp = t.get('foo/bar')
507
442
        self.assertEqualDiff(
508
443
            fp.read(),
512
447
            '"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
513
448
            % bzrlib.__version__) > -1)
514
449
 
 
450
    def test_get_smart_medium(self):
 
451
        # For HTTP, get_smart_medium should return the transport object.
 
452
        server = self.get_readonly_server()
 
453
        http_transport = self._transport(server.get_url())
 
454
        medium = http_transport.get_smart_medium()
 
455
        self.assertIs(medium, http_transport)
 
456
 
515
457
    def test_has_on_bogus_host(self):
516
458
        # Get a free address and don't 'accept' on it, so that we
517
459
        # can be sure there is no http handler there, but set a
530
472
class TestHttpTransportRegistration(tests.TestCase):
531
473
    """Test registrations of various http implementations"""
532
474
 
533
 
    scenarios = vary_by_http_client_implementation()
534
 
 
535
475
    def test_http_registered(self):
536
 
        t = transport.get_transport_from_url(
537
 
            '%s://foo.com/' % self._url_protocol)
 
476
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
538
477
        self.assertIsInstance(t, transport.Transport)
539
478
        self.assertIsInstance(t, self._transport)
540
479
 
541
480
 
542
481
class TestPost(tests.TestCase):
543
482
 
544
 
    scenarios = multiply_scenarios(
545
 
        vary_by_http_client_implementation(),
546
 
        vary_by_http_protocol_version(),
547
 
        )
548
 
 
549
483
    def test_post_body_is_received(self):
550
 
        server = RecordingServer(expect_body_tail='end-of-body',
551
 
                                 scheme=self._url_protocol)
552
 
        self.start_server(server)
553
 
        url = server.get_url()
554
 
        # FIXME: needs a cleanup -- vila 20100611
555
 
        http_transport = transport.get_transport_from_url(url)
 
484
        server = RecordingServer(expect_body_tail='end-of-body')
 
485
        server.setUp()
 
486
        self.addCleanup(server.tearDown)
 
487
        scheme = self._qualified_prefix
 
488
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
 
489
        http_transport = self._transport(url)
556
490
        code, response = http_transport._post('abc def end-of-body')
557
491
        self.assertTrue(
558
492
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
559
493
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
560
 
        self.assertTrue('content-type: application/octet-stream\r'
561
 
                        in server.received_bytes.lower())
562
494
        # The transport should not be assuming that the server can accept
563
495
        # chunked encoding the first time it connects, because HTTP/1.1, so we
564
496
        # check for the literal string.
600
532
    Daughter classes are expected to override _req_handler_class
601
533
    """
602
534
 
603
 
    scenarios = multiply_scenarios(
604
 
        vary_by_http_client_implementation(),
605
 
        vary_by_http_protocol_version(),
606
 
        )
607
 
 
608
535
    # Provide a useful default
609
536
    _req_handler_class = http_server.TestingHTTPRequestHandler
610
537
 
611
538
    def create_transport_readonly_server(self):
612
 
        server = http_server.HttpServer(self._req_handler_class,
613
 
                                        protocol_version=self._protocol_version)
614
 
        server._url_protocol = self._url_protocol
615
 
        return server
 
539
        return http_server.HttpServer(self._req_handler_class,
 
540
                                      protocol_version=self._protocol_version)
616
541
 
617
542
    def _testing_pycurl(self):
618
 
        # TODO: This is duplicated for lots of the classes in this file
619
 
        return (features.pycurl.available()
620
 
                and self._transport == PyCurlTransport)
 
543
        return pycurl_present and self._transport == PyCurlTransport
621
544
 
622
545
 
623
546
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
624
547
    """Whatever request comes in, close the connection"""
625
548
 
626
 
    def _handle_one_request(self):
 
549
    def handle_one_request(self):
627
550
        """Handle a single HTTP request, by abruptly closing the connection"""
628
551
        self.close_connection = 1
629
552
 
634
557
    _req_handler_class = WallRequestHandler
635
558
 
636
559
    def test_http_has(self):
637
 
        t = self.get_readonly_transport()
 
560
        server = self.get_readonly_server()
 
561
        t = self._transport(server.get_url())
638
562
        # Unfortunately httplib (see HTTPResponse._read_status
639
563
        # for details) make no distinction between a closed
640
564
        # socket and badly formatted status line, so we can't
641
565
        # just test for ConnectionError, we have to test
642
 
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
643
 
        # instead of ConnectionError too.
644
 
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
645
 
                            errors.InvalidHttpResponse),
 
566
        # InvalidHttpResponse too.
 
567
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
646
568
                          t.has, 'foo/bar')
647
569
 
648
570
    def test_http_get(self):
649
 
        t = self.get_readonly_transport()
650
 
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
651
 
                           errors.InvalidHttpResponse),
 
571
        server = self.get_readonly_server()
 
572
        t = self._transport(server.get_url())
 
573
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
652
574
                          t.get, 'foo/bar')
653
575
 
654
576
 
669
591
    _req_handler_class = BadStatusRequestHandler
670
592
 
671
593
    def test_http_has(self):
672
 
        t = self.get_readonly_transport()
 
594
        server = self.get_readonly_server()
 
595
        t = self._transport(server.get_url())
673
596
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
674
597
 
675
598
    def test_http_get(self):
676
 
        t = self.get_readonly_transport()
 
599
        server = self.get_readonly_server()
 
600
        t = self._transport(server.get_url())
677
601
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
678
602
 
679
603
 
684
608
        """Fakes handling a single HTTP request, returns a bad status"""
685
609
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
686
610
        self.wfile.write("Invalid status line\r\n")
687
 
        # If we don't close the connection pycurl will hang. Since this is a
688
 
        # stress test we don't *have* to respect the protocol, but we don't
689
 
        # have to sabotage it too much either.
690
 
        self.close_connection = True
691
611
        return False
692
612
 
693
613
 
699
619
 
700
620
    _req_handler_class = InvalidStatusRequestHandler
701
621
 
 
622
    def test_http_has(self):
 
623
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
624
            raise tests.KnownFailure(
 
625
                'pycurl hangs if the server send back garbage')
 
626
        super(TestInvalidStatusServer, self).test_http_has()
 
627
 
 
628
    def test_http_get(self):
 
629
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
630
            raise tests.KnownFailure(
 
631
                'pycurl hangs if the server send back garbage')
 
632
        super(TestInvalidStatusServer, self).test_http_get()
 
633
 
702
634
 
703
635
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
704
636
    """Whatever request comes in, returns a bad protocol version"""
720
652
    _req_handler_class = BadProtocolRequestHandler
721
653
 
722
654
    def setUp(self):
723
 
        if self._testing_pycurl():
 
655
        if pycurl_present and self._transport == PyCurlTransport:
724
656
            raise tests.TestNotApplicable(
725
657
                "pycurl doesn't check the protocol version")
726
658
        super(TestBadProtocolServer, self).setUp()
727
659
 
728
660
    def test_http_has(self):
729
 
        t = self.get_readonly_transport()
 
661
        server = self.get_readonly_server()
 
662
        t = self._transport(server.get_url())
730
663
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
731
664
 
732
665
    def test_http_get(self):
733
 
        t = self.get_readonly_transport()
 
666
        server = self.get_readonly_server()
 
667
        t = self._transport(server.get_url())
734
668
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
735
669
 
736
670
 
750
684
    _req_handler_class = ForbiddenRequestHandler
751
685
 
752
686
    def test_http_has(self):
753
 
        t = self.get_readonly_transport()
 
687
        server = self.get_readonly_server()
 
688
        t = self._transport(server.get_url())
754
689
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
755
690
 
756
691
    def test_http_get(self):
757
 
        t = self.get_readonly_transport()
 
692
        server = self.get_readonly_server()
 
693
        t = self._transport(server.get_url())
758
694
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
759
695
 
760
696
 
766
702
        self.assertEqual(None, server.host)
767
703
        self.assertEqual(None, server.port)
768
704
 
769
 
    def test_setUp_and_stop(self):
 
705
    def test_setUp_and_tearDown(self):
770
706
        server = RecordingServer(expect_body_tail=None)
771
 
        server.start_server()
 
707
        server.setUp()
772
708
        try:
773
709
            self.assertNotEqual(None, server.host)
774
710
            self.assertNotEqual(None, server.port)
775
711
        finally:
776
 
            server.stop_server()
 
712
            server.tearDown()
777
713
        self.assertEqual(None, server.host)
778
714
        self.assertEqual(None, server.port)
779
715
 
780
716
    def test_send_receive_bytes(self):
781
 
        server = RecordingServer(expect_body_tail='c', scheme='http')
782
 
        self.start_server(server)
 
717
        server = RecordingServer(expect_body_tail='c')
 
718
        server.setUp()
 
719
        self.addCleanup(server.tearDown)
783
720
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
784
721
        sock.connect((server.host, server.port))
785
722
        sock.sendall('abc')
799
736
        self.build_tree_contents([('a', '0123456789')],)
800
737
 
801
738
    def test_readv(self):
802
 
        t = self.get_readonly_transport()
 
739
        server = self.get_readonly_server()
 
740
        t = self._transport(server.get_url())
803
741
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
804
742
        self.assertEqual(l[0], (0, '0'))
805
743
        self.assertEqual(l[1], (1, '1'))
807
745
        self.assertEqual(l[3], (9, '9'))
808
746
 
809
747
    def test_readv_out_of_order(self):
810
 
        t = self.get_readonly_transport()
 
748
        server = self.get_readonly_server()
 
749
        t = self._transport(server.get_url())
811
750
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
812
751
        self.assertEqual(l[0], (1, '1'))
813
752
        self.assertEqual(l[1], (9, '9'))
815
754
        self.assertEqual(l[3], (3, '34'))
816
755
 
817
756
    def test_readv_invalid_ranges(self):
818
 
        t = self.get_readonly_transport()
 
757
        server = self.get_readonly_server()
 
758
        t = self._transport(server.get_url())
819
759
 
820
760
        # This is intentionally reading off the end of the file
821
761
        # since we are sure that it cannot get there
829
769
 
830
770
    def test_readv_multiple_get_requests(self):
831
771
        server = self.get_readonly_server()
832
 
        t = self.get_readonly_transport()
 
772
        t = self._transport(server.get_url())
833
773
        # force transport to issue multiple requests
834
774
        t._max_readv_combine = 1
835
775
        t._max_get_ranges = 1
843
783
 
844
784
    def test_readv_get_max_size(self):
845
785
        server = self.get_readonly_server()
846
 
        t = self.get_readonly_transport()
 
786
        t = self._transport(server.get_url())
847
787
        # force transport to issue multiple requests by limiting the number of
848
788
        # bytes by request. Note that this apply to coalesced offsets only, a
849
789
        # single range will keep its size even if bigger than the limit.
858
798
 
859
799
    def test_complete_readv_leave_pipe_clean(self):
860
800
        server = self.get_readonly_server()
861
 
        t = self.get_readonly_transport()
 
801
        t = self._transport(server.get_url())
862
802
        # force transport to issue multiple requests
863
803
        t._get_max_size = 2
864
 
        list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
 
804
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
865
805
        # The server should have issued 3 requests
866
806
        self.assertEqual(3, server.GET_request_nb)
867
807
        self.assertEqual('0123456789', t.get_bytes('a'))
869
809
 
870
810
    def test_incomplete_readv_leave_pipe_clean(self):
871
811
        server = self.get_readonly_server()
872
 
        t = self.get_readonly_transport()
 
812
        t = self._transport(server.get_url())
873
813
        # force transport to issue multiple requests
874
814
        t._get_max_size = 2
875
815
        # Don't collapse readv results into a list so that we leave unread
876
816
        # bytes on the socket
877
817
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
878
818
        self.assertEqual((0, '0'), ireadv.next())
879
 
        # The server should have issued one request so far
 
819
        # The server should have issued one request so far 
880
820
        self.assertEqual(1, server.GET_request_nb)
881
821
        self.assertEqual('0123456789', t.get_bytes('a'))
882
822
        # get_bytes issued an additional request, the readv pending ones are
944
884
    def get_multiple_ranges(self, file, file_size, ranges):
945
885
        self.send_response(206)
946
886
        self.send_header('Accept-Ranges', 'bytes')
947
 
        # XXX: this is strange; the 'random' name below seems undefined and
948
 
        # yet the tests pass -- mbp 2010-10-11 bug 658773
949
887
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
950
888
        self.send_header("Content-Type",
951
889
                         "multipart/byteranges; boundary=%s" % boundary)
1013
951
                return
1014
952
            self.send_range_content(file, start, end - start + 1)
1015
953
            cur += 1
1016
 
        # Final boundary
 
954
        # No final boundary
1017
955
        self.wfile.write(boundary_line)
1018
956
 
1019
957
 
1027
965
 
1028
966
    def test_readv_with_short_reads(self):
1029
967
        server = self.get_readonly_server()
1030
 
        t = self.get_readonly_transport()
 
968
        t = self._transport(server.get_url())
1031
969
        # Force separate ranges for each offset
1032
970
        t._bytes_to_read_before_seek = 0
1033
971
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1048
986
        # that mode
1049
987
        self.assertEqual('single', t._range_hint)
1050
988
 
1051
 
 
1052
 
class TruncatedBeforeBoundaryRequestHandler(
1053
 
    http_server.TestingHTTPRequestHandler):
1054
 
    """Truncation before a boundary, like in bug 198646"""
1055
 
 
1056
 
    _truncated_ranges = 1
1057
 
 
1058
 
    def get_multiple_ranges(self, file, file_size, ranges):
1059
 
        self.send_response(206)
1060
 
        self.send_header('Accept-Ranges', 'bytes')
1061
 
        boundary = 'tagada'
1062
 
        self.send_header('Content-Type',
1063
 
                         'multipart/byteranges; boundary=%s' % boundary)
1064
 
        boundary_line = '--%s\r\n' % boundary
1065
 
        # Calculate the Content-Length
1066
 
        content_length = 0
1067
 
        for (start, end) in ranges:
1068
 
            content_length += len(boundary_line)
1069
 
            content_length += self._header_line_length(
1070
 
                'Content-type', 'application/octet-stream')
1071
 
            content_length += self._header_line_length(
1072
 
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
1073
 
            content_length += len('\r\n') # end headers
1074
 
            content_length += end - start # + 1
1075
 
        content_length += len(boundary_line)
1076
 
        self.send_header('Content-length', content_length)
1077
 
        self.end_headers()
1078
 
 
1079
 
        # Send the multipart body
1080
 
        cur = 0
1081
 
        for (start, end) in ranges:
1082
 
            if cur + self._truncated_ranges >= len(ranges):
1083
 
                # Abruptly ends the response and close the connection
1084
 
                self.close_connection = 1
1085
 
                return
1086
 
            self.wfile.write(boundary_line)
1087
 
            self.send_header('Content-type', 'application/octet-stream')
1088
 
            self.send_header('Content-Range', 'bytes %d-%d/%d'
1089
 
                             % (start, end, file_size))
1090
 
            self.end_headers()
1091
 
            self.send_range_content(file, start, end - start + 1)
1092
 
            cur += 1
1093
 
        # Final boundary
1094
 
        self.wfile.write(boundary_line)
1095
 
 
1096
 
 
1097
 
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
1098
 
    """Tests the case of bug 198646, disconnecting before a boundary."""
1099
 
 
1100
 
    _req_handler_class = TruncatedBeforeBoundaryRequestHandler
1101
 
 
1102
 
    def setUp(self):
1103
 
        super(TestTruncatedBeforeBoundary, self).setUp()
1104
 
        self.build_tree_contents([('a', '0123456789')],)
1105
 
 
1106
 
    def test_readv_with_short_reads(self):
1107
 
        server = self.get_readonly_server()
1108
 
        t = self.get_readonly_transport()
1109
 
        # Force separate ranges for each offset
1110
 
        t._bytes_to_read_before_seek = 0
1111
 
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1112
 
        self.assertEqual((0, '0'), ireadv.next())
1113
 
        self.assertEqual((2, '2'), ireadv.next())
1114
 
        self.assertEqual((4, '45'), ireadv.next())
1115
 
        self.assertEqual((9, '9'), ireadv.next())
1116
 
 
1117
 
 
1118
989
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1119
990
    """Errors out when range specifiers exceed the limit"""
1120
991
 
1144
1015
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1145
1016
    """Tests readv requests against a server erroring out on too much ranges."""
1146
1017
 
1147
 
    scenarios = multiply_scenarios(
1148
 
        vary_by_http_client_implementation(),
1149
 
        vary_by_http_protocol_version(),
1150
 
        )
1151
 
 
1152
1018
    # Requests with more range specifiers will error out
1153
1019
    range_limit = 3
1154
1020
 
1156
1022
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1157
1023
                                      protocol_version=self._protocol_version)
1158
1024
 
 
1025
    def get_transport(self):
 
1026
        return self._transport(self.get_readonly_server().get_url())
 
1027
 
1159
1028
    def setUp(self):
1160
1029
        http_utils.TestCaseWithWebserver.setUp(self)
1161
1030
        # We need to manipulate ranges that correspond to real chunks in the
1165
1034
        self.build_tree_contents([('a', content)],)
1166
1035
 
1167
1036
    def test_few_ranges(self):
1168
 
        t = self.get_readonly_transport()
 
1037
        t = self.get_transport()
1169
1038
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1170
1039
        self.assertEqual(l[0], (0, '0000'))
1171
1040
        self.assertEqual(l[1], (1024, '0001'))
1172
1041
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1173
1042
 
1174
1043
    def test_more_ranges(self):
1175
 
        t = self.get_readonly_transport()
 
1044
        t = self.get_transport()
1176
1045
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1177
1046
        self.assertEqual(l[0], (0, '0000'))
1178
1047
        self.assertEqual(l[1], (1024, '0001'))
1189
1058
    Only the urllib implementation is tested here.
1190
1059
    """
1191
1060
 
 
1061
    def setUp(self):
 
1062
        tests.TestCase.setUp(self)
 
1063
        self._old_env = {}
 
1064
 
 
1065
    def tearDown(self):
 
1066
        self._restore_env()
 
1067
        tests.TestCase.tearDown(self)
 
1068
 
 
1069
    def _install_env(self, env):
 
1070
        for name, value in env.iteritems():
 
1071
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1072
 
 
1073
    def _restore_env(self):
 
1074
        for name, value in self._old_env.iteritems():
 
1075
            osutils.set_or_unset_env(name, value)
 
1076
 
1192
1077
    def _proxied_request(self):
1193
1078
        handler = _urllib2_wrappers.ProxyHandler()
1194
 
        request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
 
1079
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1195
1080
        handler.set_proxy(request, 'http')
1196
1081
        return request
1197
1082
 
1198
 
    def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1199
 
        handler = _urllib2_wrappers.ProxyHandler()
1200
 
        self.assertEquals(expected,
1201
 
                          handler.evaluate_proxy_bypass(host, no_proxy))
1202
 
 
1203
1083
    def test_empty_user(self):
1204
 
        self.overrideEnv('http_proxy', 'http://bar.com')
1205
 
        request = self._proxied_request()
1206
 
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1207
 
 
1208
 
    def test_user_with_at(self):
1209
 
        self.overrideEnv('http_proxy',
1210
 
                         'http://username@domain:password@proxy_host:1234')
 
1084
        self._install_env({'http_proxy': 'http://bar.com'})
1211
1085
        request = self._proxied_request()
1212
1086
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1213
1087
 
1214
1088
    def test_invalid_proxy(self):
1215
1089
        """A proxy env variable without scheme"""
1216
 
        self.overrideEnv('http_proxy', 'host:1234')
 
1090
        self._install_env({'http_proxy': 'host:1234'})
1217
1091
        self.assertRaises(errors.InvalidURL, self._proxied_request)
1218
1092
 
1219
 
    def test_evaluate_proxy_bypass_true(self):
1220
 
        """The host is not proxied"""
1221
 
        self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1222
 
        self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1223
 
 
1224
 
    def test_evaluate_proxy_bypass_false(self):
1225
 
        """The host is proxied"""
1226
 
        self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1227
 
 
1228
 
    def test_evaluate_proxy_bypass_unknown(self):
1229
 
        """The host is not explicitly proxied"""
1230
 
        self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1231
 
        self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1232
 
 
1233
 
    def test_evaluate_proxy_bypass_empty_entries(self):
1234
 
        """Ignore empty entries"""
1235
 
        self.assertEvaluateProxyBypass(None, 'example.com', '')
1236
 
        self.assertEvaluateProxyBypass(None, 'example.com', ',')
1237
 
        self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1238
 
 
1239
1093
 
1240
1094
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1241
1095
    """Tests proxy server.
1246
1100
    to the file names).
1247
1101
    """
1248
1102
 
1249
 
    scenarios = multiply_scenarios(
1250
 
        vary_by_http_client_implementation(),
1251
 
        vary_by_http_protocol_version(),
1252
 
        )
1253
 
 
1254
1103
    # FIXME: We don't have an https server available, so we don't
1255
 
    # test https connections. --vila toolongago
 
1104
    # test https connections.
1256
1105
 
1257
1106
    def setUp(self):
1258
1107
        super(TestProxyHttpServer, self).setUp()
1259
 
        self.transport_secondary_server = http_utils.ProxyServer
1260
1108
        self.build_tree_contents([('foo', 'contents of foo\n'),
1261
1109
                                  ('foo-proxied', 'proxied contents of foo\n')])
1262
1110
        # Let's setup some attributes for tests
1263
 
        server = self.get_readonly_server()
1264
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1111
        self.server = self.get_readonly_server()
 
1112
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1265
1113
        if self._testing_pycurl():
1266
1114
            # Oh my ! pycurl does not check for the port as part of
1267
1115
            # no_proxy :-( So we just test the host part
1268
 
            self.no_proxy_host = server.host
 
1116
            self.no_proxy_host = 'localhost'
1269
1117
        else:
1270
 
            self.no_proxy_host = self.server_host_port
 
1118
            self.no_proxy_host = self.proxy_address
1271
1119
        # The secondary server is the proxy
1272
 
        self.proxy_url = self.get_secondary_url()
 
1120
        self.proxy = self.get_secondary_server()
 
1121
        self.proxy_url = self.proxy.get_url()
 
1122
        self._old_env = {}
1273
1123
 
1274
1124
    def _testing_pycurl(self):
1275
 
        # TODO: This is duplicated for lots of the classes in this file
1276
 
        return (features.pycurl.available()
1277
 
                and self._transport == PyCurlTransport)
1278
 
 
1279
 
    def assertProxied(self):
1280
 
        t = self.get_readonly_transport()
1281
 
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1282
 
 
1283
 
    def assertNotProxied(self):
1284
 
        t = self.get_readonly_transport()
1285
 
        self.assertEqual('contents of foo\n', t.get('foo').read())
 
1125
        return pycurl_present and self._transport == PyCurlTransport
 
1126
 
 
1127
    def create_transport_secondary_server(self):
 
1128
        """Creates an http server that will serve files with
 
1129
        '-proxied' appended to their names.
 
1130
        """
 
1131
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
 
1132
 
 
1133
    def _install_env(self, env):
 
1134
        for name, value in env.iteritems():
 
1135
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1136
 
 
1137
    def _restore_env(self):
 
1138
        for name, value in self._old_env.iteritems():
 
1139
            osutils.set_or_unset_env(name, value)
 
1140
 
 
1141
    def proxied_in_env(self, env):
 
1142
        self._install_env(env)
 
1143
        url = self.server.get_url()
 
1144
        t = self._transport(url)
 
1145
        try:
 
1146
            self.assertEqual(t.get('foo').read(), 'proxied contents of foo\n')
 
1147
        finally:
 
1148
            self._restore_env()
 
1149
 
 
1150
    def not_proxied_in_env(self, env):
 
1151
        self._install_env(env)
 
1152
        url = self.server.get_url()
 
1153
        t = self._transport(url)
 
1154
        try:
 
1155
            self.assertEqual(t.get('foo').read(), 'contents of foo\n')
 
1156
        finally:
 
1157
            self._restore_env()
1286
1158
 
1287
1159
    def test_http_proxy(self):
1288
 
        self.overrideEnv('http_proxy', self.proxy_url)
1289
 
        self.assertProxied()
 
1160
        self.proxied_in_env({'http_proxy': self.proxy_url})
1290
1161
 
1291
1162
    def test_HTTP_PROXY(self):
1292
1163
        if self._testing_pycurl():
1295
1166
            # about. Should we ?)
1296
1167
            raise tests.TestNotApplicable(
1297
1168
                'pycurl does not check HTTP_PROXY for security reasons')
1298
 
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1299
 
        self.assertProxied()
 
1169
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1300
1170
 
1301
1171
    def test_all_proxy(self):
1302
 
        self.overrideEnv('all_proxy', self.proxy_url)
1303
 
        self.assertProxied()
 
1172
        self.proxied_in_env({'all_proxy': self.proxy_url})
1304
1173
 
1305
1174
    def test_ALL_PROXY(self):
1306
 
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1307
 
        self.assertProxied()
 
1175
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1308
1176
 
1309
1177
    def test_http_proxy_with_no_proxy(self):
1310
 
        self.overrideEnv('no_proxy', self.no_proxy_host)
1311
 
        self.overrideEnv('http_proxy', self.proxy_url)
1312
 
        self.assertNotProxied()
 
1178
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
 
1179
                                 'no_proxy': self.no_proxy_host})
1313
1180
 
1314
1181
    def test_HTTP_PROXY_with_NO_PROXY(self):
1315
1182
        if self._testing_pycurl():
1316
1183
            raise tests.TestNotApplicable(
1317
1184
                'pycurl does not check HTTP_PROXY for security reasons')
1318
 
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1319
 
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1320
 
        self.assertNotProxied()
 
1185
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
 
1186
                                 'NO_PROXY': self.no_proxy_host})
1321
1187
 
1322
1188
    def test_all_proxy_with_no_proxy(self):
1323
 
        self.overrideEnv('no_proxy', self.no_proxy_host)
1324
 
        self.overrideEnv('all_proxy', self.proxy_url)
1325
 
        self.assertNotProxied()
 
1189
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
 
1190
                                 'no_proxy': self.no_proxy_host})
1326
1191
 
1327
1192
    def test_ALL_PROXY_with_NO_PROXY(self):
1328
 
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1329
 
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1330
 
        self.assertNotProxied()
 
1193
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
 
1194
                                 'NO_PROXY': self.no_proxy_host})
1331
1195
 
1332
1196
    def test_http_proxy_without_scheme(self):
1333
 
        self.overrideEnv('http_proxy', self.server_host_port)
1334
1197
        if self._testing_pycurl():
1335
1198
            # pycurl *ignores* invalid proxy env variables. If that ever change
1336
1199
            # in the future, this test will fail indicating that pycurl do not
1337
1200
            # ignore anymore such variables.
1338
 
            self.assertNotProxied()
 
1201
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1339
1202
        else:
1340
 
            self.assertRaises(errors.InvalidURL, self.assertProxied)
 
1203
            self.assertRaises(errors.InvalidURL,
 
1204
                              self.proxied_in_env,
 
1205
                              {'http_proxy': self.proxy_address})
1341
1206
 
1342
1207
 
1343
1208
class TestRanges(http_utils.TestCaseWithWebserver):
1344
1209
    """Test the Range header in GET methods."""
1345
1210
 
1346
 
    scenarios = multiply_scenarios(
1347
 
        vary_by_http_client_implementation(),
1348
 
        vary_by_http_protocol_version(),
1349
 
        )
1350
 
 
1351
1211
    def setUp(self):
1352
1212
        http_utils.TestCaseWithWebserver.setUp(self)
1353
1213
        self.build_tree_contents([('a', '0123456789')],)
 
1214
        server = self.get_readonly_server()
 
1215
        self.transport = self._transport(server.get_url())
1354
1216
 
1355
1217
    def create_transport_readonly_server(self):
1356
1218
        return http_server.HttpServer(protocol_version=self._protocol_version)
1357
1219
 
1358
1220
    def _file_contents(self, relpath, ranges):
1359
 
        t = self.get_readonly_transport()
1360
1221
        offsets = [ (start, end - start + 1) for start, end in ranges]
1361
 
        coalesce = t._coalesce_offsets
 
1222
        coalesce = self.transport._coalesce_offsets
1362
1223
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1363
 
        code, data = t._get(relpath, coalesced)
 
1224
        code, data = self.transport._get(relpath, coalesced)
1364
1225
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1365
1226
        for start, end in ranges:
1366
1227
            data.seek(start)
1367
1228
            yield data.read(end - start + 1)
1368
1229
 
1369
1230
    def _file_tail(self, relpath, tail_amount):
1370
 
        t = self.get_readonly_transport()
1371
 
        code, data = t._get(relpath, [], tail_amount)
 
1231
        code, data = self.transport._get(relpath, [], tail_amount)
1372
1232
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1373
1233
        data.seek(-tail_amount, 2)
1374
1234
        return data.read(tail_amount)
1393
1253
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1394
1254
    """Test redirection between http servers."""
1395
1255
 
1396
 
    scenarios = multiply_scenarios(
1397
 
        vary_by_http_client_implementation(),
1398
 
        vary_by_http_protocol_version(),
1399
 
        )
 
1256
    def create_transport_secondary_server(self):
 
1257
        """Create the secondary server redirecting to the primary server"""
 
1258
        new = self.get_readonly_server()
 
1259
 
 
1260
        redirecting = http_utils.HTTPServerRedirecting(
 
1261
            protocol_version=self._protocol_version)
 
1262
        redirecting.redirect_to(new.host, new.port)
 
1263
        return redirecting
1400
1264
 
1401
1265
    def setUp(self):
1402
1266
        super(TestHTTPRedirections, self).setUp()
1405
1269
                                  '# Bazaar revision bundle v0.9\n#\n')
1406
1270
                                  ],)
1407
1271
 
 
1272
        self.old_transport = self._transport(self.old_server.get_url())
 
1273
 
1408
1274
    def test_redirected(self):
1409
 
        self.assertRaises(errors.RedirectRequested,
1410
 
                          self.get_old_transport().get, 'a')
1411
 
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
 
1275
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1276
        t = self._transport(self.new_server.get_url())
 
1277
        self.assertEqual('0123456789', t.get('a').read())
 
1278
 
 
1279
    def test_read_redirected_bundle_from_url(self):
 
1280
        from bzrlib.bundle import read_bundle_from_url
 
1281
        url = self.old_transport.abspath('bundle')
 
1282
        bundle = read_bundle_from_url(url)
 
1283
        # If read_bundle_from_url was successful we get an empty bundle
 
1284
        self.assertEqual([], bundle.revisions)
1412
1285
 
1413
1286
 
1414
1287
class RedirectedRequest(_urllib2_wrappers.Request):
1423
1296
        # Since the tests using this class will replace
1424
1297
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1425
1298
        # or we'll loop.
1426
 
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
 
1299
        RedirectedRequest.init_orig(self, method, url, args, kwargs)
1427
1300
        self.follow_redirections = True
1428
1301
 
1429
1302
 
1430
 
def install_redirected_request(test):
1431
 
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1432
 
 
1433
 
 
1434
 
def cleanup_http_redirection_connections(test):
1435
 
    # Some sockets are opened but never seen by _urllib, so we trap them at
1436
 
    # the _urllib2_wrappers level to be able to clean them up.
1437
 
    def socket_disconnect(sock):
1438
 
        try:
1439
 
            sock.shutdown(socket.SHUT_RDWR)
1440
 
            sock.close()
1441
 
        except socket.error:
1442
 
            pass
1443
 
    def connect(connection):
1444
 
        test.http_connect_orig(connection)
1445
 
        test.addCleanup(socket_disconnect, connection.sock)
1446
 
    test.http_connect_orig = test.overrideAttr(
1447
 
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1448
 
    def connect(connection):
1449
 
        test.https_connect_orig(connection)
1450
 
        test.addCleanup(socket_disconnect, connection.sock)
1451
 
    test.https_connect_orig = test.overrideAttr(
1452
 
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1453
 
 
1454
 
 
1455
1303
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1456
1304
    """Test redirections.
1457
1305
 
1466
1314
    -- vila 20070212
1467
1315
    """
1468
1316
 
1469
 
    scenarios = multiply_scenarios(
1470
 
        vary_by_http_client_implementation(),
1471
 
        vary_by_http_protocol_version(),
1472
 
        )
1473
 
 
1474
1317
    def setUp(self):
1475
 
        if (features.pycurl.available()
1476
 
            and self._transport == PyCurlTransport):
 
1318
        if pycurl_present and self._transport == PyCurlTransport:
1477
1319
            raise tests.TestNotApplicable(
1478
 
                "pycurl doesn't redirect silently anymore")
 
1320
                "pycurl doesn't redirect silently annymore")
1479
1321
        super(TestHTTPSilentRedirections, self).setUp()
1480
 
        install_redirected_request(self)
1481
 
        cleanup_http_redirection_connections(self)
 
1322
        self.setup_redirected_request()
 
1323
        self.addCleanup(self.cleanup_redirected_request)
1482
1324
        self.build_tree_contents([('a','a'),
1483
1325
                                  ('1/',),
1484
1326
                                  ('1/a', 'redirected once'),
1492
1334
                                  ('5/a', 'redirected 5 times'),
1493
1335
                                  ],)
1494
1336
 
 
1337
        self.old_transport = self._transport(self.old_server.get_url())
 
1338
 
 
1339
    def setup_redirected_request(self):
 
1340
        self.original_class = _urllib2_wrappers.Request
 
1341
        _urllib2_wrappers.Request = RedirectedRequest
 
1342
 
 
1343
    def cleanup_redirected_request(self):
 
1344
        _urllib2_wrappers.Request = self.original_class
 
1345
 
 
1346
    def create_transport_secondary_server(self):
 
1347
        """Create the secondary server, redirections are defined in the tests"""
 
1348
        return http_utils.HTTPServerRedirecting(
 
1349
            protocol_version=self._protocol_version)
 
1350
 
1495
1351
    def test_one_redirection(self):
1496
 
        t = self.get_old_transport()
1497
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1352
        t = self.old_transport
 
1353
 
 
1354
        req = RedirectedRequest('GET', t.abspath('a'))
 
1355
        req.follow_redirections = True
1498
1356
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1499
1357
                                       self.new_server.port)
1500
1358
        self.old_server.redirections = \
1501
1359
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1502
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1360
        self.assertEquals('redirected once',t._perform(req).read())
1503
1361
 
1504
1362
    def test_five_redirections(self):
1505
 
        t = self.get_old_transport()
1506
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1363
        t = self.old_transport
 
1364
 
 
1365
        req = RedirectedRequest('GET', t.abspath('a'))
 
1366
        req.follow_redirections = True
1507
1367
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1508
1368
                                       self.old_server.port)
1509
1369
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1515
1375
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1516
1376
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1517
1377
            ]
1518
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1378
        self.assertEquals('redirected 5 times',t._perform(req).read())
1519
1379
 
1520
1380
 
1521
1381
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1522
1382
    """Test transport.do_catching_redirections."""
1523
1383
 
1524
 
    scenarios = multiply_scenarios(
1525
 
        vary_by_http_client_implementation(),
1526
 
        vary_by_http_protocol_version(),
1527
 
        )
1528
 
 
1529
1384
    def setUp(self):
1530
1385
        super(TestDoCatchRedirections, self).setUp()
1531
1386
        self.build_tree_contents([('a', '0123456789'),],)
1532
 
        cleanup_http_redirection_connections(self)
1533
 
 
1534
 
        self.old_transport = self.get_old_transport()
1535
 
 
1536
 
    def get_a(self, t):
1537
 
        return t.get('a')
 
1387
 
 
1388
        self.old_transport = self._transport(self.old_server.get_url())
 
1389
 
 
1390
    def get_a(self, transport):
 
1391
        return transport.get('a')
1538
1392
 
1539
1393
    def test_no_redirection(self):
1540
 
        t = self.get_new_transport()
 
1394
        t = self._transport(self.new_server.get_url())
1541
1395
 
1542
1396
        # We use None for redirected so that we fail if redirected
1543
 
        self.assertEqual('0123456789',
1544
 
                         transport.do_catching_redirections(
 
1397
        self.assertEquals('0123456789',
 
1398
                          transport.do_catching_redirections(
1545
1399
                self.get_a, t, None).read())
1546
1400
 
1547
1401
    def test_one_redirection(self):
1548
1402
        self.redirections = 0
1549
1403
 
1550
 
        def redirected(t, exception, redirection_notice):
 
1404
        def redirected(transport, exception, redirection_notice):
1551
1405
            self.redirections += 1
1552
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1553
 
            return redirected_t
 
1406
            dir, file = urlutils.split(exception.target)
 
1407
            return self._transport(dir)
1554
1408
 
1555
 
        self.assertEqual('0123456789',
1556
 
                         transport.do_catching_redirections(
 
1409
        self.assertEquals('0123456789',
 
1410
                          transport.do_catching_redirections(
1557
1411
                self.get_a, self.old_transport, redirected).read())
1558
 
        self.assertEqual(1, self.redirections)
 
1412
        self.assertEquals(1, self.redirections)
1559
1413
 
1560
1414
    def test_redirection_loop(self):
1561
1415
 
1570
1424
                          self.get_a, self.old_transport, redirected)
1571
1425
 
1572
1426
 
1573
 
def _setup_authentication_config(**kwargs):
1574
 
    conf = config.AuthenticationConfig()
1575
 
    conf._get_config().update({'httptest': kwargs})
1576
 
    conf._save()
1577
 
 
1578
 
 
1579
 
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1580
 
    """Unit tests for glue by which urllib2 asks us for authentication"""
1581
 
 
1582
 
    def test_get_user_password_without_port(self):
1583
 
        """We cope if urllib2 doesn't tell us the port.
1584
 
 
1585
 
        See https://bugs.launchpad.net/bzr/+bug/654684
1586
 
        """
1587
 
        user = 'joe'
1588
 
        password = 'foo'
1589
 
        _setup_authentication_config(scheme='http', host='localhost',
1590
 
                                     user=user, password=password)
1591
 
        handler = _urllib2_wrappers.HTTPAuthHandler()
1592
 
        got_pass = handler.get_user_password(dict(
1593
 
            user='joe',
1594
 
            protocol='http',
1595
 
            host='localhost',
1596
 
            path='/',
1597
 
            realm='Realm',
1598
 
            ))
1599
 
        self.assertEquals((user, password), got_pass)
1600
 
 
1601
 
 
1602
1427
class TestAuth(http_utils.TestCaseWithWebserver):
1603
1428
    """Test authentication scheme"""
1604
1429
 
1605
 
    scenarios = multiply_scenarios(
1606
 
        vary_by_http_client_implementation(),
1607
 
        vary_by_http_protocol_version(),
1608
 
        vary_by_http_auth_scheme(),
1609
 
        )
 
1430
    _auth_header = 'Authorization'
 
1431
    _password_prompt_prefix = ''
1610
1432
 
1611
1433
    def setUp(self):
1612
1434
        super(TestAuth, self).setUp()
1615
1437
                                  ('b', 'contents of b\n'),])
1616
1438
 
1617
1439
    def create_transport_readonly_server(self):
1618
 
        server = self._auth_server(protocol_version=self._protocol_version)
1619
 
        server._url_protocol = self._url_protocol
 
1440
        if self._auth_scheme == 'basic':
 
1441
            server = http_utils.HTTPBasicAuthServer(
 
1442
                protocol_version=self._protocol_version)
 
1443
        else:
 
1444
            if self._auth_scheme != 'digest':
 
1445
                raise AssertionError('Unknown auth scheme: %r'
 
1446
                                     % self._auth_scheme)
 
1447
            server = http_utils.HTTPDigestAuthServer(
 
1448
                protocol_version=self._protocol_version)
1620
1449
        return server
1621
1450
 
1622
1451
    def _testing_pycurl(self):
1623
 
        # TODO: This is duplicated for lots of the classes in this file
1624
 
        return (features.pycurl.available()
1625
 
                and self._transport == PyCurlTransport)
 
1452
        return pycurl_present and self._transport == PyCurlTransport
1626
1453
 
1627
 
    def get_user_url(self, user, password):
 
1454
    def get_user_url(self, user=None, password=None):
1628
1455
        """Build an url embedding user and password"""
1629
1456
        url = '%s://' % self.server._url_protocol
1630
1457
        if user is not None:
1635
1462
        url += '%s:%s/' % (self.server.host, self.server.port)
1636
1463
        return url
1637
1464
 
1638
 
    def get_user_transport(self, user, password):
1639
 
        t = transport.get_transport_from_url(
1640
 
            self.get_user_url(user, password))
1641
 
        return t
 
1465
    def get_user_transport(self, user=None, password=None):
 
1466
        return self._transport(self.get_user_url(user, password))
1642
1467
 
1643
1468
    def test_no_user(self):
1644
1469
        self.server.add_user('joe', 'foo')
1645
 
        t = self.get_user_transport(None, None)
 
1470
        t = self.get_user_transport()
1646
1471
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1647
1472
        # Only one 'Authentication Required' error should occur
1648
1473
        self.assertEqual(1, self.server.auth_required_errors)
1678
1503
        # initial 'who are you' and 'this is not you, who are you')
1679
1504
        self.assertEqual(2, self.server.auth_required_errors)
1680
1505
 
1681
 
    def test_prompt_for_username(self):
1682
 
        if self._testing_pycurl():
1683
 
            raise tests.TestNotApplicable(
1684
 
                'pycurl cannot prompt, it handles auth by embedding'
1685
 
                ' user:pass in urls only')
1686
 
 
1687
 
        self.server.add_user('joe', 'foo')
1688
 
        t = self.get_user_transport(None, None)
1689
 
        stdout = tests.StringIOWrapper()
1690
 
        stderr = tests.StringIOWrapper()
1691
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1692
 
                                            stdout=stdout, stderr=stderr)
1693
 
        self.assertEqual('contents of a\n',t.get('a').read())
1694
 
        # stdin should be empty
1695
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
1696
 
        stderr.seek(0)
1697
 
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1698
 
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1699
 
        self.assertEqual('', stdout.getvalue())
1700
 
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1701
 
                                    stderr.readline())
1702
 
 
1703
1506
    def test_prompt_for_password(self):
1704
1507
        if self._testing_pycurl():
1705
1508
            raise tests.TestNotApplicable(
1709
1512
        self.server.add_user('joe', 'foo')
1710
1513
        t = self.get_user_transport('joe', None)
1711
1514
        stdout = tests.StringIOWrapper()
1712
 
        stderr = tests.StringIOWrapper()
1713
 
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1714
 
                                            stdout=stdout, stderr=stderr)
1715
 
        self.assertEqual('contents of a\n', t.get('a').read())
 
1515
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
 
1516
        self.assertEqual('contents of a\n',t.get('a').read())
1716
1517
        # stdin should be empty
1717
1518
        self.assertEqual('', ui.ui_factory.stdin.readline())
1718
1519
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1719
 
                                    stderr.getvalue())
1720
 
        self.assertEqual('', stdout.getvalue())
 
1520
                                    stdout.getvalue())
1721
1521
        # And we shouldn't prompt again for a different request
1722
1522
        # against the same transport.
1723
1523
        self.assertEqual('contents of b\n',t.get('b').read())
1733
1533
                              % (scheme.upper(),
1734
1534
                                 user, self.server.host, self.server.port,
1735
1535
                                 self.server.auth_realm)))
1736
 
        self.assertEqual(expected_prompt, actual_prompt)
1737
 
 
1738
 
    def _expected_username_prompt(self, scheme):
1739
 
        return (self._username_prompt_prefix
1740
 
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1741
 
                                 self.server.host, self.server.port,
1742
 
                                 self.server.auth_realm))
 
1536
        self.assertEquals(expected_prompt, actual_prompt)
1743
1537
 
1744
1538
    def test_no_prompt_for_password_when_using_auth_config(self):
1745
1539
        if self._testing_pycurl():
1753
1547
        self.server.add_user(user, password)
1754
1548
        t = self.get_user_transport(user, None)
1755
1549
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1756
 
                                            stderr=tests.StringIOWrapper())
 
1550
                                            stdout=tests.StringIOWrapper())
1757
1551
        # Create a minimal config file with the right password
1758
 
        _setup_authentication_config(scheme='http', port=self.server.port,
1759
 
                                     user=user, password=password)
 
1552
        conf = config.AuthenticationConfig()
 
1553
        conf._get_config().update(
 
1554
            {'httptest': {'scheme': 'http', 'port': self.server.port,
 
1555
                          'user': user, 'password': password}})
 
1556
        conf._save()
1760
1557
        # Issue a request to the server to connect
1761
1558
        self.assertEqual('contents of a\n',t.get('a').read())
1762
1559
        # stdin should have  been left untouched
1765
1562
        self.assertEqual(1, self.server.auth_required_errors)
1766
1563
 
1767
1564
    def test_changing_nonce(self):
1768
 
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1769
 
                                     http_utils.ProxyDigestAuthServer):
1770
 
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
 
1565
        if self._auth_scheme != 'digest':
 
1566
            raise tests.TestNotApplicable('HTTP auth digest only test')
1771
1567
        if self._testing_pycurl():
1772
 
            self.knownFailure(
 
1568
            raise tests.KnownFailure(
1773
1569
                'pycurl does not handle a nonce change')
1774
1570
        self.server.add_user('joe', 'foo')
1775
1571
        t = self.get_user_transport('joe', 'foo')
1785
1581
        # initial 'who are you' and a second 'who are you' with the new nonce)
1786
1582
        self.assertEqual(2, self.server.auth_required_errors)
1787
1583
 
1788
 
    def test_user_from_auth_conf(self):
1789
 
        if self._testing_pycurl():
1790
 
            raise tests.TestNotApplicable(
1791
 
                'pycurl does not support authentication.conf')
1792
 
        user = 'joe'
1793
 
        password = 'foo'
1794
 
        self.server.add_user(user, password)
1795
 
        _setup_authentication_config(scheme='http', port=self.server.port,
1796
 
                                     user=user, password=password)
1797
 
        t = self.get_user_transport(None, None)
1798
 
        # Issue a request to the server to connect
1799
 
        self.assertEqual('contents of a\n', t.get('a').read())
1800
 
        # Only one 'Authentication Required' error should occur
1801
 
        self.assertEqual(1, self.server.auth_required_errors)
1802
 
 
1803
 
    def test_no_credential_leaks_in_log(self):
1804
 
        self.overrideAttr(debug, 'debug_flags', set(['http']))
1805
 
        user = 'joe'
1806
 
        password = 'very-sensitive-password'
1807
 
        self.server.add_user(user, password)
1808
 
        t = self.get_user_transport(user, password)
1809
 
        # Capture the debug calls to mutter
1810
 
        self.mutters = []
1811
 
        def mutter(*args):
1812
 
            lines = args[0] % args[1:]
1813
 
            # Some calls output multiple lines, just split them now since we
1814
 
            # care about a single one later.
1815
 
            self.mutters.extend(lines.splitlines())
1816
 
        self.overrideAttr(trace, 'mutter', mutter)
1817
 
        # Issue a request to the server to connect
1818
 
        self.assertEqual(True, t.has('a'))
1819
 
        # Only one 'Authentication Required' error should occur
1820
 
        self.assertEqual(1, self.server.auth_required_errors)
1821
 
        # Since the authentification succeeded, there should be a corresponding
1822
 
        # debug line
1823
 
        sent_auth_headers = [line for line in self.mutters
1824
 
                             if line.startswith('> %s' % (self._auth_header,))]
1825
 
        self.assertLength(1, sent_auth_headers)
1826
 
        self.assertStartsWith(sent_auth_headers[0],
1827
 
                              '> %s: <masked>' % (self._auth_header,))
1828
1584
 
1829
1585
 
1830
1586
class TestProxyAuth(TestAuth):
1831
 
    """Test proxy authentication schemes.
1832
 
 
1833
 
    This inherits from TestAuth to tweak the setUp and filter some failing
1834
 
    tests.
1835
 
    """
1836
 
 
1837
 
    scenarios = multiply_scenarios(
1838
 
        vary_by_http_client_implementation(),
1839
 
        vary_by_http_protocol_version(),
1840
 
        vary_by_http_proxy_auth_scheme(),
1841
 
        )
 
1587
    """Test proxy authentication schemes."""
 
1588
 
 
1589
    _auth_header = 'Proxy-authorization'
 
1590
    _password_prompt_prefix='Proxy '
1842
1591
 
1843
1592
    def setUp(self):
1844
1593
        super(TestProxyAuth, self).setUp()
 
1594
        self._old_env = {}
 
1595
        self.addCleanup(self._restore_env)
1845
1596
        # Override the contents to avoid false positives
1846
1597
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1847
1598
                                  ('b', 'not proxied contents of b\n'),
1849
1600
                                  ('b-proxied', 'contents of b\n'),
1850
1601
                                  ])
1851
1602
 
1852
 
    def get_user_transport(self, user, password):
1853
 
        self.overrideEnv('all_proxy', self.get_user_url(user, password))
1854
 
        return TestAuth.get_user_transport(self, user, password)
 
1603
    def create_transport_readonly_server(self):
 
1604
        if self._auth_scheme == 'basic':
 
1605
            server = http_utils.ProxyBasicAuthServer(
 
1606
                protocol_version=self._protocol_version)
 
1607
        else:
 
1608
            if self._auth_scheme != 'digest':
 
1609
                raise AssertionError('Unknown auth scheme: %r'
 
1610
                                     % self._auth_scheme)
 
1611
            server = http_utils.ProxyDigestAuthServer(
 
1612
                protocol_version=self._protocol_version)
 
1613
        return server
 
1614
 
 
1615
    def get_user_transport(self, user=None, password=None):
 
1616
        self._install_env({'all_proxy': self.get_user_url(user, password)})
 
1617
        return self._transport(self.server.get_url())
 
1618
 
 
1619
    def _install_env(self, env):
 
1620
        for name, value in env.iteritems():
 
1621
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1622
 
 
1623
    def _restore_env(self):
 
1624
        for name, value in self._old_env.iteritems():
 
1625
            osutils.set_or_unset_env(name, value)
1855
1626
 
1856
1627
    def test_empty_pass(self):
1857
1628
        if self._testing_pycurl():
1858
1629
            import pycurl
1859
1630
            if pycurl.version_info()[1] < '7.16.0':
1860
 
                self.knownFailure(
 
1631
                raise tests.KnownFailure(
1861
1632
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1862
1633
        super(TestProxyAuth, self).test_empty_pass()
1863
1634
 
1876
1647
        self.readfile = StringIO(socket_read_content)
1877
1648
        self.writefile = StringIO()
1878
1649
        self.writefile.close = lambda: None
1879
 
        self.close = lambda: None
1880
1650
 
1881
1651
    def makefile(self, mode='r', bufsize=None):
1882
1652
        if 'r' in mode:
1887
1657
 
1888
1658
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1889
1659
 
1890
 
    scenarios = multiply_scenarios(
1891
 
        vary_by_http_client_implementation(),
1892
 
        vary_by_http_protocol_version(),
1893
 
        )
1894
 
 
1895
1660
    def setUp(self):
1896
1661
        super(SmartHTTPTunnellingTest, self).setUp()
1897
1662
        # We use the VFS layer as part of HTTP tunnelling tests.
1898
 
        self.overrideEnv('BZR_NO_SMART_VFS', None)
 
1663
        self._captureVar('BZR_NO_SMART_VFS', None)
1899
1664
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1900
 
        self.http_server = self.get_readonly_server()
1901
1665
 
1902
1666
    def create_transport_readonly_server(self):
1903
 
        server = http_utils.HTTPServerWithSmarts(
 
1667
        return http_utils.HTTPServerWithSmarts(
1904
1668
            protocol_version=self._protocol_version)
1905
 
        server._url_protocol = self._url_protocol
1906
 
        return server
1907
 
 
1908
 
    def test_open_bzrdir(self):
1909
 
        branch = self.make_branch('relpath')
1910
 
        url = self.http_server.get_url() + 'relpath'
1911
 
        bd = bzrdir.BzrDir.open(url)
1912
 
        self.addCleanup(bd.transport.disconnect)
1913
 
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1914
1669
 
1915
1670
    def test_bulk_data(self):
1916
1671
        # We should be able to send and receive bulk data in a single message.
1917
1672
        # The 'readv' command in the smart protocol both sends and receives
1918
1673
        # bulk data, so we use that.
1919
1674
        self.build_tree(['data-file'])
1920
 
        http_transport = transport.get_transport_from_url(
1921
 
            self.http_server.get_url())
 
1675
        http_server = self.get_readonly_server()
 
1676
        http_transport = self._transport(http_server.get_url())
1922
1677
        medium = http_transport.get_smart_medium()
1923
1678
        # Since we provide the medium, the url below will be mostly ignored
1924
1679
        # during the test, as long as the path is '/'.
1932
1687
        post_body = 'hello\n'
1933
1688
        expected_reply_body = 'ok\x012\n'
1934
1689
 
1935
 
        http_transport = transport.get_transport_from_url(
1936
 
            self.http_server.get_url())
 
1690
        http_server = self.get_readonly_server()
 
1691
        http_transport = self._transport(http_server.get_url())
1937
1692
        medium = http_transport.get_smart_medium()
1938
1693
        response = medium.send_http_smart_request(post_body)
1939
1694
        reply_body = response.read()
1940
1695
        self.assertEqual(expected_reply_body, reply_body)
1941
1696
 
1942
1697
    def test_smart_http_server_post_request_handler(self):
1943
 
        httpd = self.http_server.server
 
1698
        httpd = self.get_readonly_server()._get_httpd()
1944
1699
 
1945
1700
        socket = SampleSocket(
1946
1701
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1964
1719
        self.assertEndsWith(response, expected_end_of_response)
1965
1720
 
1966
1721
 
1967
 
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1968
 
    """No smart server here request handler."""
1969
 
 
1970
 
    def do_POST(self):
1971
 
        self.send_error(403, "Forbidden")
1972
 
 
1973
 
 
1974
 
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1975
 
    """Test smart client behaviour against an http server without smarts."""
1976
 
 
1977
 
    _req_handler_class = ForbiddenRequestHandler
1978
 
 
1979
 
    def test_probe_smart_server(self):
1980
 
        """Test error handling against server refusing smart requests."""
1981
 
        t = self.get_readonly_transport()
1982
 
        # No need to build a valid smart request here, the server will not even
1983
 
        # try to interpret it.
1984
 
        self.assertRaises(errors.SmartProtocolError,
1985
 
                          t.get_smart_medium().send_http_smart_request,
1986
 
                          'whatever')
1987
 
 
1988
 
 
1989
 
class Test_redirected_to(tests.TestCase):
1990
 
 
1991
 
    scenarios = vary_by_http_client_implementation()
1992
 
 
1993
 
    def test_redirected_to_subdir(self):
1994
 
        t = self._transport('http://www.example.com/foo')
1995
 
        r = t._redirected_to('http://www.example.com/foo',
1996
 
                             'http://www.example.com/foo/subdir')
1997
 
        self.assertIsInstance(r, type(t))
1998
 
        # Both transports share the some connection
1999
 
        self.assertEqual(t._get_connection(), r._get_connection())
2000
 
        self.assertEquals('http://www.example.com/foo/subdir/', r.base)
2001
 
 
2002
 
    def test_redirected_to_self_with_slash(self):
2003
 
        t = self._transport('http://www.example.com/foo')
2004
 
        r = t._redirected_to('http://www.example.com/foo',
2005
 
                             'http://www.example.com/foo/')
2006
 
        self.assertIsInstance(r, type(t))
2007
 
        # Both transports share the some connection (one can argue that we
2008
 
        # should return the exact same transport here, but that seems
2009
 
        # overkill).
2010
 
        self.assertEqual(t._get_connection(), r._get_connection())
2011
 
 
2012
 
    def test_redirected_to_host(self):
2013
 
        t = self._transport('http://www.example.com/foo')
2014
 
        r = t._redirected_to('http://www.example.com/foo',
2015
 
                             'http://foo.example.com/foo/subdir')
2016
 
        self.assertIsInstance(r, type(t))
2017
 
        self.assertEquals('http://foo.example.com/foo/subdir/',
2018
 
            r.external_url())
2019
 
 
2020
 
    def test_redirected_to_same_host_sibling_protocol(self):
2021
 
        t = self._transport('http://www.example.com/foo')
2022
 
        r = t._redirected_to('http://www.example.com/foo',
2023
 
                             'https://www.example.com/foo')
2024
 
        self.assertIsInstance(r, type(t))
2025
 
        self.assertEquals('https://www.example.com/foo/',
2026
 
            r.external_url())
2027
 
 
2028
 
    def test_redirected_to_same_host_different_protocol(self):
2029
 
        t = self._transport('http://www.example.com/foo')
2030
 
        r = t._redirected_to('http://www.example.com/foo',
2031
 
                             'ftp://www.example.com/foo')
2032
 
        self.assertNotEquals(type(r), type(t))
2033
 
        self.assertEquals('ftp://www.example.com/foo/', r.external_url())
2034
 
 
2035
 
    def test_redirected_to_same_host_specific_implementation(self):
2036
 
        t = self._transport('http://www.example.com/foo')
2037
 
        r = t._redirected_to('http://www.example.com/foo',
2038
 
                             'https+urllib://www.example.com/foo')
2039
 
        self.assertEquals('https://www.example.com/foo/', r.external_url())
2040
 
 
2041
 
    def test_redirected_to_different_host_same_user(self):
2042
 
        t = self._transport('http://joe@www.example.com/foo')
2043
 
        r = t._redirected_to('http://www.example.com/foo',
2044
 
                             'https://foo.example.com/foo')
2045
 
        self.assertIsInstance(r, type(t))
2046
 
        self.assertEqual(t._parsed_url.user, r._parsed_url.user)
2047
 
        self.assertEquals('https://joe@foo.example.com/foo/', r.external_url())
2048
 
 
2049
 
 
2050
 
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
2051
 
    """Request handler for a unique and pre-defined request.
2052
 
 
2053
 
    The only thing we care about here is how many bytes travel on the wire. But
2054
 
    since we want to measure it for a real http client, we have to send it
2055
 
    correct responses.
2056
 
 
2057
 
    We expect to receive a *single* request nothing more (and we won't even
2058
 
    check what request it is, we just measure the bytes read until an empty
2059
 
    line.
2060
 
    """
2061
 
 
2062
 
    def _handle_one_request(self):
2063
 
        tcs = self.server.test_case_server
2064
 
        requestline = self.rfile.readline()
2065
 
        headers = self.MessageClass(self.rfile, 0)
2066
 
        # We just read: the request, the headers, an empty line indicating the
2067
 
        # end of the headers.
2068
 
        bytes_read = len(requestline)
2069
 
        for line in headers.headers:
2070
 
            bytes_read += len(line)
2071
 
        bytes_read += len('\r\n')
2072
 
        if requestline.startswith('POST'):
2073
 
            # The body should be a single line (or we don't know where it ends
2074
 
            # and we don't want to issue a blocking read)
2075
 
            body = self.rfile.readline()
2076
 
            bytes_read += len(body)
2077
 
        tcs.bytes_read = bytes_read
2078
 
 
2079
 
        # We set the bytes written *before* issuing the write, the client is
2080
 
        # supposed to consume every produced byte *before* checking that value.
2081
 
 
2082
 
        # Doing the oppposite may lead to test failure: we may be interrupted
2083
 
        # after the write but before updating the value. The client can then
2084
 
        # continue and read the value *before* we can update it. And yes,
2085
 
        # this has been observed -- vila 20090129
2086
 
        tcs.bytes_written = len(tcs.canned_response)
2087
 
        self.wfile.write(tcs.canned_response)
2088
 
 
2089
 
 
2090
 
class ActivityServerMixin(object):
2091
 
 
2092
 
    def __init__(self, protocol_version):
2093
 
        super(ActivityServerMixin, self).__init__(
2094
 
            request_handler=PredefinedRequestHandler,
2095
 
            protocol_version=protocol_version)
2096
 
        # Bytes read and written by the server
2097
 
        self.bytes_read = 0
2098
 
        self.bytes_written = 0
2099
 
        self.canned_response = None
2100
 
 
2101
 
 
2102
 
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
2103
 
    pass
2104
 
 
2105
 
 
2106
 
if features.HTTPSServerFeature.available():
2107
 
    from bzrlib.tests import https_server
2108
 
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
2109
 
        pass
2110
 
 
2111
 
 
2112
 
class TestActivityMixin(object):
2113
 
    """Test socket activity reporting.
2114
 
 
2115
 
    We use a special purpose server to control the bytes sent and received and
2116
 
    be able to predict the activity on the client socket.
2117
 
    """
2118
 
 
2119
 
    def setUp(self):
2120
 
        tests.TestCase.setUp(self)
2121
 
        self.server = self._activity_server(self._protocol_version)
2122
 
        self.server.start_server()
2123
 
        _activities = {} # Don't close over self and create a cycle
2124
 
        def report_activity(t, bytes, direction):
2125
 
            count = _activities.get(direction, 0)
2126
 
            count += bytes
2127
 
            _activities[direction] = count
2128
 
        self.activities = _activities
2129
 
 
2130
 
        # We override at class level because constructors may propagate the
2131
 
        # bound method and render instance overriding ineffective (an
2132
 
        # alternative would be to define a specific ui factory instead...)
2133
 
        self.overrideAttr(self._transport, '_report_activity', report_activity)
2134
 
        self.addCleanup(self.server.stop_server)
2135
 
 
2136
 
    def get_transport(self):
2137
 
        t = self._transport(self.server.get_url())
2138
 
        # FIXME: Needs cleanup -- vila 20100611
2139
 
        return t
2140
 
 
2141
 
    def assertActivitiesMatch(self):
2142
 
        self.assertEqual(self.server.bytes_read,
2143
 
                         self.activities.get('write', 0), 'written bytes')
2144
 
        self.assertEqual(self.server.bytes_written,
2145
 
                         self.activities.get('read', 0), 'read bytes')
2146
 
 
2147
 
    def test_get(self):
2148
 
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2149
 
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2150
 
Server: Apache/2.0.54 (Fedora)\r
2151
 
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2152
 
ETag: "56691-23-38e9ae00"\r
2153
 
Accept-Ranges: bytes\r
2154
 
Content-Length: 35\r
2155
 
Connection: close\r
2156
 
Content-Type: text/plain; charset=UTF-8\r
2157
 
\r
2158
 
Bazaar-NG meta directory, format 1
2159
 
'''
2160
 
        t = self.get_transport()
2161
 
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
2162
 
                         t.get('foo/bar').read())
2163
 
        self.assertActivitiesMatch()
2164
 
 
2165
 
    def test_has(self):
2166
 
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2167
 
Server: SimpleHTTP/0.6 Python/2.5.2\r
2168
 
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2169
 
Content-type: application/octet-stream\r
2170
 
Content-Length: 20\r
2171
 
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2172
 
\r
2173
 
'''
2174
 
        t = self.get_transport()
2175
 
        self.assertTrue(t.has('foo/bar'))
2176
 
        self.assertActivitiesMatch()
2177
 
 
2178
 
    def test_readv(self):
2179
 
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2180
 
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2181
 
Server: Apache/2.0.54 (Fedora)\r
2182
 
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2183
 
ETag: "238a3c-16ec2-805c5540"\r
2184
 
Accept-Ranges: bytes\r
2185
 
Content-Length: 1534\r
2186
 
Connection: close\r
2187
 
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2188
 
\r
2189
 
\r
2190
 
--418470f848b63279b\r
2191
 
Content-type: text/plain; charset=UTF-8\r
2192
 
Content-range: bytes 0-254/93890\r
2193
 
\r
2194
 
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2195
 
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2196
 
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2197
 
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2198
 
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2199
 
\r
2200
 
--418470f848b63279b\r
2201
 
Content-type: text/plain; charset=UTF-8\r
2202
 
Content-range: bytes 1000-2049/93890\r
2203
 
\r
2204
 
40-fd4ec249b6b139ab
2205
 
mbp@sourcefrog.net-20050311063625-07858525021f270b
2206
 
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2207
 
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2208
 
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2209
 
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2210
 
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2211
 
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2212
 
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2213
 
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2214
 
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2215
 
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2216
 
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2217
 
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2218
 
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2219
 
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2220
 
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2221
 
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2222
 
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2223
 
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2224
 
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2225
 
mbp@source\r
2226
 
--418470f848b63279b--\r
2227
 
'''
2228
 
        t = self.get_transport()
2229
 
        # Remember that the request is ignored and that the ranges below
2230
 
        # doesn't have to match the canned response.
2231
 
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2232
 
        self.assertEqual(2, len(l))
2233
 
        self.assertActivitiesMatch()
2234
 
 
2235
 
    def test_post(self):
2236
 
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2237
 
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2238
 
Server: Apache/2.0.54 (Fedora)\r
2239
 
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2240
 
ETag: "56691-23-38e9ae00"\r
2241
 
Accept-Ranges: bytes\r
2242
 
Content-Length: 35\r
2243
 
Connection: close\r
2244
 
Content-Type: text/plain; charset=UTF-8\r
2245
 
\r
2246
 
lalala whatever as long as itsssss
2247
 
'''
2248
 
        t = self.get_transport()
2249
 
        # We must send a single line of body bytes, see
2250
 
        # PredefinedRequestHandler._handle_one_request
2251
 
        code, f = t._post('abc def end-of-body\n')
2252
 
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2253
 
        self.assertActivitiesMatch()
2254
 
 
2255
 
 
2256
 
class TestActivity(tests.TestCase, TestActivityMixin):
2257
 
 
2258
 
    scenarios = multiply_scenarios(
2259
 
        vary_by_http_activity(),
2260
 
        vary_by_http_protocol_version(),
2261
 
        )
2262
 
 
2263
 
    def setUp(self):
2264
 
        TestActivityMixin.setUp(self)
2265
 
 
2266
 
 
2267
 
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2268
 
 
2269
 
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2270
 
    # ReportingSocket, so we don't need all the parametrization. Since
2271
 
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2272
 
    # test them through their use by the transport than directly (that's a
2273
 
    # bit less clean but far more simpler and effective).
2274
 
    _activity_server = ActivityHTTPServer
2275
 
    _protocol_version = 'HTTP/1.1'
2276
 
 
2277
 
    def setUp(self):
2278
 
        self._transport =_urllib.HttpTransport_urllib
2279
 
        TestActivityMixin.setUp(self)
2280
 
 
2281
 
    def assertActivitiesMatch(self):
2282
 
        # Nothing to check here
2283
 
        pass
2284
 
 
2285
 
 
2286
 
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2287
 
    """Test authentication on the redirected http server."""
2288
 
 
2289
 
    scenarios = vary_by_http_protocol_version()
2290
 
 
2291
 
    _auth_header = 'Authorization'
2292
 
    _password_prompt_prefix = ''
2293
 
    _username_prompt_prefix = ''
2294
 
    _auth_server = http_utils.HTTPBasicAuthServer
2295
 
    _transport = _urllib.HttpTransport_urllib
2296
 
 
2297
 
    def setUp(self):
2298
 
        super(TestAuthOnRedirected, self).setUp()
2299
 
        self.build_tree_contents([('a','a'),
2300
 
                                  ('1/',),
2301
 
                                  ('1/a', 'redirected once'),
2302
 
                                  ],)
2303
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2304
 
                                       self.new_server.port)
2305
 
        self.old_server.redirections = [
2306
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2307
 
        self.old_transport = self.get_old_transport()
2308
 
        self.new_server.add_user('joe', 'foo')
2309
 
        cleanup_http_redirection_connections(self)
2310
 
 
2311
 
    def create_transport_readonly_server(self):
2312
 
        server = self._auth_server(protocol_version=self._protocol_version)
2313
 
        server._url_protocol = self._url_protocol
2314
 
        return server
2315
 
 
2316
 
    def get_a(self, t):
2317
 
        return t.get('a')
2318
 
 
2319
 
    def test_auth_on_redirected_via_do_catching_redirections(self):
2320
 
        self.redirections = 0
2321
 
 
2322
 
        def redirected(t, exception, redirection_notice):
2323
 
            self.redirections += 1
2324
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2325
 
            self.addCleanup(redirected_t.disconnect)
2326
 
            return redirected_t
2327
 
 
2328
 
        stdout = tests.StringIOWrapper()
2329
 
        stderr = tests.StringIOWrapper()
2330
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2331
 
                                            stdout=stdout, stderr=stderr)
2332
 
        self.assertEqual('redirected once',
2333
 
                         transport.do_catching_redirections(
2334
 
                self.get_a, self.old_transport, redirected).read())
2335
 
        self.assertEqual(1, self.redirections)
2336
 
        # stdin should be empty
2337
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2338
 
        # stdout should be empty, stderr will contains the prompts
2339
 
        self.assertEqual('', stdout.getvalue())
2340
 
 
2341
 
    def test_auth_on_redirected_via_following_redirections(self):
2342
 
        self.new_server.add_user('joe', 'foo')
2343
 
        stdout = tests.StringIOWrapper()
2344
 
        stderr = tests.StringIOWrapper()
2345
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2346
 
                                            stdout=stdout, stderr=stderr)
2347
 
        t = self.old_transport
2348
 
        req = RedirectedRequest('GET', t.abspath('a'))
2349
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2350
 
                                       self.new_server.port)
2351
 
        self.old_server.redirections = [
2352
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2353
 
        self.assertEqual('redirected once', t._perform(req).read())
2354
 
        # stdin should be empty
2355
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2356
 
        # stdout should be empty, stderr will contains the prompts
2357
 
        self.assertEqual('', stdout.getvalue())
2358