~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: John Arbash Meinel
  • Date: 2010-02-17 17:11:16 UTC
  • mfrom: (4797.2.17 2.1)
  • mto: (4797.2.18 2.1)
  • mto: This revision was merged to the branch mainline in revision 5055.
  • Revision ID: john@arbash-meinel.com-20100217171116-h7t9223ystbnx5h8
merge bzr.2.1 in preparation for NEWS entry.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
48
48
    deprecated_in,
49
49
    )
50
50
from bzrlib.tests import (
 
51
    features,
51
52
    http_server,
52
53
    http_utils,
53
54
    )
61
62
    )
62
63
 
63
64
 
64
 
try:
 
65
if features.pycurl.available():
65
66
    from bzrlib.transport.http._pycurl import PyCurlTransport
66
 
    pycurl_present = True
67
 
except errors.DependencyNotPresent:
68
 
    pycurl_present = False
69
67
 
70
68
 
71
69
def load_tests(standard_tests, module, loader):
84
82
                        _server=http_server.HttpServer_urllib,
85
83
                        _qualified_prefix='http+urllib',)),
86
84
        ]
87
 
    if pycurl_present:
 
85
    if features.pycurl.available():
88
86
        transport_scenarios.append(
89
87
            ('pycurl', dict(_transport=PyCurlTransport,
90
88
                            _server=http_server.HttpServer_PyCurl,
156
154
        activity_scenarios.append(
157
155
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
158
156
                                  _transport=_urllib.HttpTransport_urllib,)),)
159
 
    if pycurl_present:
 
157
    if features.pycurl.available():
160
158
        activity_scenarios.append(
161
159
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
162
160
                                 _transport=PyCurlTransport,)),)
220
218
    def get_url(self):
221
219
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
222
220
 
223
 
    def setUp(self):
 
221
    def start_server(self):
224
222
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
225
223
        self._sock.bind(('127.0.0.1', 0))
226
224
        self.host, self.port = self._sock.getsockname()
249
247
            # The client may have already closed the socket.
250
248
            pass
251
249
 
252
 
    def tearDown(self):
 
250
    def stop_server(self):
253
251
        try:
254
252
            self._sock.close()
255
253
        except socket.error:
269
267
 
270
268
    def test_empty_header(self):
271
269
        scheme, remainder = self.parse_header('')
272
 
        self.assertEquals('', scheme)
 
270
        self.assertEqual('', scheme)
273
271
        self.assertIs(None, remainder)
274
272
 
275
273
    def test_negotiate_header(self):
276
274
        scheme, remainder = self.parse_header('Negotiate')
277
 
        self.assertEquals('negotiate', scheme)
 
275
        self.assertEqual('negotiate', scheme)
278
276
        self.assertIs(None, remainder)
279
277
 
280
278
    def test_basic_header(self):
281
279
        scheme, remainder = self.parse_header(
282
280
            'Basic realm="Thou should not pass"')
283
 
        self.assertEquals('basic', scheme)
284
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
281
        self.assertEqual('basic', scheme)
 
282
        self.assertEqual('realm="Thou should not pass"', remainder)
285
283
 
286
284
    def test_basic_extract_realm(self):
287
285
        scheme, remainder = self.parse_header(
289
287
            _urllib2_wrappers.BasicAuthHandler)
290
288
        match, realm = self.auth_handler.extract_realm(remainder)
291
289
        self.assertTrue(match is not None)
292
 
        self.assertEquals('Thou should not pass', realm)
 
290
        self.assertEqual('Thou should not pass', realm)
293
291
 
294
292
    def test_digest_header(self):
295
293
        scheme, remainder = self.parse_header(
296
294
            'Digest realm="Thou should not pass"')
297
 
        self.assertEquals('digest', scheme)
298
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
295
        self.assertEqual('digest', scheme)
 
296
        self.assertEqual('realm="Thou should not pass"', remainder)
299
297
 
300
298
 
301
299
class TestHTTPServer(tests.TestCase):
308
306
 
309
307
        server = http_server.HttpServer(BogusRequestHandler)
310
308
        try:
311
 
            self.assertRaises(httplib.UnknownProtocol, server.setUp)
 
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
312
310
        except:
313
 
            server.tearDown()
 
311
            server.stop_server()
314
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
315
313
 
316
314
    def test_force_invalid_protocol(self):
317
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
318
316
        try:
319
 
            self.assertRaises(httplib.UnknownProtocol, server.setUp)
 
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
320
318
        except:
321
 
            server.tearDown()
 
319
            server.stop_server()
322
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
323
321
 
324
322
    def test_server_start_and_stop(self):
325
323
        server = http_server.HttpServer()
326
 
        server.setUp()
 
324
        server.start_server()
327
325
        try:
328
326
            self.assertTrue(server._http_running)
329
327
        finally:
330
 
            server.tearDown()
 
328
            server.stop_server()
331
329
        self.assertFalse(server._http_running)
332
330
 
333
331
    def test_create_http_server_one_zero(self):
376
374
    """Test case to inherit from if pycurl is present"""
377
375
 
378
376
    def _get_pycurl_maybe(self):
379
 
        try:
380
 
            from bzrlib.transport.http._pycurl import PyCurlTransport
381
 
            return PyCurlTransport
382
 
        except errors.DependencyNotPresent:
383
 
            raise tests.TestSkipped('pycurl not present')
 
377
        self.requireFeature(features.pycurl)
 
378
        return PyCurlTransport
384
379
 
385
380
    _transport = property(_get_pycurl_maybe)
386
381
 
393
388
    def test_url_parsing(self):
394
389
        f = FakeManager()
395
390
        url = http.extract_auth('http://example.com', f)
396
 
        self.assertEquals('http://example.com', url)
397
 
        self.assertEquals(0, len(f.credentials))
 
391
        self.assertEqual('http://example.com', url)
 
392
        self.assertEqual(0, len(f.credentials))
398
393
        url = http.extract_auth(
399
394
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
400
 
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
401
 
        self.assertEquals(1, len(f.credentials))
402
 
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
403
 
                          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])
404
399
 
405
400
 
406
401
class TestHttpTransportUrls(tests.TestCase):
433
428
    def test_http_impl_urls(self):
434
429
        """There are servers which ask for particular clients to connect"""
435
430
        server = self._server()
436
 
        server.setUp()
 
431
        server.start_server()
437
432
        try:
438
433
            url = server.get_url()
439
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
440
435
        finally:
441
 
            server.tearDown()
 
436
            server.stop_server()
442
437
 
443
438
 
444
439
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
453
448
        https by supplying a fake version_info that do not
454
449
        support it.
455
450
        """
456
 
        try:
457
 
            import pycurl
458
 
        except ImportError:
459
 
            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
460
454
 
461
455
        version_info_orig = pycurl.version_info
462
 
        try:
463
 
            # Now that we have pycurl imported, we can fake its version_info
464
 
            # This was taken from a windows pycurl without SSL
465
 
            # (thanks to bialix)
466
 
            pycurl.version_info = lambda : (2,
467
 
                                            '7.13.2',
468
 
                                            462082,
469
 
                                            'i386-pc-win32',
470
 
                                            2576,
471
 
                                            None,
472
 
                                            0,
473
 
                                            None,
474
 
                                            ('ftp', 'gopher', 'telnet',
475
 
                                             'dict', 'ldap', 'http', 'file'),
476
 
                                            None,
477
 
                                            0,
478
 
                                            None)
479
 
            self.assertRaises(errors.DependencyNotPresent, self._transport,
480
 
                              'https://launchpad.net')
481
 
        finally:
482
 
            # Restore the right function
 
456
        def restore():
483
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')
484
477
 
485
478
 
486
479
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
603
596
                                      protocol_version=self._protocol_version)
604
597
 
605
598
    def _testing_pycurl(self):
606
 
        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)
607
602
 
608
603
 
609
604
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
718
713
    _req_handler_class = BadProtocolRequestHandler
719
714
 
720
715
    def setUp(self):
721
 
        if pycurl_present and self._transport == PyCurlTransport:
 
716
        if self._testing_pycurl():
722
717
            raise tests.TestNotApplicable(
723
718
                "pycurl doesn't check the protocol version")
724
719
        super(TestBadProtocolServer, self).setUp()
768
763
        self.assertEqual(None, server.host)
769
764
        self.assertEqual(None, server.port)
770
765
 
771
 
    def test_setUp_and_tearDown(self):
 
766
    def test_setUp_and_stop(self):
772
767
        server = RecordingServer(expect_body_tail=None)
773
 
        server.setUp()
 
768
        server.start_server()
774
769
        try:
775
770
            self.assertNotEqual(None, server.host)
776
771
            self.assertNotEqual(None, server.port)
777
772
        finally:
778
 
            server.tearDown()
 
773
            server.stop_server()
779
774
        self.assertEqual(None, server.host)
780
775
        self.assertEqual(None, server.port)
781
776
 
1178
1173
        if self._testing_pycurl():
1179
1174
            # Oh my ! pycurl does not check for the port as part of
1180
1175
            # no_proxy :-( So we just test the host part
1181
 
            self.no_proxy_host = 'localhost'
 
1176
            self.no_proxy_host = self.server.host
1182
1177
        else:
1183
1178
            self.no_proxy_host = self.proxy_address
1184
1179
        # The secondary server is the proxy
1187
1182
        self._old_env = {}
1188
1183
 
1189
1184
    def _testing_pycurl(self):
1190
 
        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)
1191
1188
 
1192
1189
    def create_transport_secondary_server(self):
1193
1190
        """Creates an http server that will serve files with
1366
1363
        self.follow_redirections = True
1367
1364
 
1368
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
 
1369
1374
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1370
1375
    """Test redirections.
1371
1376
 
1381
1386
    """
1382
1387
 
1383
1388
    def setUp(self):
1384
 
        if pycurl_present and self._transport == PyCurlTransport:
 
1389
        if (features.pycurl.available()
 
1390
            and self._transport == PyCurlTransport):
1385
1391
            raise tests.TestNotApplicable(
1386
1392
                "pycurl doesn't redirect silently annymore")
1387
1393
        super(TestHTTPSilentRedirections, self).setUp()
1388
 
        self.setup_redirected_request()
1389
 
        self.addCleanup(self.cleanup_redirected_request)
 
1394
        install_redirected_request(self)
1390
1395
        self.build_tree_contents([('a','a'),
1391
1396
                                  ('1/',),
1392
1397
                                  ('1/a', 'redirected once'),
1402
1407
 
1403
1408
        self.old_transport = self._transport(self.old_server.get_url())
1404
1409
 
1405
 
    def setup_redirected_request(self):
1406
 
        self.original_class = _urllib2_wrappers.Request
1407
 
        _urllib2_wrappers.Request = RedirectedRequest
1408
 
 
1409
 
    def cleanup_redirected_request(self):
1410
 
        _urllib2_wrappers.Request = self.original_class
1411
 
 
1412
1410
    def create_transport_secondary_server(self):
1413
1411
        """Create the secondary server, redirections are defined in the tests"""
1414
1412
        return http_utils.HTTPServerRedirecting(
1418
1416
        t = self.old_transport
1419
1417
 
1420
1418
        req = RedirectedRequest('GET', t.abspath('a'))
1421
 
        req.follow_redirections = True
1422
1419
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1423
1420
                                       self.new_server.port)
1424
1421
        self.old_server.redirections = \
1425
1422
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1426
 
        self.assertEquals('redirected once',t._perform(req).read())
 
1423
        self.assertEqual('redirected once',t._perform(req).read())
1427
1424
 
1428
1425
    def test_five_redirections(self):
1429
1426
        t = self.old_transport
1430
1427
 
1431
1428
        req = RedirectedRequest('GET', t.abspath('a'))
1432
 
        req.follow_redirections = True
1433
1429
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1434
1430
                                       self.old_server.port)
1435
1431
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1441
1437
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1442
1438
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1443
1439
            ]
1444
 
        self.assertEquals('redirected 5 times',t._perform(req).read())
 
1440
        self.assertEqual('redirected 5 times',t._perform(req).read())
1445
1441
 
1446
1442
 
1447
1443
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1460
1456
        t = self._transport(self.new_server.get_url())
1461
1457
 
1462
1458
        # We use None for redirected so that we fail if redirected
1463
 
        self.assertEquals('0123456789',
1464
 
                          transport.do_catching_redirections(
 
1459
        self.assertEqual('0123456789',
 
1460
                         transport.do_catching_redirections(
1465
1461
                self.get_a, t, None).read())
1466
1462
 
1467
1463
    def test_one_redirection(self):
1472
1468
            dir, file = urlutils.split(exception.target)
1473
1469
            return self._transport(dir)
1474
1470
 
1475
 
        self.assertEquals('0123456789',
1476
 
                          transport.do_catching_redirections(
 
1471
        self.assertEqual('0123456789',
 
1472
                         transport.do_catching_redirections(
1477
1473
                self.get_a, self.old_transport, redirected).read())
1478
 
        self.assertEquals(1, self.redirections)
 
1474
        self.assertEqual(1, self.redirections)
1479
1475
 
1480
1476
    def test_redirection_loop(self):
1481
1477
 
1509
1505
        return self._auth_server(protocol_version=self._protocol_version)
1510
1506
 
1511
1507
    def _testing_pycurl(self):
1512
 
        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)
1513
1511
 
1514
1512
    def get_user_url(self, user, password):
1515
1513
        """Build an url embedding user and password"""
1580
1578
        self.assertEqual('', ui.ui_factory.stdin.readline())
1581
1579
        stderr.seek(0)
1582
1580
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1583
 
        self.assertEquals(expected_prompt, stderr.read(len(expected_prompt)))
1584
 
        self.assertEquals('', stdout.getvalue())
 
1581
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
 
1582
        self.assertEqual('', stdout.getvalue())
1585
1583
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1586
1584
                                    stderr.readline())
1587
1585
 
1602
1600
        self.assertEqual('', ui.ui_factory.stdin.readline())
1603
1601
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1604
1602
                                    stderr.getvalue())
1605
 
        self.assertEquals('', stdout.getvalue())
 
1603
        self.assertEqual('', stdout.getvalue())
1606
1604
        # And we shouldn't prompt again for a different request
1607
1605
        # against the same transport.
1608
1606
        self.assertEqual('contents of b\n',t.get('b').read())
1618
1616
                              % (scheme.upper(),
1619
1617
                                 user, self.server.host, self.server.port,
1620
1618
                                 self.server.auth_realm)))
1621
 
        self.assertEquals(expected_prompt, actual_prompt)
 
1619
        self.assertEqual(expected_prompt, actual_prompt)
1622
1620
 
1623
1621
    def _expected_username_prompt(self, scheme):
1624
1622
        return (self._username_prompt_prefix
1638
1636
        self.server.add_user(user, password)
1639
1637
        t = self.get_user_transport(user, None)
1640
1638
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1641
 
                                            stdout=tests.StringIOWrapper())
 
1639
                                            stderr=tests.StringIOWrapper())
1642
1640
        # Create a minimal config file with the right password
1643
1641
        conf = config.AuthenticationConfig()
1644
1642
        conf._get_config().update(
1856
1854
                             'http://www.example.com/foo/subdir')
1857
1855
        self.assertIsInstance(r, type(t))
1858
1856
        # Both transports share the some connection
1859
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1857
        self.assertEqual(t._get_connection(), r._get_connection())
1860
1858
 
1861
1859
    def test_redirected_to_self_with_slash(self):
1862
1860
        t = self._transport('http://www.example.com/foo')
1866
1864
        # Both transports share the some connection (one can argue that we
1867
1865
        # should return the exact same transport here, but that seems
1868
1866
        # overkill).
1869
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1867
        self.assertEqual(t._get_connection(), r._get_connection())
1870
1868
 
1871
1869
    def test_redirected_to_host(self):
1872
1870
        t = self._transport('http://www.example.com/foo')
1891
1889
        r = t._redirected_to('http://www.example.com/foo',
1892
1890
                             'https://foo.example.com/foo')
1893
1891
        self.assertIsInstance(r, type(t))
1894
 
        self.assertEquals(t._user, r._user)
 
1892
        self.assertEqual(t._user, r._user)
1895
1893
 
1896
1894
 
1897
1895
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1956
1954
        pass
1957
1955
 
1958
1956
 
1959
 
class TestActivity(tests.TestCase):
 
1957
class TestActivityMixin(object):
1960
1958
    """Test socket activity reporting.
1961
1959
 
1962
1960
    We use a special purpose server to control the bytes sent and received and
1966
1964
    def setUp(self):
1967
1965
        tests.TestCase.setUp(self)
1968
1966
        self.server = self._activity_server(self._protocol_version)
1969
 
        self.server.setUp()
 
1967
        self.server.start_server()
1970
1968
        self.activities = {}
1971
1969
        def report_activity(t, bytes, direction):
1972
1970
            count = self.activities.get(direction, 0)
1981
1979
 
1982
1980
    def tearDown(self):
1983
1981
        self._transport._report_activity = self.orig_report_activity
1984
 
        self.server.tearDown()
 
1982
        self.server.stop_server()
1985
1983
        tests.TestCase.tearDown(self)
1986
1984
 
1987
1985
    def get_transport(self):
2100
2098
        code, f = t._post('abc def end-of-body\n')
2101
2099
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2102
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