~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: 2010-02-11 04:02:41 UTC
  • mfrom: (5017.2.2 tariff)
  • Revision ID: pqm@pqm.ubuntu.com-20100211040241-w6n021dz0uus341n
(mbp) add import-tariff tests

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,)),)
204
202
    It records the bytes sent to it, and replies with a 200.
205
203
    """
206
204
 
207
 
    def __init__(self, expect_body_tail=None):
 
205
    def __init__(self, expect_body_tail=None, scheme=''):
208
206
        """Constructor.
209
207
 
210
208
        :type expect_body_tail: str
215
213
        self.host = None
216
214
        self.port = None
217
215
        self.received_bytes = ''
218
 
 
219
 
    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):
220
222
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
221
223
        self._sock.bind(('127.0.0.1', 0))
222
224
        self.host, self.port = self._sock.getsockname()
245
247
            # The client may have already closed the socket.
246
248
            pass
247
249
 
248
 
    def tearDown(self):
 
250
    def stop_server(self):
249
251
        try:
250
252
            self._sock.close()
251
253
        except socket.error:
265
267
 
266
268
    def test_empty_header(self):
267
269
        scheme, remainder = self.parse_header('')
268
 
        self.assertEquals('', scheme)
 
270
        self.assertEqual('', scheme)
269
271
        self.assertIs(None, remainder)
270
272
 
271
273
    def test_negotiate_header(self):
272
274
        scheme, remainder = self.parse_header('Negotiate')
273
 
        self.assertEquals('negotiate', scheme)
 
275
        self.assertEqual('negotiate', scheme)
274
276
        self.assertIs(None, remainder)
275
277
 
276
278
    def test_basic_header(self):
277
279
        scheme, remainder = self.parse_header(
278
280
            'Basic realm="Thou should not pass"')
279
 
        self.assertEquals('basic', scheme)
280
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
281
        self.assertEqual('basic', scheme)
 
282
        self.assertEqual('realm="Thou should not pass"', remainder)
281
283
 
282
284
    def test_basic_extract_realm(self):
283
285
        scheme, remainder = self.parse_header(
285
287
            _urllib2_wrappers.BasicAuthHandler)
286
288
        match, realm = self.auth_handler.extract_realm(remainder)
287
289
        self.assertTrue(match is not None)
288
 
        self.assertEquals('Thou should not pass', realm)
 
290
        self.assertEqual('Thou should not pass', realm)
289
291
 
290
292
    def test_digest_header(self):
291
293
        scheme, remainder = self.parse_header(
292
294
            'Digest realm="Thou should not pass"')
293
 
        self.assertEquals('digest', scheme)
294
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
295
        self.assertEqual('digest', scheme)
 
296
        self.assertEqual('realm="Thou should not pass"', remainder)
295
297
 
296
298
 
297
299
class TestHTTPServer(tests.TestCase):
304
306
 
305
307
        server = http_server.HttpServer(BogusRequestHandler)
306
308
        try:
307
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
308
310
        except:
309
 
            server.tearDown()
 
311
            server.stop_server()
310
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
311
313
 
312
314
    def test_force_invalid_protocol(self):
313
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
314
316
        try:
315
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
316
318
        except:
317
 
            server.tearDown()
 
319
            server.stop_server()
318
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
319
321
 
320
322
    def test_server_start_and_stop(self):
321
323
        server = http_server.HttpServer()
322
 
        server.setUp()
323
 
        self.assertTrue(server._http_running)
324
 
        server.tearDown()
 
324
        server.start_server()
 
325
        try:
 
326
            self.assertTrue(server._http_running)
 
327
        finally:
 
328
            server.stop_server()
325
329
        self.assertFalse(server._http_running)
326
330
 
327
331
    def test_create_http_server_one_zero(self):
330
334
            protocol_version = 'HTTP/1.0'
331
335
 
332
336
        server = http_server.HttpServer(RequestHandlerOneZero)
333
 
        server.setUp()
334
 
        self.addCleanup(server.tearDown)
 
337
        self.start_server(server)
335
338
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
336
339
 
337
340
    def test_create_http_server_one_one(self):
340
343
            protocol_version = 'HTTP/1.1'
341
344
 
342
345
        server = http_server.HttpServer(RequestHandlerOneOne)
343
 
        server.setUp()
344
 
        self.addCleanup(server.tearDown)
 
346
        self.start_server(server)
345
347
        self.assertIsInstance(server._httpd,
346
348
                              http_server.TestingThreadingHTTPServer)
347
349
 
352
354
 
353
355
        server = http_server.HttpServer(RequestHandlerOneZero,
354
356
                                        protocol_version='HTTP/1.1')
355
 
        server.setUp()
356
 
        self.addCleanup(server.tearDown)
 
357
        self.start_server(server)
357
358
        self.assertIsInstance(server._httpd,
358
359
                              http_server.TestingThreadingHTTPServer)
359
360
 
364
365
 
365
366
        server = http_server.HttpServer(RequestHandlerOneOne,
366
367
                                        protocol_version='HTTP/1.0')
367
 
        server.setUp()
368
 
        self.addCleanup(server.tearDown)
 
368
        self.start_server(server)
369
369
        self.assertIsInstance(server._httpd,
370
370
                              http_server.TestingHTTPServer)
371
371
 
374
374
    """Test case to inherit from if pycurl is present"""
375
375
 
376
376
    def _get_pycurl_maybe(self):
377
 
        try:
378
 
            from bzrlib.transport.http._pycurl import PyCurlTransport
379
 
            return PyCurlTransport
380
 
        except errors.DependencyNotPresent:
381
 
            raise tests.TestSkipped('pycurl not present')
 
377
        self.requireFeature(features.pycurl)
 
378
        return PyCurlTransport
382
379
 
383
380
    _transport = property(_get_pycurl_maybe)
384
381
 
391
388
    def test_url_parsing(self):
392
389
        f = FakeManager()
393
390
        url = http.extract_auth('http://example.com', f)
394
 
        self.assertEquals('http://example.com', url)
395
 
        self.assertEquals(0, len(f.credentials))
 
391
        self.assertEqual('http://example.com', url)
 
392
        self.assertEqual(0, len(f.credentials))
396
393
        url = http.extract_auth(
397
 
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
398
 
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
399
 
        self.assertEquals(1, len(f.credentials))
400
 
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
401
 
                          f.credentials[0])
 
394
            'http://user:pass@example.com/bzr/bzr.dev', f)
 
395
        self.assertEqual('http://example.com/bzr/bzr.dev', url)
 
396
        self.assertEqual(1, len(f.credentials))
 
397
        self.assertEqual([None, 'example.com', 'user', 'pass'],
 
398
                         f.credentials[0])
402
399
 
403
400
 
404
401
class TestHttpTransportUrls(tests.TestCase):
431
428
    def test_http_impl_urls(self):
432
429
        """There are servers which ask for particular clients to connect"""
433
430
        server = self._server()
 
431
        server.start_server()
434
432
        try:
435
 
            server.setUp()
436
433
            url = server.get_url()
437
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
438
435
        finally:
439
 
            server.tearDown()
 
436
            server.stop_server()
440
437
 
441
438
 
442
439
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
451
448
        https by supplying a fake version_info that do not
452
449
        support it.
453
450
        """
454
 
        try:
455
 
            import pycurl
456
 
        except ImportError:
457
 
            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
458
454
 
459
 
        version_info_orig = pycurl.version_info
460
 
        try:
461
 
            # Now that we have pycurl imported, we can fake its version_info
462
 
            # This was taken from a windows pycurl without SSL
463
 
            # (thanks to bialix)
464
 
            pycurl.version_info = lambda : (2,
465
 
                                            '7.13.2',
466
 
                                            462082,
467
 
                                            'i386-pc-win32',
468
 
                                            2576,
469
 
                                            None,
470
 
                                            0,
471
 
                                            None,
472
 
                                            ('ftp', 'gopher', 'telnet',
473
 
                                             'dict', 'ldap', 'http', 'file'),
474
 
                                            None,
475
 
                                            0,
476
 
                                            None)
477
 
            self.assertRaises(errors.DependencyNotPresent, self._transport,
478
 
                              'https://launchpad.net')
479
 
        finally:
480
 
            # Restore the right function
481
 
            pycurl.version_info = version_info_orig
 
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')
482
473
 
483
474
 
484
475
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
543
534
class TestPost(tests.TestCase):
544
535
 
545
536
    def test_post_body_is_received(self):
546
 
        server = RecordingServer(expect_body_tail='end-of-body')
547
 
        server.setUp()
548
 
        self.addCleanup(server.tearDown)
549
 
        scheme = self._qualified_prefix
550
 
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
 
537
        server = RecordingServer(expect_body_tail='end-of-body',
 
538
            scheme=self._qualified_prefix)
 
539
        self.start_server(server)
 
540
        url = server.get_url()
551
541
        http_transport = self._transport(url)
552
542
        code, response = http_transport._post('abc def end-of-body')
553
543
        self.assertTrue(
602
592
                                      protocol_version=self._protocol_version)
603
593
 
604
594
    def _testing_pycurl(self):
605
 
        return pycurl_present and self._transport == PyCurlTransport
 
595
        # TODO: This is duplicated for lots of the classes in this file
 
596
        return (features.pycurl.available()
 
597
                and self._transport == PyCurlTransport)
606
598
 
607
599
 
608
600
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
625
617
        # for details) make no distinction between a closed
626
618
        # socket and badly formatted status line, so we can't
627
619
        # just test for ConnectionError, we have to test
628
 
        # InvalidHttpResponse too.
629
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
620
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
 
621
        # instead of ConnectionError too.
 
622
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
 
623
                            errors.InvalidHttpResponse),
630
624
                          t.has, 'foo/bar')
631
625
 
632
626
    def test_http_get(self):
633
627
        server = self.get_readonly_server()
634
628
        t = self._transport(server.get_url())
635
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
629
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
 
630
                           errors.InvalidHttpResponse),
636
631
                          t.get, 'foo/bar')
637
632
 
638
633
 
714
709
    _req_handler_class = BadProtocolRequestHandler
715
710
 
716
711
    def setUp(self):
717
 
        if pycurl_present and self._transport == PyCurlTransport:
 
712
        if self._testing_pycurl():
718
713
            raise tests.TestNotApplicable(
719
714
                "pycurl doesn't check the protocol version")
720
715
        super(TestBadProtocolServer, self).setUp()
764
759
        self.assertEqual(None, server.host)
765
760
        self.assertEqual(None, server.port)
766
761
 
767
 
    def test_setUp_and_tearDown(self):
 
762
    def test_setUp_and_stop(self):
768
763
        server = RecordingServer(expect_body_tail=None)
769
 
        server.setUp()
 
764
        server.start_server()
770
765
        try:
771
766
            self.assertNotEqual(None, server.host)
772
767
            self.assertNotEqual(None, server.port)
773
768
        finally:
774
 
            server.tearDown()
 
769
            server.stop_server()
775
770
        self.assertEqual(None, server.host)
776
771
        self.assertEqual(None, server.port)
777
772
 
778
773
    def test_send_receive_bytes(self):
779
 
        server = RecordingServer(expect_body_tail='c')
780
 
        server.setUp()
781
 
        self.addCleanup(server.tearDown)
 
774
        server = RecordingServer(expect_body_tail='c', scheme='http')
 
775
        self.start_server(server)
782
776
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
783
777
        sock.connect((server.host, server.port))
784
778
        sock.sendall('abc')
1175
1169
        if self._testing_pycurl():
1176
1170
            # Oh my ! pycurl does not check for the port as part of
1177
1171
            # no_proxy :-( So we just test the host part
1178
 
            self.no_proxy_host = 'localhost'
 
1172
            self.no_proxy_host = self.server.host
1179
1173
        else:
1180
1174
            self.no_proxy_host = self.proxy_address
1181
1175
        # The secondary server is the proxy
1184
1178
        self._old_env = {}
1185
1179
 
1186
1180
    def _testing_pycurl(self):
1187
 
        return pycurl_present and self._transport == PyCurlTransport
 
1181
        # TODO: This is duplicated for lots of the classes in this file
 
1182
        return (features.pycurl.available()
 
1183
                and self._transport == PyCurlTransport)
1188
1184
 
1189
1185
    def create_transport_secondary_server(self):
1190
1186
        """Creates an http server that will serve files with
1363
1359
        self.follow_redirections = True
1364
1360
 
1365
1361
 
 
1362
def install_redirected_request(test):
 
1363
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
 
1364
 
 
1365
 
1366
1366
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1367
1367
    """Test redirections.
1368
1368
 
1378
1378
    """
1379
1379
 
1380
1380
    def setUp(self):
1381
 
        if pycurl_present and self._transport == PyCurlTransport:
 
1381
        if (features.pycurl.available()
 
1382
            and self._transport == PyCurlTransport):
1382
1383
            raise tests.TestNotApplicable(
1383
1384
                "pycurl doesn't redirect silently annymore")
1384
1385
        super(TestHTTPSilentRedirections, self).setUp()
1385
 
        self.setup_redirected_request()
1386
 
        self.addCleanup(self.cleanup_redirected_request)
 
1386
        install_redirected_request(self)
1387
1387
        self.build_tree_contents([('a','a'),
1388
1388
                                  ('1/',),
1389
1389
                                  ('1/a', 'redirected once'),
1399
1399
 
1400
1400
        self.old_transport = self._transport(self.old_server.get_url())
1401
1401
 
1402
 
    def setup_redirected_request(self):
1403
 
        self.original_class = _urllib2_wrappers.Request
1404
 
        _urllib2_wrappers.Request = RedirectedRequest
1405
 
 
1406
 
    def cleanup_redirected_request(self):
1407
 
        _urllib2_wrappers.Request = self.original_class
1408
 
 
1409
1402
    def create_transport_secondary_server(self):
1410
1403
        """Create the secondary server, redirections are defined in the tests"""
1411
1404
        return http_utils.HTTPServerRedirecting(
1415
1408
        t = self.old_transport
1416
1409
 
1417
1410
        req = RedirectedRequest('GET', t.abspath('a'))
1418
 
        req.follow_redirections = True
1419
1411
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1420
1412
                                       self.new_server.port)
1421
1413
        self.old_server.redirections = \
1422
1414
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1423
 
        self.assertEquals('redirected once',t._perform(req).read())
 
1415
        self.assertEqual('redirected once',t._perform(req).read())
1424
1416
 
1425
1417
    def test_five_redirections(self):
1426
1418
        t = self.old_transport
1427
1419
 
1428
1420
        req = RedirectedRequest('GET', t.abspath('a'))
1429
 
        req.follow_redirections = True
1430
1421
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1431
1422
                                       self.old_server.port)
1432
1423
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1438
1429
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1439
1430
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1440
1431
            ]
1441
 
        self.assertEquals('redirected 5 times',t._perform(req).read())
 
1432
        self.assertEqual('redirected 5 times',t._perform(req).read())
1442
1433
 
1443
1434
 
1444
1435
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1457
1448
        t = self._transport(self.new_server.get_url())
1458
1449
 
1459
1450
        # We use None for redirected so that we fail if redirected
1460
 
        self.assertEquals('0123456789',
1461
 
                          transport.do_catching_redirections(
 
1451
        self.assertEqual('0123456789',
 
1452
                         transport.do_catching_redirections(
1462
1453
                self.get_a, t, None).read())
1463
1454
 
1464
1455
    def test_one_redirection(self):
1469
1460
            dir, file = urlutils.split(exception.target)
1470
1461
            return self._transport(dir)
1471
1462
 
1472
 
        self.assertEquals('0123456789',
1473
 
                          transport.do_catching_redirections(
 
1463
        self.assertEqual('0123456789',
 
1464
                         transport.do_catching_redirections(
1474
1465
                self.get_a, self.old_transport, redirected).read())
1475
 
        self.assertEquals(1, self.redirections)
 
1466
        self.assertEqual(1, self.redirections)
1476
1467
 
1477
1468
    def test_redirection_loop(self):
1478
1469
 
1506
1497
        return self._auth_server(protocol_version=self._protocol_version)
1507
1498
 
1508
1499
    def _testing_pycurl(self):
1509
 
        return pycurl_present and self._transport == PyCurlTransport
 
1500
        # TODO: This is duplicated for lots of the classes in this file
 
1501
        return (features.pycurl.available()
 
1502
                and self._transport == PyCurlTransport)
1510
1503
 
1511
1504
    def get_user_url(self, user, password):
1512
1505
        """Build an url embedding user and password"""
1577
1570
        self.assertEqual('', ui.ui_factory.stdin.readline())
1578
1571
        stderr.seek(0)
1579
1572
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1580
 
        self.assertEquals(expected_prompt, stderr.read(len(expected_prompt)))
1581
 
        self.assertEquals('', stdout.getvalue())
 
1573
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
 
1574
        self.assertEqual('', stdout.getvalue())
1582
1575
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1583
1576
                                    stderr.readline())
1584
1577
 
1599
1592
        self.assertEqual('', ui.ui_factory.stdin.readline())
1600
1593
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1601
1594
                                    stderr.getvalue())
1602
 
        self.assertEquals('', stdout.getvalue())
 
1595
        self.assertEqual('', stdout.getvalue())
1603
1596
        # And we shouldn't prompt again for a different request
1604
1597
        # against the same transport.
1605
1598
        self.assertEqual('contents of b\n',t.get('b').read())
1615
1608
                              % (scheme.upper(),
1616
1609
                                 user, self.server.host, self.server.port,
1617
1610
                                 self.server.auth_realm)))
1618
 
        self.assertEquals(expected_prompt, actual_prompt)
 
1611
        self.assertEqual(expected_prompt, actual_prompt)
1619
1612
 
1620
1613
    def _expected_username_prompt(self, scheme):
1621
1614
        return (self._username_prompt_prefix
1635
1628
        self.server.add_user(user, password)
1636
1629
        t = self.get_user_transport(user, None)
1637
1630
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1638
 
                                            stdout=tests.StringIOWrapper())
 
1631
                                            stderr=tests.StringIOWrapper())
1639
1632
        # Create a minimal config file with the right password
1640
1633
        conf = config.AuthenticationConfig()
1641
1634
        conf._get_config().update(
1853
1846
                             'http://www.example.com/foo/subdir')
1854
1847
        self.assertIsInstance(r, type(t))
1855
1848
        # Both transports share the some connection
1856
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1849
        self.assertEqual(t._get_connection(), r._get_connection())
1857
1850
 
1858
1851
    def test_redirected_to_self_with_slash(self):
1859
1852
        t = self._transport('http://www.example.com/foo')
1863
1856
        # Both transports share the some connection (one can argue that we
1864
1857
        # should return the exact same transport here, but that seems
1865
1858
        # overkill).
1866
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1859
        self.assertEqual(t._get_connection(), r._get_connection())
1867
1860
 
1868
1861
    def test_redirected_to_host(self):
1869
1862
        t = self._transport('http://www.example.com/foo')
1888
1881
        r = t._redirected_to('http://www.example.com/foo',
1889
1882
                             'https://foo.example.com/foo')
1890
1883
        self.assertIsInstance(r, type(t))
1891
 
        self.assertEquals(t._user, r._user)
 
1884
        self.assertEqual(t._user, r._user)
1892
1885
 
1893
1886
 
1894
1887
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1953
1946
        pass
1954
1947
 
1955
1948
 
1956
 
class TestActivity(tests.TestCase):
 
1949
class TestActivityMixin(object):
1957
1950
    """Test socket activity reporting.
1958
1951
 
1959
1952
    We use a special purpose server to control the bytes sent and received and
1963
1956
    def setUp(self):
1964
1957
        tests.TestCase.setUp(self)
1965
1958
        self.server = self._activity_server(self._protocol_version)
1966
 
        self.server.setUp()
 
1959
        self.server.start_server()
1967
1960
        self.activities = {}
1968
1961
        def report_activity(t, bytes, direction):
1969
1962
            count = self.activities.get(direction, 0)
1978
1971
 
1979
1972
    def tearDown(self):
1980
1973
        self._transport._report_activity = self.orig_report_activity
1981
 
        self.server.tearDown()
 
1974
        self.server.stop_server()
1982
1975
        tests.TestCase.tearDown(self)
1983
1976
 
1984
1977
    def get_transport(self):
2097
2090
        code, f = t._post('abc def end-of-body\n')
2098
2091
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2099
2092
        self.assertActivitiesMatch()
 
2093
 
 
2094
 
 
2095
class TestActivity(tests.TestCase, TestActivityMixin):
 
2096
 
 
2097
    def setUp(self):
 
2098
        tests.TestCase.setUp(self)
 
2099
        self.server = self._activity_server(self._protocol_version)
 
2100
        self.server.start_server()
 
2101
        self.activities = {}
 
2102
        def report_activity(t, bytes, direction):
 
2103
            count = self.activities.get(direction, 0)
 
2104
            count += bytes
 
2105
            self.activities[direction] = count
 
2106
 
 
2107
        # We override at class level because constructors may propagate the
 
2108
        # bound method and render instance overriding ineffective (an
 
2109
        # alternative would be to define a specific ui factory instead...)
 
2110
        self.orig_report_activity = self._transport._report_activity
 
2111
        self._transport._report_activity = report_activity
 
2112
 
 
2113
    def tearDown(self):
 
2114
        self._transport._report_activity = self.orig_report_activity
 
2115
        self.server.stop_server()
 
2116
        tests.TestCase.tearDown(self)
 
2117
 
 
2118
 
 
2119
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
 
2120
 
 
2121
    def setUp(self):
 
2122
        tests.TestCase.setUp(self)
 
2123
        # Unlike TestActivity, we are really testing ReportingFileSocket and
 
2124
        # ReportingSocket, so we don't need all the parametrization. Since
 
2125
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
 
2126
        # test them through their use by the transport than directly (that's a
 
2127
        # bit less clean but far more simpler and effective).
 
2128
        self.server = ActivityHTTPServer('HTTP/1.1')
 
2129
        self._transport=_urllib.HttpTransport_urllib
 
2130
 
 
2131
        self.server.start_server()
 
2132
 
 
2133
        # We override at class level because constructors may propagate the
 
2134
        # bound method and render instance overriding ineffective (an
 
2135
        # alternative would be to define a specific ui factory instead...)
 
2136
        self.orig_report_activity = self._transport._report_activity
 
2137
        self._transport._report_activity = None
 
2138
 
 
2139
    def tearDown(self):
 
2140
        self._transport._report_activity = self.orig_report_activity
 
2141
        self.server.stop_server()
 
2142
        tests.TestCase.tearDown(self)
 
2143
 
 
2144
    def assertActivitiesMatch(self):
 
2145
        # Nothing to check here
 
2146
        pass
 
2147
 
 
2148
 
 
2149
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
 
2150
    """Test authentication on the redirected http server."""
 
2151
 
 
2152
    _auth_header = 'Authorization'
 
2153
    _password_prompt_prefix = ''
 
2154
    _username_prompt_prefix = ''
 
2155
    _auth_server = http_utils.HTTPBasicAuthServer
 
2156
    _transport = _urllib.HttpTransport_urllib
 
2157
 
 
2158
    def create_transport_readonly_server(self):
 
2159
        return self._auth_server()
 
2160
 
 
2161
    def create_transport_secondary_server(self):
 
2162
        """Create the secondary server redirecting to the primary server"""
 
2163
        new = self.get_readonly_server()
 
2164
 
 
2165
        redirecting = http_utils.HTTPServerRedirecting()
 
2166
        redirecting.redirect_to(new.host, new.port)
 
2167
        return redirecting
 
2168
 
 
2169
    def setUp(self):
 
2170
        super(TestAuthOnRedirected, self).setUp()
 
2171
        self.build_tree_contents([('a','a'),
 
2172
                                  ('1/',),
 
2173
                                  ('1/a', 'redirected once'),
 
2174
                                  ],)
 
2175
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2176
                                       self.new_server.port)
 
2177
        self.old_server.redirections = [
 
2178
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2179
        self.old_transport = self._transport(self.old_server.get_url())
 
2180
        self.new_server.add_user('joe', 'foo')
 
2181
 
 
2182
    def get_a(self, transport):
 
2183
        return transport.get('a')
 
2184
 
 
2185
    def test_auth_on_redirected_via_do_catching_redirections(self):
 
2186
        self.redirections = 0
 
2187
 
 
2188
        def redirected(transport, exception, redirection_notice):
 
2189
            self.redirections += 1
 
2190
            dir, file = urlutils.split(exception.target)
 
2191
            return self._transport(dir)
 
2192
 
 
2193
        stdout = tests.StringIOWrapper()
 
2194
        stderr = tests.StringIOWrapper()
 
2195
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2196
                                            stdout=stdout, stderr=stderr)
 
2197
        self.assertEqual('redirected once',
 
2198
                         transport.do_catching_redirections(
 
2199
                self.get_a, self.old_transport, redirected).read())
 
2200
        self.assertEqual(1, self.redirections)
 
2201
        # stdin should be empty
 
2202
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2203
        # stdout should be empty, stderr will contains the prompts
 
2204
        self.assertEqual('', stdout.getvalue())
 
2205
 
 
2206
    def test_auth_on_redirected_via_following_redirections(self):
 
2207
        self.new_server.add_user('joe', 'foo')
 
2208
        stdout = tests.StringIOWrapper()
 
2209
        stderr = tests.StringIOWrapper()
 
2210
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2211
                                            stdout=stdout, stderr=stderr)
 
2212
        t = self.old_transport
 
2213
        req = RedirectedRequest('GET', t.abspath('a'))
 
2214
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2215
                                       self.new_server.port)
 
2216
        self.old_server.redirections = [
 
2217
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2218
        self.assertEqual('redirected once',t._perform(req).read())
 
2219
        # stdin should be empty
 
2220
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2221
        # stdout should be empty, stderr will contains the prompts
 
2222
        self.assertEqual('', stdout.getvalue())
 
2223
 
 
2224