~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Andrew Bennetts
  • Date: 2010-01-12 03:53:21 UTC
  • mfrom: (4948 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4964.
  • Revision ID: andrew.bennetts@canonical.com-20100112035321-hofpz5p10224ryj3
Merge lp:bzr, resolving conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests for HTTP implementations.
18
18
 
44
44
    ui,
45
45
    urlutils,
46
46
    )
 
47
from bzrlib.symbol_versioning import (
 
48
    deprecated_in,
 
49
    )
47
50
from bzrlib.tests import (
 
51
    features,
48
52
    http_server,
49
53
    http_utils,
50
54
    )
58
62
    )
59
63
 
60
64
 
61
 
try:
 
65
if features.pycurl.available():
62
66
    from bzrlib.transport.http._pycurl import PyCurlTransport
63
 
    pycurl_present = True
64
 
except errors.DependencyNotPresent:
65
 
    pycurl_present = False
66
67
 
67
68
 
68
69
def load_tests(standard_tests, module, loader):
69
70
    """Multiply tests for http clients and protocol versions."""
70
71
    result = loader.suiteClass()
71
 
    adapter = tests.TestScenarioApplier()
72
 
    remaining_tests = standard_tests
73
72
 
74
 
    # one for each transport
 
73
    # one for each transport implementation
75
74
    t_tests, remaining_tests = tests.split_suite_by_condition(
76
 
        remaining_tests, tests.condition_isinstance((
 
75
        standard_tests, tests.condition_isinstance((
77
76
                TestHttpTransportRegistration,
78
77
                TestHttpTransportUrls,
79
78
                Test_redirected_to,
83
82
                        _server=http_server.HttpServer_urllib,
84
83
                        _qualified_prefix='http+urllib',)),
85
84
        ]
86
 
    if pycurl_present:
 
85
    if features.pycurl.available():
87
86
        transport_scenarios.append(
88
87
            ('pycurl', dict(_transport=PyCurlTransport,
89
88
                            _server=http_server.HttpServer_PyCurl,
90
89
                            _qualified_prefix='http+pycurl',)))
91
 
    adapter.scenarios = transport_scenarios
92
 
    tests.adapt_tests(t_tests, adapter, result)
 
90
    tests.multiply_tests(t_tests, transport_scenarios, result)
93
91
 
94
 
    # multiplied by one for each protocol version
 
92
    # each implementation tested with each HTTP version
95
93
    tp_tests, remaining_tests = tests.split_suite_by_condition(
96
94
        remaining_tests, tests.condition_isinstance((
97
95
                SmartHTTPTunnellingTest,
109
107
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
110
108
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
111
109
            ]
112
 
    tp_scenarios = tests.multiply_scenarios(adapter.scenarios,
 
110
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
113
111
                                            protocol_scenarios)
114
 
    adapter.scenarios = tp_scenarios
115
 
    tests.adapt_tests(tp_tests, adapter, result)
116
 
 
117
 
    # multiplied by one for each authentication scheme
 
112
    tests.multiply_tests(tp_tests, tp_scenarios, result)
 
113
 
 
114
    # proxy auth: each auth scheme on all http versions on all implementations.
 
115
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
 
116
        remaining_tests, tests.condition_isinstance((
 
117
                TestProxyAuth,
 
118
                )))
 
119
    proxy_auth_scheme_scenarios = [
 
120
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
 
121
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
 
122
        ('basicdigest',
 
123
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
 
124
        ]
 
125
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
 
126
                                              proxy_auth_scheme_scenarios)
 
127
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
 
128
 
 
129
    # auth: each auth scheme on all http versions on all implementations.
118
130
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
119
131
        remaining_tests, tests.condition_isinstance((
120
132
                TestAuth,
121
133
                )))
122
134
    auth_scheme_scenarios = [
123
 
        ('basic', dict(_auth_scheme='basic')),
124
 
        ('digest', dict(_auth_scheme='digest')),
 
135
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
 
136
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
 
137
        ('basicdigest',
 
138
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
125
139
        ]
126
 
    adapter.scenarios = tests.multiply_scenarios(adapter.scenarios,
127
 
                                                 auth_scheme_scenarios)
128
 
    tests.adapt_tests(tpa_tests, adapter, result)
 
140
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
 
141
                                             auth_scheme_scenarios)
 
142
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
129
143
 
 
144
    # activity: on all http[s] versions on all implementations
130
145
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
131
146
        remaining_tests, tests.condition_isinstance((
132
147
                TestActivity,
133
148
                )))
134
149
    activity_scenarios = [
135
 
        ('http', dict(_activity_server=ActivityHTTPServer)),
 
150
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
 
151
                             _transport=_urllib.HttpTransport_urllib,)),
136
152
        ]
137
153
    if tests.HTTPSServerFeature.available():
138
154
        activity_scenarios.append(
139
 
            ('https', dict(_activity_server=ActivityHTTPSServer,)))
140
 
    adapter.scenarios = tests.multiply_scenarios(tp_scenarios,
141
 
                                                 activity_scenarios)
142
 
    tests.adapt_tests(tpact_tests, adapter, result)
 
155
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
 
156
                                  _transport=_urllib.HttpTransport_urllib,)),)
 
157
    if features.pycurl.available():
 
158
        activity_scenarios.append(
 
159
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
 
160
                                 _transport=PyCurlTransport,)),)
 
161
        if tests.HTTPSServerFeature.available():
 
162
            from bzrlib.tests import (
 
163
                ssl_certs,
 
164
                )
 
165
            # FIXME: Until we have a better way to handle self-signed
 
166
            # certificates (like allowing them in a test specific
 
167
            # authentication.conf for example), we need some specialized pycurl
 
168
            # transport for tests.
 
169
            class HTTPS_pycurl_transport(PyCurlTransport):
 
170
 
 
171
                def __init__(self, base, _from_transport=None):
 
172
                    super(HTTPS_pycurl_transport, self).__init__(
 
173
                        base, _from_transport)
 
174
                    self.cabundle = str(ssl_certs.build_path('ca.crt'))
 
175
 
 
176
            activity_scenarios.append(
 
177
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
 
178
                                      _transport=HTTPS_pycurl_transport,)),)
 
179
 
 
180
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
 
181
                                               protocol_scenarios)
 
182
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
143
183
 
144
184
    # No parametrization for the remaining tests
145
185
    result.addTests(remaining_tests)
158
198
 
159
199
class RecordingServer(object):
160
200
    """A fake HTTP server.
161
 
    
 
201
 
162
202
    It records the bytes sent to it, and replies with a 200.
163
203
    """
164
204
 
165
 
    def __init__(self, expect_body_tail=None):
 
205
    def __init__(self, expect_body_tail=None, scheme=''):
166
206
        """Constructor.
167
207
 
168
208
        :type expect_body_tail: str
173
213
        self.host = None
174
214
        self.port = None
175
215
        self.received_bytes = ''
176
 
 
177
 
    def setUp(self):
 
216
        self.scheme = scheme
 
217
 
 
218
    def get_url(self):
 
219
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
 
220
 
 
221
    def start_server(self):
178
222
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
179
223
        self._sock.bind(('127.0.0.1', 0))
180
224
        self.host, self.port = self._sock.getsockname()
203
247
            # The client may have already closed the socket.
204
248
            pass
205
249
 
206
 
    def tearDown(self):
 
250
    def stop_server(self):
207
251
        try:
208
252
            self._sock.close()
209
253
        except socket.error:
213
257
        self.port = None
214
258
 
215
259
 
 
260
class TestAuthHeader(tests.TestCase):
 
261
 
 
262
    def parse_header(self, header, auth_handler_class=None):
 
263
        if auth_handler_class is None:
 
264
            auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
 
265
        self.auth_handler =  auth_handler_class()
 
266
        return self.auth_handler._parse_auth_header(header)
 
267
 
 
268
    def test_empty_header(self):
 
269
        scheme, remainder = self.parse_header('')
 
270
        self.assertEqual('', scheme)
 
271
        self.assertIs(None, remainder)
 
272
 
 
273
    def test_negotiate_header(self):
 
274
        scheme, remainder = self.parse_header('Negotiate')
 
275
        self.assertEqual('negotiate', scheme)
 
276
        self.assertIs(None, remainder)
 
277
 
 
278
    def test_basic_header(self):
 
279
        scheme, remainder = self.parse_header(
 
280
            'Basic realm="Thou should not pass"')
 
281
        self.assertEqual('basic', scheme)
 
282
        self.assertEqual('realm="Thou should not pass"', remainder)
 
283
 
 
284
    def test_basic_extract_realm(self):
 
285
        scheme, remainder = self.parse_header(
 
286
            'Basic realm="Thou should not pass"',
 
287
            _urllib2_wrappers.BasicAuthHandler)
 
288
        match, realm = self.auth_handler.extract_realm(remainder)
 
289
        self.assertTrue(match is not None)
 
290
        self.assertEqual('Thou should not pass', realm)
 
291
 
 
292
    def test_digest_header(self):
 
293
        scheme, remainder = self.parse_header(
 
294
            'Digest realm="Thou should not pass"')
 
295
        self.assertEqual('digest', scheme)
 
296
        self.assertEqual('realm="Thou should not pass"', remainder)
 
297
 
 
298
 
216
299
class TestHTTPServer(tests.TestCase):
217
300
    """Test the HTTP servers implementations."""
218
301
 
223
306
 
224
307
        server = http_server.HttpServer(BogusRequestHandler)
225
308
        try:
226
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
227
310
        except:
228
 
            server.tearDown()
 
311
            server.stop_server()
229
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
230
313
 
231
314
    def test_force_invalid_protocol(self):
232
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
233
316
        try:
234
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
235
318
        except:
236
 
            server.tearDown()
 
319
            server.stop_server()
237
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
238
321
 
239
322
    def test_server_start_and_stop(self):
240
323
        server = http_server.HttpServer()
241
 
        server.setUp()
242
 
        self.assertTrue(server._http_running)
243
 
        server.tearDown()
 
324
        server.start_server()
 
325
        try:
 
326
            self.assertTrue(server._http_running)
 
327
        finally:
 
328
            server.stop_server()
244
329
        self.assertFalse(server._http_running)
245
330
 
246
331
    def test_create_http_server_one_zero(self):
249
334
            protocol_version = 'HTTP/1.0'
250
335
 
251
336
        server = http_server.HttpServer(RequestHandlerOneZero)
252
 
        server.setUp()
253
 
        self.addCleanup(server.tearDown)
 
337
        self.start_server(server)
254
338
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
255
339
 
256
340
    def test_create_http_server_one_one(self):
259
343
            protocol_version = 'HTTP/1.1'
260
344
 
261
345
        server = http_server.HttpServer(RequestHandlerOneOne)
262
 
        server.setUp()
263
 
        self.addCleanup(server.tearDown)
 
346
        self.start_server(server)
264
347
        self.assertIsInstance(server._httpd,
265
348
                              http_server.TestingThreadingHTTPServer)
266
349
 
271
354
 
272
355
        server = http_server.HttpServer(RequestHandlerOneZero,
273
356
                                        protocol_version='HTTP/1.1')
274
 
        server.setUp()
275
 
        self.addCleanup(server.tearDown)
 
357
        self.start_server(server)
276
358
        self.assertIsInstance(server._httpd,
277
359
                              http_server.TestingThreadingHTTPServer)
278
360
 
283
365
 
284
366
        server = http_server.HttpServer(RequestHandlerOneOne,
285
367
                                        protocol_version='HTTP/1.0')
286
 
        server.setUp()
287
 
        self.addCleanup(server.tearDown)
 
368
        self.start_server(server)
288
369
        self.assertIsInstance(server._httpd,
289
370
                              http_server.TestingHTTPServer)
290
371
 
293
374
    """Test case to inherit from if pycurl is present"""
294
375
 
295
376
    def _get_pycurl_maybe(self):
296
 
        try:
297
 
            from bzrlib.transport.http._pycurl import PyCurlTransport
298
 
            return PyCurlTransport
299
 
        except errors.DependencyNotPresent:
300
 
            raise tests.TestSkipped('pycurl not present')
 
377
        self.requireFeature(features.pycurl)
 
378
        return PyCurlTransport
301
379
 
302
380
    _transport = property(_get_pycurl_maybe)
303
381
 
310
388
    def test_url_parsing(self):
311
389
        f = FakeManager()
312
390
        url = http.extract_auth('http://example.com', f)
313
 
        self.assertEquals('http://example.com', url)
314
 
        self.assertEquals(0, len(f.credentials))
 
391
        self.assertEqual('http://example.com', url)
 
392
        self.assertEqual(0, len(f.credentials))
315
393
        url = http.extract_auth(
316
394
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
317
 
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
318
 
        self.assertEquals(1, len(f.credentials))
319
 
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
320
 
                          f.credentials[0])
 
395
        self.assertEqual('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
 
396
        self.assertEqual(1, len(f.credentials))
 
397
        self.assertEqual([None, 'www.bazaar-vcs.org', 'user', 'pass'],
 
398
                         f.credentials[0])
321
399
 
322
400
 
323
401
class TestHttpTransportUrls(tests.TestCase):
350
428
    def test_http_impl_urls(self):
351
429
        """There are servers which ask for particular clients to connect"""
352
430
        server = self._server()
 
431
        server.start_server()
353
432
        try:
354
 
            server.setUp()
355
433
            url = server.get_url()
356
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
357
435
        finally:
358
 
            server.tearDown()
 
436
            server.stop_server()
359
437
 
360
438
 
361
439
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
370
448
        https by supplying a fake version_info that do not
371
449
        support it.
372
450
        """
373
 
        try:
374
 
            import pycurl
375
 
        except ImportError:
376
 
            raise tests.TestSkipped('pycurl not present')
 
451
        self.requireFeature(features.pycurl)
 
452
        # Import the module locally now that we now it's available.
 
453
        pycurl = features.pycurl.module
377
454
 
378
455
        version_info_orig = pycurl.version_info
379
 
        try:
380
 
            # Now that we have pycurl imported, we can fake its version_info
381
 
            # This was taken from a windows pycurl without SSL
382
 
            # (thanks to bialix)
383
 
            pycurl.version_info = lambda : (2,
384
 
                                            '7.13.2',
385
 
                                            462082,
386
 
                                            'i386-pc-win32',
387
 
                                            2576,
388
 
                                            None,
389
 
                                            0,
390
 
                                            None,
391
 
                                            ('ftp', 'gopher', 'telnet',
392
 
                                             'dict', 'ldap', 'http', 'file'),
393
 
                                            None,
394
 
                                            0,
395
 
                                            None)
396
 
            self.assertRaises(errors.DependencyNotPresent, self._transport,
397
 
                              'https://launchpad.net')
398
 
        finally:
399
 
            # Restore the right function
 
456
        def restore():
400
457
            pycurl.version_info = version_info_orig
 
458
        self.addCleanup(restore)
 
459
 
 
460
        # Fake the pycurl version_info This was taken from a windows pycurl
 
461
        # without SSL (thanks to bialix)
 
462
        pycurl.version_info = lambda : (2,
 
463
                                        '7.13.2',
 
464
                                        462082,
 
465
                                        'i386-pc-win32',
 
466
                                        2576,
 
467
                                        None,
 
468
                                        0,
 
469
                                        None,
 
470
                                        ('ftp', 'gopher', 'telnet',
 
471
                                         'dict', 'ldap', 'http', 'file'),
 
472
                                        None,
 
473
                                        0,
 
474
                                        None)
 
475
        self.assertRaises(errors.DependencyNotPresent, self._transport,
 
476
                          'https://launchpad.net')
401
477
 
402
478
 
403
479
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
462
538
class TestPost(tests.TestCase):
463
539
 
464
540
    def test_post_body_is_received(self):
465
 
        server = RecordingServer(expect_body_tail='end-of-body')
466
 
        server.setUp()
467
 
        self.addCleanup(server.tearDown)
468
 
        scheme = self._qualified_prefix
469
 
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
 
541
        server = RecordingServer(expect_body_tail='end-of-body',
 
542
            scheme=self._qualified_prefix)
 
543
        self.start_server(server)
 
544
        url = server.get_url()
470
545
        http_transport = self._transport(url)
471
546
        code, response = http_transport._post('abc def end-of-body')
472
547
        self.assertTrue(
521
596
                                      protocol_version=self._protocol_version)
522
597
 
523
598
    def _testing_pycurl(self):
524
 
        return pycurl_present and self._transport == PyCurlTransport
 
599
        # TODO: This is duplicated for lots of the classes in this file
 
600
        return (features.pycurl.available()
 
601
                and self._transport == PyCurlTransport)
525
602
 
526
603
 
527
604
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
544
621
        # for details) make no distinction between a closed
545
622
        # socket and badly formatted status line, so we can't
546
623
        # just test for ConnectionError, we have to test
547
 
        # InvalidHttpResponse too.
548
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
624
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
 
625
        # instead of ConnectionError too.
 
626
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
 
627
                            errors.InvalidHttpResponse),
549
628
                          t.has, 'foo/bar')
550
629
 
551
630
    def test_http_get(self):
552
631
        server = self.get_readonly_server()
553
632
        t = self._transport(server.get_url())
554
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
633
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
 
634
                           errors.InvalidHttpResponse),
555
635
                          t.get, 'foo/bar')
556
636
 
557
637
 
633
713
    _req_handler_class = BadProtocolRequestHandler
634
714
 
635
715
    def setUp(self):
636
 
        if pycurl_present and self._transport == PyCurlTransport:
 
716
        if self._testing_pycurl():
637
717
            raise tests.TestNotApplicable(
638
718
                "pycurl doesn't check the protocol version")
639
719
        super(TestBadProtocolServer, self).setUp()
683
763
        self.assertEqual(None, server.host)
684
764
        self.assertEqual(None, server.port)
685
765
 
686
 
    def test_setUp_and_tearDown(self):
 
766
    def test_setUp_and_stop(self):
687
767
        server = RecordingServer(expect_body_tail=None)
688
 
        server.setUp()
 
768
        server.start_server()
689
769
        try:
690
770
            self.assertNotEqual(None, server.host)
691
771
            self.assertNotEqual(None, server.port)
692
772
        finally:
693
 
            server.tearDown()
 
773
            server.stop_server()
694
774
        self.assertEqual(None, server.host)
695
775
        self.assertEqual(None, server.port)
696
776
 
697
777
    def test_send_receive_bytes(self):
698
 
        server = RecordingServer(expect_body_tail='c')
699
 
        server.setUp()
700
 
        self.addCleanup(server.tearDown)
 
778
        server = RecordingServer(expect_body_tail='c', scheme='http')
 
779
        self.start_server(server)
701
780
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
702
781
        sock.connect((server.host, server.port))
703
782
        sock.sendall('abc')
797
876
        # bytes on the socket
798
877
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
799
878
        self.assertEqual((0, '0'), ireadv.next())
800
 
        # The server should have issued one request so far 
 
879
        # The server should have issued one request so far
801
880
        self.assertEqual(1, server.GET_request_nb)
802
881
        self.assertEqual('0123456789', t.get_bytes('a'))
803
882
        # get_bytes issued an additional request, the readv pending ones are
1094
1173
        if self._testing_pycurl():
1095
1174
            # Oh my ! pycurl does not check for the port as part of
1096
1175
            # no_proxy :-( So we just test the host part
1097
 
            self.no_proxy_host = 'localhost'
 
1176
            self.no_proxy_host = self.server.host
1098
1177
        else:
1099
1178
            self.no_proxy_host = self.proxy_address
1100
1179
        # The secondary server is the proxy
1103
1182
        self._old_env = {}
1104
1183
 
1105
1184
    def _testing_pycurl(self):
1106
 
        return pycurl_present and self._transport == PyCurlTransport
 
1185
        # TODO: This is duplicated for lots of the classes in this file
 
1186
        return (features.pycurl.available()
 
1187
                and self._transport == PyCurlTransport)
1107
1188
 
1108
1189
    def create_transport_secondary_server(self):
1109
1190
        """Creates an http server that will serve files with
1260
1341
    def test_read_redirected_bundle_from_url(self):
1261
1342
        from bzrlib.bundle import read_bundle_from_url
1262
1343
        url = self.old_transport.abspath('bundle')
1263
 
        bundle = read_bundle_from_url(url)
 
1344
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
 
1345
                read_bundle_from_url, url)
1264
1346
        # If read_bundle_from_url was successful we get an empty bundle
1265
1347
        self.assertEqual([], bundle.revisions)
1266
1348
 
1277
1359
        # Since the tests using this class will replace
1278
1360
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1279
1361
        # or we'll loop.
1280
 
        RedirectedRequest.init_orig(self, method, url, args, kwargs)
 
1362
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
1281
1363
        self.follow_redirections = True
1282
1364
 
1283
1365
 
 
1366
def install_redirected_request(test):
 
1367
    test.original_class = _urllib2_wrappers.Request
 
1368
    def restore():
 
1369
        _urllib2_wrappers.Request = test.original_class
 
1370
    _urllib2_wrappers.Request = RedirectedRequest
 
1371
    test.addCleanup(restore)
 
1372
 
 
1373
 
1284
1374
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1285
1375
    """Test redirections.
1286
1376
 
1296
1386
    """
1297
1387
 
1298
1388
    def setUp(self):
1299
 
        if pycurl_present and self._transport == PyCurlTransport:
 
1389
        if (features.pycurl.available()
 
1390
            and self._transport == PyCurlTransport):
1300
1391
            raise tests.TestNotApplicable(
1301
1392
                "pycurl doesn't redirect silently annymore")
1302
1393
        super(TestHTTPSilentRedirections, self).setUp()
1303
 
        self.setup_redirected_request()
1304
 
        self.addCleanup(self.cleanup_redirected_request)
 
1394
        install_redirected_request(self)
1305
1395
        self.build_tree_contents([('a','a'),
1306
1396
                                  ('1/',),
1307
1397
                                  ('1/a', 'redirected once'),
1317
1407
 
1318
1408
        self.old_transport = self._transport(self.old_server.get_url())
1319
1409
 
1320
 
    def setup_redirected_request(self):
1321
 
        self.original_class = _urllib2_wrappers.Request
1322
 
        _urllib2_wrappers.Request = RedirectedRequest
1323
 
 
1324
 
    def cleanup_redirected_request(self):
1325
 
        _urllib2_wrappers.Request = self.original_class
1326
 
 
1327
1410
    def create_transport_secondary_server(self):
1328
1411
        """Create the secondary server, redirections are defined in the tests"""
1329
1412
        return http_utils.HTTPServerRedirecting(
1333
1416
        t = self.old_transport
1334
1417
 
1335
1418
        req = RedirectedRequest('GET', t.abspath('a'))
1336
 
        req.follow_redirections = True
1337
1419
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1338
1420
                                       self.new_server.port)
1339
1421
        self.old_server.redirections = \
1340
1422
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1341
 
        self.assertEquals('redirected once',t._perform(req).read())
 
1423
        self.assertEqual('redirected once',t._perform(req).read())
1342
1424
 
1343
1425
    def test_five_redirections(self):
1344
1426
        t = self.old_transport
1345
1427
 
1346
1428
        req = RedirectedRequest('GET', t.abspath('a'))
1347
 
        req.follow_redirections = True
1348
1429
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1349
1430
                                       self.old_server.port)
1350
1431
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1356
1437
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1357
1438
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1358
1439
            ]
1359
 
        self.assertEquals('redirected 5 times',t._perform(req).read())
 
1440
        self.assertEqual('redirected 5 times',t._perform(req).read())
1360
1441
 
1361
1442
 
1362
1443
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1375
1456
        t = self._transport(self.new_server.get_url())
1376
1457
 
1377
1458
        # We use None for redirected so that we fail if redirected
1378
 
        self.assertEquals('0123456789',
1379
 
                          transport.do_catching_redirections(
 
1459
        self.assertEqual('0123456789',
 
1460
                         transport.do_catching_redirections(
1380
1461
                self.get_a, t, None).read())
1381
1462
 
1382
1463
    def test_one_redirection(self):
1387
1468
            dir, file = urlutils.split(exception.target)
1388
1469
            return self._transport(dir)
1389
1470
 
1390
 
        self.assertEquals('0123456789',
1391
 
                          transport.do_catching_redirections(
 
1471
        self.assertEqual('0123456789',
 
1472
                         transport.do_catching_redirections(
1392
1473
                self.get_a, self.old_transport, redirected).read())
1393
 
        self.assertEquals(1, self.redirections)
 
1474
        self.assertEqual(1, self.redirections)
1394
1475
 
1395
1476
    def test_redirection_loop(self):
1396
1477
 
1410
1491
 
1411
1492
    _auth_header = 'Authorization'
1412
1493
    _password_prompt_prefix = ''
 
1494
    _username_prompt_prefix = ''
 
1495
    # Set by load_tests
 
1496
    _auth_server = None
1413
1497
 
1414
1498
    def setUp(self):
1415
1499
        super(TestAuth, self).setUp()
1418
1502
                                  ('b', 'contents of b\n'),])
1419
1503
 
1420
1504
    def create_transport_readonly_server(self):
1421
 
        if self._auth_scheme == 'basic':
1422
 
            server = http_utils.HTTPBasicAuthServer(
1423
 
                protocol_version=self._protocol_version)
1424
 
        else:
1425
 
            if self._auth_scheme != 'digest':
1426
 
                raise AssertionError('Unknown auth scheme: %r'
1427
 
                                     % self._auth_scheme)
1428
 
            server = http_utils.HTTPDigestAuthServer(
1429
 
                protocol_version=self._protocol_version)
1430
 
        return server
 
1505
        return self._auth_server(protocol_version=self._protocol_version)
1431
1506
 
1432
1507
    def _testing_pycurl(self):
1433
 
        return pycurl_present and self._transport == PyCurlTransport
 
1508
        # TODO: This is duplicated for lots of the classes in this file
 
1509
        return (features.pycurl.available()
 
1510
                and self._transport == PyCurlTransport)
1434
1511
 
1435
1512
    def get_user_url(self, user, password):
1436
1513
        """Build an url embedding user and password"""
1484
1561
        # initial 'who are you' and 'this is not you, who are you')
1485
1562
        self.assertEqual(2, self.server.auth_required_errors)
1486
1563
 
 
1564
    def test_prompt_for_username(self):
 
1565
        if self._testing_pycurl():
 
1566
            raise tests.TestNotApplicable(
 
1567
                'pycurl cannot prompt, it handles auth by embedding'
 
1568
                ' user:pass in urls only')
 
1569
 
 
1570
        self.server.add_user('joe', 'foo')
 
1571
        t = self.get_user_transport(None, None)
 
1572
        stdout = tests.StringIOWrapper()
 
1573
        stderr = tests.StringIOWrapper()
 
1574
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
1575
                                            stdout=stdout, stderr=stderr)
 
1576
        self.assertEqual('contents of a\n',t.get('a').read())
 
1577
        # stdin should be empty
 
1578
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
1579
        stderr.seek(0)
 
1580
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
 
1581
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
 
1582
        self.assertEqual('', stdout.getvalue())
 
1583
        self._check_password_prompt(t._unqualified_scheme, 'joe',
 
1584
                                    stderr.readline())
 
1585
 
1487
1586
    def test_prompt_for_password(self):
1488
1587
        if self._testing_pycurl():
1489
1588
            raise tests.TestNotApplicable(
1493
1592
        self.server.add_user('joe', 'foo')
1494
1593
        t = self.get_user_transport('joe', None)
1495
1594
        stdout = tests.StringIOWrapper()
1496
 
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
1497
 
        self.assertEqual('contents of a\n',t.get('a').read())
 
1595
        stderr = tests.StringIOWrapper()
 
1596
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
 
1597
                                            stdout=stdout, stderr=stderr)
 
1598
        self.assertEqual('contents of a\n', t.get('a').read())
1498
1599
        # stdin should be empty
1499
1600
        self.assertEqual('', ui.ui_factory.stdin.readline())
1500
1601
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1501
 
                                    stdout.getvalue())
 
1602
                                    stderr.getvalue())
 
1603
        self.assertEqual('', stdout.getvalue())
1502
1604
        # And we shouldn't prompt again for a different request
1503
1605
        # against the same transport.
1504
1606
        self.assertEqual('contents of b\n',t.get('b').read())
1514
1616
                              % (scheme.upper(),
1515
1617
                                 user, self.server.host, self.server.port,
1516
1618
                                 self.server.auth_realm)))
1517
 
        self.assertEquals(expected_prompt, actual_prompt)
 
1619
        self.assertEqual(expected_prompt, actual_prompt)
 
1620
 
 
1621
    def _expected_username_prompt(self, scheme):
 
1622
        return (self._username_prompt_prefix
 
1623
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
 
1624
                                 self.server.host, self.server.port,
 
1625
                                 self.server.auth_realm))
1518
1626
 
1519
1627
    def test_no_prompt_for_password_when_using_auth_config(self):
1520
1628
        if self._testing_pycurl():
1528
1636
        self.server.add_user(user, password)
1529
1637
        t = self.get_user_transport(user, None)
1530
1638
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1531
 
                                            stdout=tests.StringIOWrapper())
 
1639
                                            stderr=tests.StringIOWrapper())
1532
1640
        # Create a minimal config file with the right password
1533
1641
        conf = config.AuthenticationConfig()
1534
1642
        conf._get_config().update(
1562
1670
        self.assertEqual(1, self.server.auth_required_errors)
1563
1671
 
1564
1672
    def test_changing_nonce(self):
1565
 
        if self._auth_scheme != 'digest':
1566
 
            raise tests.TestNotApplicable('HTTP auth digest only test')
 
1673
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
 
1674
                                     http_utils.ProxyDigestAuthServer):
 
1675
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
1567
1676
        if self._testing_pycurl():
1568
1677
            raise tests.KnownFailure(
1569
1678
                'pycurl does not handle a nonce change')
1587
1696
    """Test proxy authentication schemes."""
1588
1697
 
1589
1698
    _auth_header = 'Proxy-authorization'
1590
 
    _password_prompt_prefix='Proxy '
 
1699
    _password_prompt_prefix = 'Proxy '
 
1700
    _username_prompt_prefix = 'Proxy '
1591
1701
 
1592
1702
    def setUp(self):
1593
1703
        super(TestProxyAuth, self).setUp()
1600
1710
                                  ('b-proxied', 'contents of b\n'),
1601
1711
                                  ])
1602
1712
 
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
1713
    def get_user_transport(self, user, password):
1616
1714
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1617
1715
        return self._transport(self.server.get_url())
1756
1854
                             'http://www.example.com/foo/subdir')
1757
1855
        self.assertIsInstance(r, type(t))
1758
1856
        # Both transports share the some connection
1759
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1857
        self.assertEqual(t._get_connection(), r._get_connection())
1760
1858
 
1761
1859
    def test_redirected_to_self_with_slash(self):
1762
1860
        t = self._transport('http://www.example.com/foo')
1766
1864
        # Both transports share the some connection (one can argue that we
1767
1865
        # should return the exact same transport here, but that seems
1768
1866
        # overkill).
1769
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1867
        self.assertEqual(t._get_connection(), r._get_connection())
1770
1868
 
1771
1869
    def test_redirected_to_host(self):
1772
1870
        t = self._transport('http://www.example.com/foo')
1791
1889
        r = t._redirected_to('http://www.example.com/foo',
1792
1890
                             'https://foo.example.com/foo')
1793
1891
        self.assertIsInstance(r, type(t))
1794
 
        self.assertEquals(t._user, r._user)
 
1892
        self.assertEqual(t._user, r._user)
1795
1893
 
1796
1894
 
1797
1895
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1856
1954
        pass
1857
1955
 
1858
1956
 
1859
 
class TestActivity(tests.TestCase):
 
1957
class TestActivityMixin(object):
1860
1958
    """Test socket activity reporting.
1861
1959
 
1862
1960
    We use a special purpose server to control the bytes sent and received and
1866
1964
    def setUp(self):
1867
1965
        tests.TestCase.setUp(self)
1868
1966
        self.server = self._activity_server(self._protocol_version)
1869
 
        self.server.setUp()
 
1967
        self.server.start_server()
1870
1968
        self.activities = {}
1871
1969
        def report_activity(t, bytes, direction):
1872
1970
            count = self.activities.get(direction, 0)
1875
1973
 
1876
1974
        # We override at class level because constructors may propagate the
1877
1975
        # bound method and render instance overriding ineffective (an
1878
 
        # alternative would be be to define a specific ui factory instead...)
 
1976
        # alternative would be to define a specific ui factory instead...)
1879
1977
        self.orig_report_activity = self._transport._report_activity
1880
1978
        self._transport._report_activity = report_activity
1881
1979
 
1882
1980
    def tearDown(self):
1883
1981
        self._transport._report_activity = self.orig_report_activity
1884
 
        self.server.tearDown()
 
1982
        self.server.stop_server()
1885
1983
        tests.TestCase.tearDown(self)
1886
1984
 
1887
1985
    def get_transport(self):
2000
2098
        code, f = t._post('abc def end-of-body\n')
2001
2099
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2002
2100
        self.assertActivitiesMatch()
 
2101
 
 
2102
 
 
2103
class TestActivity(tests.TestCase, TestActivityMixin):
 
2104
 
 
2105
    def setUp(self):
 
2106
        tests.TestCase.setUp(self)
 
2107
        self.server = self._activity_server(self._protocol_version)
 
2108
        self.server.start_server()
 
2109
        self.activities = {}
 
2110
        def report_activity(t, bytes, direction):
 
2111
            count = self.activities.get(direction, 0)
 
2112
            count += bytes
 
2113
            self.activities[direction] = count
 
2114
 
 
2115
        # We override at class level because constructors may propagate the
 
2116
        # bound method and render instance overriding ineffective (an
 
2117
        # alternative would be to define a specific ui factory instead...)
 
2118
        self.orig_report_activity = self._transport._report_activity
 
2119
        self._transport._report_activity = report_activity
 
2120
 
 
2121
    def tearDown(self):
 
2122
        self._transport._report_activity = self.orig_report_activity
 
2123
        self.server.stop_server()
 
2124
        tests.TestCase.tearDown(self)
 
2125
 
 
2126
 
 
2127
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
 
2128
 
 
2129
    def setUp(self):
 
2130
        tests.TestCase.setUp(self)
 
2131
        # Unlike TestActivity, we are really testing ReportingFileSocket and
 
2132
        # ReportingSocket, so we don't need all the parametrization. Since
 
2133
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
 
2134
        # test them through their use by the transport than directly (that's a
 
2135
        # bit less clean but far more simpler and effective).
 
2136
        self.server = ActivityHTTPServer('HTTP/1.1')
 
2137
        self._transport=_urllib.HttpTransport_urllib
 
2138
 
 
2139
        self.server.start_server()
 
2140
 
 
2141
        # We override at class level because constructors may propagate the
 
2142
        # bound method and render instance overriding ineffective (an
 
2143
        # alternative would be to define a specific ui factory instead...)
 
2144
        self.orig_report_activity = self._transport._report_activity
 
2145
        self._transport._report_activity = None
 
2146
 
 
2147
    def tearDown(self):
 
2148
        self._transport._report_activity = self.orig_report_activity
 
2149
        self.server.stop_server()
 
2150
        tests.TestCase.tearDown(self)
 
2151
 
 
2152
    def assertActivitiesMatch(self):
 
2153
        # Nothing to check here
 
2154
        pass
 
2155
 
 
2156
 
 
2157
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
 
2158
    """Test authentication on the redirected http server."""
 
2159
 
 
2160
    _auth_header = 'Authorization'
 
2161
    _password_prompt_prefix = ''
 
2162
    _username_prompt_prefix = ''
 
2163
    _auth_server = http_utils.HTTPBasicAuthServer
 
2164
    _transport = _urllib.HttpTransport_urllib
 
2165
 
 
2166
    def create_transport_readonly_server(self):
 
2167
        return self._auth_server()
 
2168
 
 
2169
    def create_transport_secondary_server(self):
 
2170
        """Create the secondary server redirecting to the primary server"""
 
2171
        new = self.get_readonly_server()
 
2172
 
 
2173
        redirecting = http_utils.HTTPServerRedirecting()
 
2174
        redirecting.redirect_to(new.host, new.port)
 
2175
        return redirecting
 
2176
 
 
2177
    def setUp(self):
 
2178
        super(TestAuthOnRedirected, self).setUp()
 
2179
        self.build_tree_contents([('a','a'),
 
2180
                                  ('1/',),
 
2181
                                  ('1/a', 'redirected once'),
 
2182
                                  ],)
 
2183
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2184
                                       self.new_server.port)
 
2185
        self.old_server.redirections = [
 
2186
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2187
        self.old_transport = self._transport(self.old_server.get_url())
 
2188
        self.new_server.add_user('joe', 'foo')
 
2189
 
 
2190
    def get_a(self, transport):
 
2191
        return transport.get('a')
 
2192
 
 
2193
    def test_auth_on_redirected_via_do_catching_redirections(self):
 
2194
        self.redirections = 0
 
2195
 
 
2196
        def redirected(transport, exception, redirection_notice):
 
2197
            self.redirections += 1
 
2198
            dir, file = urlutils.split(exception.target)
 
2199
            return self._transport(dir)
 
2200
 
 
2201
        stdout = tests.StringIOWrapper()
 
2202
        stderr = tests.StringIOWrapper()
 
2203
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2204
                                            stdout=stdout, stderr=stderr)
 
2205
        self.assertEqual('redirected once',
 
2206
                         transport.do_catching_redirections(
 
2207
                self.get_a, self.old_transport, redirected).read())
 
2208
        self.assertEqual(1, self.redirections)
 
2209
        # stdin should be empty
 
2210
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2211
        # stdout should be empty, stderr will contains the prompts
 
2212
        self.assertEqual('', stdout.getvalue())
 
2213
 
 
2214
    def test_auth_on_redirected_via_following_redirections(self):
 
2215
        self.new_server.add_user('joe', 'foo')
 
2216
        stdout = tests.StringIOWrapper()
 
2217
        stderr = tests.StringIOWrapper()
 
2218
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2219
                                            stdout=stdout, stderr=stderr)
 
2220
        t = self.old_transport
 
2221
        req = RedirectedRequest('GET', t.abspath('a'))
 
2222
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2223
                                       self.new_server.port)
 
2224
        self.old_server.redirections = [
 
2225
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2226
        self.assertEqual('redirected once',t._perform(req).read())
 
2227
        # stdin should be empty
 
2228
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2229
        # stdout should be empty, stderr will contains the prompts
 
2230
        self.assertEqual('', stdout.getvalue())
 
2231
 
 
2232