~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: 2009-09-22 02:18:24 UTC
  • mto: This revision was merged to the branch mainline in revision 4709.
  • Revision ID: john@arbash-meinel.com-20090922021824-j3en52uqoof7ym89
Remove some assert statements.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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
44
44
    ui,
45
45
    urlutils,
46
46
    )
 
47
from bzrlib.symbol_versioning import (
 
48
    deprecated_in,
 
49
    )
47
50
from bzrlib.tests import (
48
 
    features,
49
51
    http_server,
50
52
    http_utils,
51
 
    test_server,
52
53
    )
53
54
from bzrlib.transport import (
54
55
    http,
60
61
    )
61
62
 
62
63
 
63
 
if features.pycurl.available():
 
64
try:
64
65
    from bzrlib.transport.http._pycurl import PyCurlTransport
 
66
    pycurl_present = True
 
67
except errors.DependencyNotPresent:
 
68
    pycurl_present = False
65
69
 
66
70
 
67
71
def load_tests(standard_tests, module, loader):
78
82
    transport_scenarios = [
79
83
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
80
84
                        _server=http_server.HttpServer_urllib,
81
 
                        _url_protocol='http+urllib',)),
 
85
                        _qualified_prefix='http+urllib',)),
82
86
        ]
83
 
    if features.pycurl.available():
 
87
    if pycurl_present:
84
88
        transport_scenarios.append(
85
89
            ('pycurl', dict(_transport=PyCurlTransport,
86
90
                            _server=http_server.HttpServer_PyCurl,
87
 
                            _url_protocol='http+pycurl',)))
 
91
                            _qualified_prefix='http+pycurl',)))
88
92
    tests.multiply_tests(t_tests, transport_scenarios, result)
89
93
 
90
 
    protocol_scenarios = [
91
 
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
92
 
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
93
 
            ]
94
 
 
95
 
    # some tests are parametrized by the protocol version only
96
 
    p_tests, remaining_tests = tests.split_suite_by_condition(
97
 
        remaining_tests, tests.condition_isinstance((
98
 
                TestAuthOnRedirected,
99
 
                )))
100
 
    tests.multiply_tests(p_tests, protocol_scenarios, result)
101
 
 
102
94
    # each implementation tested with each HTTP version
103
95
    tp_tests, remaining_tests = tests.split_suite_by_condition(
104
96
        remaining_tests, tests.condition_isinstance((
113
105
                TestRanges,
114
106
                TestSpecificRequestHandler,
115
107
                )))
 
108
    protocol_scenarios = [
 
109
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
 
110
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
111
            ]
116
112
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
117
113
                                            protocol_scenarios)
118
114
    tests.multiply_tests(tp_tests, tp_scenarios, result)
160
156
        activity_scenarios.append(
161
157
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
162
158
                                  _transport=_urllib.HttpTransport_urllib,)),)
163
 
    if features.pycurl.available():
 
159
    if pycurl_present:
164
160
        activity_scenarios.append(
165
161
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
166
162
                                 _transport=PyCurlTransport,)),)
224
220
    def get_url(self):
225
221
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
226
222
 
227
 
    def start_server(self):
 
223
    def setUp(self):
228
224
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
229
225
        self._sock.bind(('127.0.0.1', 0))
230
226
        self.host, self.port = self._sock.getsockname()
231
227
        self._ready = threading.Event()
232
 
        self._thread = test_server.ThreadWithException(
233
 
            event=self._ready, target=self._accept_read_and_reply)
 
228
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
229
        self._thread.setDaemon(True)
234
230
        self._thread.start()
235
 
        if 'threads' in tests.selftest_debug_flags:
236
 
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
237
 
        self._ready.wait()
 
231
        self._ready.wait(5)
238
232
 
239
233
    def _accept_read_and_reply(self):
240
234
        self._sock.listen(1)
241
235
        self._ready.set()
242
 
        conn, address = self._sock.accept()
243
 
        if self._expect_body_tail is not None:
 
236
        self._sock.settimeout(5)
 
237
        try:
 
238
            conn, address = self._sock.accept()
 
239
            # On win32, the accepted connection will be non-blocking to start
 
240
            # with because we're using settimeout.
 
241
            conn.setblocking(True)
244
242
            while not self.received_bytes.endswith(self._expect_body_tail):
245
243
                self.received_bytes += conn.recv(4096)
246
244
            conn.sendall('HTTP/1.1 200 OK\r\n')
247
 
        try:
 
245
        except socket.timeout:
 
246
            # Make sure the client isn't stuck waiting for us to e.g. accept.
248
247
            self._sock.close()
249
248
        except socket.error:
250
249
            # The client may have already closed the socket.
251
250
            pass
252
251
 
253
 
    def stop_server(self):
 
252
    def tearDown(self):
254
253
        try:
255
 
            # Issue a fake connection to wake up the server and allow it to
256
 
            # finish quickly
257
 
            fake_conn = osutils.connect_socket((self.host, self.port))
258
 
            fake_conn.close()
 
254
            self._sock.close()
259
255
        except socket.error:
260
256
            # We might have already closed it.  We don't care.
261
257
            pass
262
258
        self.host = None
263
259
        self.port = None
264
 
        self._thread.join()
265
 
        if 'threads' in tests.selftest_debug_flags:
266
 
            sys.stderr.write('Thread  joined: %s\n' % (self._thread.ident,))
267
260
 
268
261
 
269
262
class TestAuthHeader(tests.TestCase):
276
269
 
277
270
    def test_empty_header(self):
278
271
        scheme, remainder = self.parse_header('')
279
 
        self.assertEqual('', scheme)
 
272
        self.assertEquals('', scheme)
280
273
        self.assertIs(None, remainder)
281
274
 
282
275
    def test_negotiate_header(self):
283
276
        scheme, remainder = self.parse_header('Negotiate')
284
 
        self.assertEqual('negotiate', scheme)
 
277
        self.assertEquals('negotiate', scheme)
285
278
        self.assertIs(None, remainder)
286
279
 
287
280
    def test_basic_header(self):
288
281
        scheme, remainder = self.parse_header(
289
282
            'Basic realm="Thou should not pass"')
290
 
        self.assertEqual('basic', scheme)
291
 
        self.assertEqual('realm="Thou should not pass"', remainder)
 
283
        self.assertEquals('basic', scheme)
 
284
        self.assertEquals('realm="Thou should not pass"', remainder)
292
285
 
293
286
    def test_basic_extract_realm(self):
294
287
        scheme, remainder = self.parse_header(
296
289
            _urllib2_wrappers.BasicAuthHandler)
297
290
        match, realm = self.auth_handler.extract_realm(remainder)
298
291
        self.assertTrue(match is not None)
299
 
        self.assertEqual('Thou should not pass', realm)
 
292
        self.assertEquals('Thou should not pass', realm)
300
293
 
301
294
    def test_digest_header(self):
302
295
        scheme, remainder = self.parse_header(
303
296
            'Digest realm="Thou should not pass"')
304
 
        self.assertEqual('digest', scheme)
305
 
        self.assertEqual('realm="Thou should not pass"', remainder)
 
297
        self.assertEquals('digest', scheme)
 
298
        self.assertEquals('realm="Thou should not pass"', remainder)
306
299
 
307
300
 
308
301
class TestHTTPServer(tests.TestCase):
313
306
 
314
307
            protocol_version = 'HTTP/0.1'
315
308
 
316
 
        self.assertRaises(httplib.UnknownProtocol,
317
 
                          http_server.HttpServer, BogusRequestHandler)
 
309
        server = http_server.HttpServer(BogusRequestHandler)
 
310
        try:
 
311
            self.assertRaises(httplib.UnknownProtocol, server.setUp)
 
312
        except:
 
313
            server.tearDown()
 
314
            self.fail('HTTP Server creation did not raise UnknownProtocol')
318
315
 
319
316
    def test_force_invalid_protocol(self):
320
 
        self.assertRaises(httplib.UnknownProtocol,
321
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
317
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
318
        try:
 
319
            self.assertRaises(httplib.UnknownProtocol, server.setUp)
 
320
        except:
 
321
            server.tearDown()
 
322
            self.fail('HTTP Server creation did not raise UnknownProtocol')
322
323
 
323
324
    def test_server_start_and_stop(self):
324
325
        server = http_server.HttpServer()
325
 
        self.addCleanup(server.stop_server)
326
 
        server.start_server()
327
 
        self.assertTrue(server.server is not None)
328
 
        self.assertTrue(server.server.serving is not None)
329
 
        self.assertTrue(server.server.serving)
 
326
        server.setUp()
 
327
        try:
 
328
            self.assertTrue(server._http_running)
 
329
        finally:
 
330
            server.tearDown()
 
331
        self.assertFalse(server._http_running)
330
332
 
331
333
    def test_create_http_server_one_zero(self):
332
334
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
335
337
 
336
338
        server = http_server.HttpServer(RequestHandlerOneZero)
337
339
        self.start_server(server)
338
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
340
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
339
341
 
340
342
    def test_create_http_server_one_one(self):
341
343
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
344
346
 
345
347
        server = http_server.HttpServer(RequestHandlerOneOne)
346
348
        self.start_server(server)
347
 
        self.assertIsInstance(server.server,
 
349
        self.assertIsInstance(server._httpd,
348
350
                              http_server.TestingThreadingHTTPServer)
349
351
 
350
352
    def test_create_http_server_force_one_one(self):
355
357
        server = http_server.HttpServer(RequestHandlerOneZero,
356
358
                                        protocol_version='HTTP/1.1')
357
359
        self.start_server(server)
358
 
        self.assertIsInstance(server.server,
 
360
        self.assertIsInstance(server._httpd,
359
361
                              http_server.TestingThreadingHTTPServer)
360
362
 
361
363
    def test_create_http_server_force_one_zero(self):
366
368
        server = http_server.HttpServer(RequestHandlerOneOne,
367
369
                                        protocol_version='HTTP/1.0')
368
370
        self.start_server(server)
369
 
        self.assertIsInstance(server.server,
 
371
        self.assertIsInstance(server._httpd,
370
372
                              http_server.TestingHTTPServer)
371
373
 
372
374
 
374
376
    """Test case to inherit from if pycurl is present"""
375
377
 
376
378
    def _get_pycurl_maybe(self):
377
 
        self.requireFeature(features.pycurl)
378
 
        return PyCurlTransport
 
379
        try:
 
380
            from bzrlib.transport.http._pycurl import PyCurlTransport
 
381
            return PyCurlTransport
 
382
        except errors.DependencyNotPresent:
 
383
            raise tests.TestSkipped('pycurl not present')
379
384
 
380
385
    _transport = property(_get_pycurl_maybe)
381
386
 
388
393
    def test_url_parsing(self):
389
394
        f = FakeManager()
390
395
        url = http.extract_auth('http://example.com', f)
391
 
        self.assertEqual('http://example.com', url)
392
 
        self.assertEqual(0, len(f.credentials))
 
396
        self.assertEquals('http://example.com', url)
 
397
        self.assertEquals(0, len(f.credentials))
393
398
        url = http.extract_auth(
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])
 
399
            '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])
399
404
 
400
405
 
401
406
class TestHttpTransportUrls(tests.TestCase):
428
433
    def test_http_impl_urls(self):
429
434
        """There are servers which ask for particular clients to connect"""
430
435
        server = self._server()
431
 
        server.start_server()
 
436
        server.setUp()
432
437
        try:
433
438
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
439
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
440
        finally:
436
 
            server.stop_server()
 
441
            server.tearDown()
437
442
 
438
443
 
439
444
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
448
453
        https by supplying a fake version_info that do not
449
454
        support it.
450
455
        """
451
 
        self.requireFeature(features.pycurl)
452
 
        # Import the module locally now that we now it's available.
453
 
        pycurl = features.pycurl.module
 
456
        try:
 
457
            import pycurl
 
458
        except ImportError:
 
459
            raise tests.TestSkipped('pycurl not present')
454
460
 
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')
 
461
        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
 
483
            pycurl.version_info = version_info_orig
473
484
 
474
485
 
475
486
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
482
493
 
483
494
    def test_http_has(self):
484
495
        server = self.get_readonly_server()
485
 
        t = self.get_readonly_transport()
 
496
        t = self._transport(server.get_url())
486
497
        self.assertEqual(t.has('foo/bar'), True)
487
498
        self.assertEqual(len(server.logs), 1)
488
499
        self.assertContainsRe(server.logs[0],
490
501
 
491
502
    def test_http_has_not_found(self):
492
503
        server = self.get_readonly_server()
493
 
        t = self.get_readonly_transport()
 
504
        t = self._transport(server.get_url())
494
505
        self.assertEqual(t.has('not-found'), False)
495
506
        self.assertContainsRe(server.logs[1],
496
507
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
497
508
 
498
509
    def test_http_get(self):
499
510
        server = self.get_readonly_server()
500
 
        t = self.get_readonly_transport()
 
511
        t = self._transport(server.get_url())
501
512
        fp = t.get('foo/bar')
502
513
        self.assertEqualDiff(
503
514
            fp.read(),
526
537
    """Test registrations of various http implementations"""
527
538
 
528
539
    def test_http_registered(self):
529
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
540
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
530
541
        self.assertIsInstance(t, transport.Transport)
531
542
        self.assertIsInstance(t, self._transport)
532
543
 
535
546
 
536
547
    def test_post_body_is_received(self):
537
548
        server = RecordingServer(expect_body_tail='end-of-body',
538
 
                                 scheme=self._url_protocol)
 
549
            scheme=self._qualified_prefix)
539
550
        self.start_server(server)
540
551
        url = server.get_url()
541
 
        # FIXME: needs a cleanup -- vila 20100611
542
 
        http_transport = transport.get_transport(url)
 
552
        http_transport = self._transport(url)
543
553
        code, response = http_transport._post('abc def end-of-body')
544
554
        self.assertTrue(
545
555
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
589
599
    _req_handler_class = http_server.TestingHTTPRequestHandler
590
600
 
591
601
    def create_transport_readonly_server(self):
592
 
        server = http_server.HttpServer(self._req_handler_class,
593
 
                                        protocol_version=self._protocol_version)
594
 
        server._url_protocol = self._url_protocol
595
 
        return server
 
602
        return http_server.HttpServer(self._req_handler_class,
 
603
                                      protocol_version=self._protocol_version)
596
604
 
597
605
    def _testing_pycurl(self):
598
 
        # TODO: This is duplicated for lots of the classes in this file
599
 
        return (features.pycurl.available()
600
 
                and self._transport == PyCurlTransport)
 
606
        return pycurl_present and self._transport == PyCurlTransport
601
607
 
602
608
 
603
609
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
604
610
    """Whatever request comes in, close the connection"""
605
611
 
606
 
    def _handle_one_request(self):
 
612
    def handle_one_request(self):
607
613
        """Handle a single HTTP request, by abruptly closing the connection"""
608
614
        self.close_connection = 1
609
615
 
614
620
    _req_handler_class = WallRequestHandler
615
621
 
616
622
    def test_http_has(self):
617
 
        t = self.get_readonly_transport()
 
623
        server = self.get_readonly_server()
 
624
        t = self._transport(server.get_url())
618
625
        # Unfortunately httplib (see HTTPResponse._read_status
619
626
        # for details) make no distinction between a closed
620
627
        # socket and badly formatted status line, so we can't
626
633
                          t.has, 'foo/bar')
627
634
 
628
635
    def test_http_get(self):
629
 
        t = self.get_readonly_transport()
 
636
        server = self.get_readonly_server()
 
637
        t = self._transport(server.get_url())
630
638
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
631
639
                           errors.InvalidHttpResponse),
632
640
                          t.get, 'foo/bar')
649
657
    _req_handler_class = BadStatusRequestHandler
650
658
 
651
659
    def test_http_has(self):
652
 
        t = self.get_readonly_transport()
 
660
        server = self.get_readonly_server()
 
661
        t = self._transport(server.get_url())
653
662
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
654
663
 
655
664
    def test_http_get(self):
656
 
        t = self.get_readonly_transport()
 
665
        server = self.get_readonly_server()
 
666
        t = self._transport(server.get_url())
657
667
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
658
668
 
659
669
 
664
674
        """Fakes handling a single HTTP request, returns a bad status"""
665
675
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
666
676
        self.wfile.write("Invalid status line\r\n")
667
 
        # If we don't close the connection pycurl will hang. Since this is a
668
 
        # stress test we don't *have* to respect the protocol, but we don't
669
 
        # have to sabotage it too much either.
670
 
        self.close_connection = True
671
677
        return False
672
678
 
673
679
 
679
685
 
680
686
    _req_handler_class = InvalidStatusRequestHandler
681
687
 
 
688
    def test_http_has(self):
 
689
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
690
            raise tests.KnownFailure(
 
691
                'pycurl hangs if the server send back garbage')
 
692
        super(TestInvalidStatusServer, self).test_http_has()
 
693
 
 
694
    def test_http_get(self):
 
695
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
696
            raise tests.KnownFailure(
 
697
                'pycurl hangs if the server send back garbage')
 
698
        super(TestInvalidStatusServer, self).test_http_get()
 
699
 
682
700
 
683
701
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
684
702
    """Whatever request comes in, returns a bad protocol version"""
700
718
    _req_handler_class = BadProtocolRequestHandler
701
719
 
702
720
    def setUp(self):
703
 
        if self._testing_pycurl():
 
721
        if pycurl_present and self._transport == PyCurlTransport:
704
722
            raise tests.TestNotApplicable(
705
723
                "pycurl doesn't check the protocol version")
706
724
        super(TestBadProtocolServer, self).setUp()
707
725
 
708
726
    def test_http_has(self):
709
 
        t = self.get_readonly_transport()
 
727
        server = self.get_readonly_server()
 
728
        t = self._transport(server.get_url())
710
729
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
711
730
 
712
731
    def test_http_get(self):
713
 
        t = self.get_readonly_transport()
 
732
        server = self.get_readonly_server()
 
733
        t = self._transport(server.get_url())
714
734
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
715
735
 
716
736
 
730
750
    _req_handler_class = ForbiddenRequestHandler
731
751
 
732
752
    def test_http_has(self):
733
 
        t = self.get_readonly_transport()
 
753
        server = self.get_readonly_server()
 
754
        t = self._transport(server.get_url())
734
755
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
735
756
 
736
757
    def test_http_get(self):
737
 
        t = self.get_readonly_transport()
 
758
        server = self.get_readonly_server()
 
759
        t = self._transport(server.get_url())
738
760
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
739
761
 
740
762
 
746
768
        self.assertEqual(None, server.host)
747
769
        self.assertEqual(None, server.port)
748
770
 
749
 
    def test_setUp_and_stop(self):
 
771
    def test_setUp_and_tearDown(self):
750
772
        server = RecordingServer(expect_body_tail=None)
751
 
        server.start_server()
 
773
        server.setUp()
752
774
        try:
753
775
            self.assertNotEqual(None, server.host)
754
776
            self.assertNotEqual(None, server.port)
755
777
        finally:
756
 
            server.stop_server()
 
778
            server.tearDown()
757
779
        self.assertEqual(None, server.host)
758
780
        self.assertEqual(None, server.port)
759
781
 
779
801
        self.build_tree_contents([('a', '0123456789')],)
780
802
 
781
803
    def test_readv(self):
782
 
        t = self.get_readonly_transport()
 
804
        server = self.get_readonly_server()
 
805
        t = self._transport(server.get_url())
783
806
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
784
807
        self.assertEqual(l[0], (0, '0'))
785
808
        self.assertEqual(l[1], (1, '1'))
787
810
        self.assertEqual(l[3], (9, '9'))
788
811
 
789
812
    def test_readv_out_of_order(self):
790
 
        t = self.get_readonly_transport()
 
813
        server = self.get_readonly_server()
 
814
        t = self._transport(server.get_url())
791
815
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
792
816
        self.assertEqual(l[0], (1, '1'))
793
817
        self.assertEqual(l[1], (9, '9'))
795
819
        self.assertEqual(l[3], (3, '34'))
796
820
 
797
821
    def test_readv_invalid_ranges(self):
798
 
        t = self.get_readonly_transport()
 
822
        server = self.get_readonly_server()
 
823
        t = self._transport(server.get_url())
799
824
 
800
825
        # This is intentionally reading off the end of the file
801
826
        # since we are sure that it cannot get there
809
834
 
810
835
    def test_readv_multiple_get_requests(self):
811
836
        server = self.get_readonly_server()
812
 
        t = self.get_readonly_transport()
 
837
        t = self._transport(server.get_url())
813
838
        # force transport to issue multiple requests
814
839
        t._max_readv_combine = 1
815
840
        t._max_get_ranges = 1
823
848
 
824
849
    def test_readv_get_max_size(self):
825
850
        server = self.get_readonly_server()
826
 
        t = self.get_readonly_transport()
 
851
        t = self._transport(server.get_url())
827
852
        # force transport to issue multiple requests by limiting the number of
828
853
        # bytes by request. Note that this apply to coalesced offsets only, a
829
854
        # single range will keep its size even if bigger than the limit.
838
863
 
839
864
    def test_complete_readv_leave_pipe_clean(self):
840
865
        server = self.get_readonly_server()
841
 
        t = self.get_readonly_transport()
 
866
        t = self._transport(server.get_url())
842
867
        # force transport to issue multiple requests
843
868
        t._get_max_size = 2
844
869
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
849
874
 
850
875
    def test_incomplete_readv_leave_pipe_clean(self):
851
876
        server = self.get_readonly_server()
852
 
        t = self.get_readonly_transport()
 
877
        t = self._transport(server.get_url())
853
878
        # force transport to issue multiple requests
854
879
        t._get_max_size = 2
855
880
        # Don't collapse readv results into a list so that we leave unread
1005
1030
 
1006
1031
    def test_readv_with_short_reads(self):
1007
1032
        server = self.get_readonly_server()
1008
 
        t = self.get_readonly_transport()
 
1033
        t = self._transport(server.get_url())
1009
1034
        # Force separate ranges for each offset
1010
1035
        t._bytes_to_read_before_seek = 0
1011
1036
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1062
1087
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1063
1088
                                      protocol_version=self._protocol_version)
1064
1089
 
 
1090
    def get_transport(self):
 
1091
        return self._transport(self.get_readonly_server().get_url())
 
1092
 
1065
1093
    def setUp(self):
1066
1094
        http_utils.TestCaseWithWebserver.setUp(self)
1067
1095
        # We need to manipulate ranges that correspond to real chunks in the
1071
1099
        self.build_tree_contents([('a', content)],)
1072
1100
 
1073
1101
    def test_few_ranges(self):
1074
 
        t = self.get_readonly_transport()
 
1102
        t = self.get_transport()
1075
1103
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
1104
        self.assertEqual(l[0], (0, '0000'))
1077
1105
        self.assertEqual(l[1], (1024, '0001'))
1078
1106
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1079
1107
 
1080
1108
    def test_more_ranges(self):
1081
 
        t = self.get_readonly_transport()
 
1109
        t = self.get_transport()
1082
1110
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
1111
        self.assertEqual(l[0], (0, '0000'))
1084
1112
        self.assertEqual(l[1], (1024, '0001'))
1098
1126
    def setUp(self):
1099
1127
        tests.TestCase.setUp(self)
1100
1128
        self._old_env = {}
1101
 
        self.addCleanup(self._restore_env)
 
1129
 
 
1130
    def tearDown(self):
 
1131
        self._restore_env()
 
1132
        tests.TestCase.tearDown(self)
1102
1133
 
1103
1134
    def _install_env(self, env):
1104
1135
        for name, value in env.iteritems():
1135
1166
    """
1136
1167
 
1137
1168
    # FIXME: We don't have an https server available, so we don't
1138
 
    # test https connections. --vila toolongago
 
1169
    # test https connections.
1139
1170
 
1140
1171
    def setUp(self):
1141
1172
        super(TestProxyHttpServer, self).setUp()
1142
 
        self.transport_secondary_server = http_utils.ProxyServer
1143
1173
        self.build_tree_contents([('foo', 'contents of foo\n'),
1144
1174
                                  ('foo-proxied', 'proxied contents of foo\n')])
1145
1175
        # Let's setup some attributes for tests
1146
 
        server = self.get_readonly_server()
1147
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1176
        self.server = self.get_readonly_server()
 
1177
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1148
1178
        if self._testing_pycurl():
1149
1179
            # Oh my ! pycurl does not check for the port as part of
1150
1180
            # no_proxy :-( So we just test the host part
1151
 
            self.no_proxy_host = server.host
 
1181
            self.no_proxy_host = 'localhost'
1152
1182
        else:
1153
 
            self.no_proxy_host = self.server_host_port
 
1183
            self.no_proxy_host = self.proxy_address
1154
1184
        # The secondary server is the proxy
1155
 
        self.proxy_url = self.get_secondary_url()
 
1185
        self.proxy = self.get_secondary_server()
 
1186
        self.proxy_url = self.proxy.get_url()
1156
1187
        self._old_env = {}
1157
1188
 
1158
1189
    def _testing_pycurl(self):
1159
 
        # TODO: This is duplicated for lots of the classes in this file
1160
 
        return (features.pycurl.available()
1161
 
                and self._transport == PyCurlTransport)
 
1190
        return pycurl_present and self._transport == PyCurlTransport
 
1191
 
 
1192
    def create_transport_secondary_server(self):
 
1193
        """Creates an http server that will serve files with
 
1194
        '-proxied' appended to their names.
 
1195
        """
 
1196
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
1162
1197
 
1163
1198
    def _install_env(self, env):
1164
1199
        for name, value in env.iteritems():
1170
1205
 
1171
1206
    def proxied_in_env(self, env):
1172
1207
        self._install_env(env)
1173
 
        t = self.get_readonly_transport()
 
1208
        url = self.server.get_url()
 
1209
        t = self._transport(url)
1174
1210
        try:
1175
1211
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1176
1212
        finally:
1178
1214
 
1179
1215
    def not_proxied_in_env(self, env):
1180
1216
        self._install_env(env)
1181
 
        t = self.get_readonly_transport()
 
1217
        url = self.server.get_url()
 
1218
        t = self._transport(url)
1182
1219
        try:
1183
1220
            self.assertEqual('contents of foo\n', t.get('foo').read())
1184
1221
        finally:
1226
1263
            # pycurl *ignores* invalid proxy env variables. If that ever change
1227
1264
            # in the future, this test will fail indicating that pycurl do not
1228
1265
            # ignore anymore such variables.
1229
 
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
 
1266
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1230
1267
        else:
1231
1268
            self.assertRaises(errors.InvalidURL,
1232
1269
                              self.proxied_in_env,
1233
 
                              {'http_proxy': self.server_host_port})
 
1270
                              {'http_proxy': self.proxy_address})
1234
1271
 
1235
1272
 
1236
1273
class TestRanges(http_utils.TestCaseWithWebserver):
1239
1276
    def setUp(self):
1240
1277
        http_utils.TestCaseWithWebserver.setUp(self)
1241
1278
        self.build_tree_contents([('a', '0123456789')],)
 
1279
        server = self.get_readonly_server()
 
1280
        self.transport = self._transport(server.get_url())
1242
1281
 
1243
1282
    def create_transport_readonly_server(self):
1244
1283
        return http_server.HttpServer(protocol_version=self._protocol_version)
1245
1284
 
1246
1285
    def _file_contents(self, relpath, ranges):
1247
 
        t = self.get_readonly_transport()
1248
1286
        offsets = [ (start, end - start + 1) for start, end in ranges]
1249
 
        coalesce = t._coalesce_offsets
 
1287
        coalesce = self.transport._coalesce_offsets
1250
1288
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1251
 
        code, data = t._get(relpath, coalesced)
 
1289
        code, data = self.transport._get(relpath, coalesced)
1252
1290
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1253
1291
        for start, end in ranges:
1254
1292
            data.seek(start)
1255
1293
            yield data.read(end - start + 1)
1256
1294
 
1257
1295
    def _file_tail(self, relpath, tail_amount):
1258
 
        t = self.get_readonly_transport()
1259
 
        code, data = t._get(relpath, [], tail_amount)
 
1296
        code, data = self.transport._get(relpath, [], tail_amount)
1260
1297
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1261
1298
        data.seek(-tail_amount, 2)
1262
1299
        return data.read(tail_amount)
1281
1318
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1282
1319
    """Test redirection between http servers."""
1283
1320
 
 
1321
    def create_transport_secondary_server(self):
 
1322
        """Create the secondary server redirecting to the primary server"""
 
1323
        new = self.get_readonly_server()
 
1324
 
 
1325
        redirecting = http_utils.HTTPServerRedirecting(
 
1326
            protocol_version=self._protocol_version)
 
1327
        redirecting.redirect_to(new.host, new.port)
 
1328
        return redirecting
 
1329
 
1284
1330
    def setUp(self):
1285
1331
        super(TestHTTPRedirections, self).setUp()
1286
1332
        self.build_tree_contents([('a', '0123456789'),
1287
1333
                                  ('bundle',
1288
1334
                                  '# Bazaar revision bundle v0.9\n#\n')
1289
1335
                                  ],)
 
1336
        # The requests to the old server will be redirected to the new server
 
1337
        self.old_transport = self._transport(self.old_server.get_url())
1290
1338
 
1291
1339
    def test_redirected(self):
1292
 
        self.assertRaises(errors.RedirectRequested,
1293
 
                          self.get_old_transport().get, 'a')
1294
 
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
 
1340
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1341
        t = self._transport(self.new_server.get_url())
 
1342
        self.assertEqual('0123456789', t.get('a').read())
 
1343
 
 
1344
    def test_read_redirected_bundle_from_url(self):
 
1345
        from bzrlib.bundle import read_bundle_from_url
 
1346
        url = self.old_transport.abspath('bundle')
 
1347
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
 
1348
                read_bundle_from_url, url)
 
1349
        # If read_bundle_from_url was successful we get an empty bundle
 
1350
        self.assertEqual([], bundle.revisions)
1295
1351
 
1296
1352
 
1297
1353
class RedirectedRequest(_urllib2_wrappers.Request):
1310
1366
        self.follow_redirections = True
1311
1367
 
1312
1368
 
1313
 
def install_redirected_request(test):
1314
 
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1315
 
 
1316
 
 
1317
 
def cleanup_http_redirection_connections(test):
1318
 
    # Some sockets are opened but never seen by _urllib, so we trap them at
1319
 
    # the _urllib2_wrappers level to be able to clean them up.
1320
 
    def socket_disconnect(sock):
1321
 
        try:
1322
 
            sock.shutdown(socket.SHUT_RDWR)
1323
 
            sock.close()
1324
 
        except socket.error:
1325
 
            pass
1326
 
    def connect(connection):
1327
 
        test.http_connect_orig(connection)
1328
 
        test.addCleanup(socket_disconnect, connection.sock)
1329
 
    test.http_connect_orig = test.overrideAttr(
1330
 
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1331
 
    def connect(connection):
1332
 
        test.https_connect_orig(connection)
1333
 
        test.addCleanup(socket_disconnect, connection.sock)
1334
 
    test.https_connect_orig = test.overrideAttr(
1335
 
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1336
 
 
1337
 
 
1338
1369
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1339
1370
    """Test redirections.
1340
1371
 
1350
1381
    """
1351
1382
 
1352
1383
    def setUp(self):
1353
 
        if (features.pycurl.available()
1354
 
            and self._transport == PyCurlTransport):
 
1384
        if pycurl_present and self._transport == PyCurlTransport:
1355
1385
            raise tests.TestNotApplicable(
1356
 
                "pycurl doesn't redirect silently anymore")
 
1386
                "pycurl doesn't redirect silently annymore")
1357
1387
        super(TestHTTPSilentRedirections, self).setUp()
1358
 
        install_redirected_request(self)
1359
 
        cleanup_http_redirection_connections(self)
 
1388
        self.setup_redirected_request()
 
1389
        self.addCleanup(self.cleanup_redirected_request)
1360
1390
        self.build_tree_contents([('a','a'),
1361
1391
                                  ('1/',),
1362
1392
                                  ('1/a', 'redirected once'),
1370
1400
                                  ('5/a', 'redirected 5 times'),
1371
1401
                                  ],)
1372
1402
 
 
1403
        self.old_transport = self._transport(self.old_server.get_url())
 
1404
 
 
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
    def create_transport_secondary_server(self):
 
1413
        """Create the secondary server, redirections are defined in the tests"""
 
1414
        return http_utils.HTTPServerRedirecting(
 
1415
            protocol_version=self._protocol_version)
 
1416
 
1373
1417
    def test_one_redirection(self):
1374
 
        t = self.get_old_transport()
1375
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1418
        t = self.old_transport
 
1419
 
 
1420
        req = RedirectedRequest('GET', t.abspath('a'))
 
1421
        req.follow_redirections = True
1376
1422
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1377
1423
                                       self.new_server.port)
1378
1424
        self.old_server.redirections = \
1379
1425
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1380
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1426
        self.assertEquals('redirected once',t._perform(req).read())
1381
1427
 
1382
1428
    def test_five_redirections(self):
1383
 
        t = self.get_old_transport()
1384
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1429
        t = self.old_transport
 
1430
 
 
1431
        req = RedirectedRequest('GET', t.abspath('a'))
 
1432
        req.follow_redirections = True
1385
1433
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1386
1434
                                       self.old_server.port)
1387
1435
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1393
1441
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1394
1442
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1395
1443
            ]
1396
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1444
        self.assertEquals('redirected 5 times',t._perform(req).read())
1397
1445
 
1398
1446
 
1399
1447
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1402
1450
    def setUp(self):
1403
1451
        super(TestDoCatchRedirections, self).setUp()
1404
1452
        self.build_tree_contents([('a', '0123456789'),],)
1405
 
        cleanup_http_redirection_connections(self)
1406
 
 
1407
 
        self.old_transport = self.get_old_transport()
1408
 
 
1409
 
    def get_a(self, t):
1410
 
        return t.get('a')
 
1453
 
 
1454
        self.old_transport = self._transport(self.old_server.get_url())
 
1455
 
 
1456
    def get_a(self, transport):
 
1457
        return transport.get('a')
1411
1458
 
1412
1459
    def test_no_redirection(self):
1413
 
        t = self.get_new_transport()
 
1460
        t = self._transport(self.new_server.get_url())
1414
1461
 
1415
1462
        # We use None for redirected so that we fail if redirected
1416
 
        self.assertEqual('0123456789',
1417
 
                         transport.do_catching_redirections(
 
1463
        self.assertEquals('0123456789',
 
1464
                          transport.do_catching_redirections(
1418
1465
                self.get_a, t, None).read())
1419
1466
 
1420
1467
    def test_one_redirection(self):
1421
1468
        self.redirections = 0
1422
1469
 
1423
 
        def redirected(t, exception, redirection_notice):
 
1470
        def redirected(transport, exception, redirection_notice):
1424
1471
            self.redirections += 1
1425
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1426
 
            return redirected_t
 
1472
            dir, file = urlutils.split(exception.target)
 
1473
            return self._transport(dir)
1427
1474
 
1428
 
        self.assertEqual('0123456789',
1429
 
                         transport.do_catching_redirections(
 
1475
        self.assertEquals('0123456789',
 
1476
                          transport.do_catching_redirections(
1430
1477
                self.get_a, self.old_transport, redirected).read())
1431
 
        self.assertEqual(1, self.redirections)
 
1478
        self.assertEquals(1, self.redirections)
1432
1479
 
1433
1480
    def test_redirection_loop(self):
1434
1481
 
1459
1506
                                  ('b', 'contents of b\n'),])
1460
1507
 
1461
1508
    def create_transport_readonly_server(self):
1462
 
        server = self._auth_server(protocol_version=self._protocol_version)
1463
 
        server._url_protocol = self._url_protocol
1464
 
        return server
 
1509
        return self._auth_server(protocol_version=self._protocol_version)
1465
1510
 
1466
1511
    def _testing_pycurl(self):
1467
 
        # TODO: This is duplicated for lots of the classes in this file
1468
 
        return (features.pycurl.available()
1469
 
                and self._transport == PyCurlTransport)
 
1512
        return pycurl_present and self._transport == PyCurlTransport
1470
1513
 
1471
1514
    def get_user_url(self, user, password):
1472
1515
        """Build an url embedding user and password"""
1480
1523
        return url
1481
1524
 
1482
1525
    def get_user_transport(self, user, password):
1483
 
        t = transport.get_transport(self.get_user_url(user, password))
1484
 
        return t
 
1526
        return self._transport(self.get_user_url(user, password))
1485
1527
 
1486
1528
    def test_no_user(self):
1487
1529
        self.server.add_user('joe', 'foo')
1538
1580
        self.assertEqual('', ui.ui_factory.stdin.readline())
1539
1581
        stderr.seek(0)
1540
1582
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1541
 
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1542
 
        self.assertEqual('', stdout.getvalue())
 
1583
        self.assertEquals(expected_prompt, stderr.read(len(expected_prompt)))
 
1584
        self.assertEquals('', stdout.getvalue())
1543
1585
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1544
1586
                                    stderr.readline())
1545
1587
 
1560
1602
        self.assertEqual('', ui.ui_factory.stdin.readline())
1561
1603
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1562
1604
                                    stderr.getvalue())
1563
 
        self.assertEqual('', stdout.getvalue())
 
1605
        self.assertEquals('', stdout.getvalue())
1564
1606
        # And we shouldn't prompt again for a different request
1565
1607
        # against the same transport.
1566
1608
        self.assertEqual('contents of b\n',t.get('b').read())
1576
1618
                              % (scheme.upper(),
1577
1619
                                 user, self.server.host, self.server.port,
1578
1620
                                 self.server.auth_realm)))
1579
 
        self.assertEqual(expected_prompt, actual_prompt)
 
1621
        self.assertEquals(expected_prompt, actual_prompt)
1580
1622
 
1581
1623
    def _expected_username_prompt(self, scheme):
1582
1624
        return (self._username_prompt_prefix
1596
1638
        self.server.add_user(user, password)
1597
1639
        t = self.get_user_transport(user, None)
1598
1640
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1599
 
                                            stderr=tests.StringIOWrapper())
 
1641
                                            stdout=tests.StringIOWrapper())
1600
1642
        # Create a minimal config file with the right password
1601
1643
        conf = config.AuthenticationConfig()
1602
1644
        conf._get_config().update(
1672
1714
 
1673
1715
    def get_user_transport(self, user, password):
1674
1716
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1675
 
        return TestAuth.get_user_transport(self, user, password)
 
1717
        return self._transport(self.server.get_url())
1676
1718
 
1677
1719
    def _install_env(self, env):
1678
1720
        for name, value in env.iteritems():
1705
1747
        self.readfile = StringIO(socket_read_content)
1706
1748
        self.writefile = StringIO()
1707
1749
        self.writefile.close = lambda: None
1708
 
        self.close = lambda: None
1709
1750
 
1710
1751
    def makefile(self, mode='r', bufsize=None):
1711
1752
        if 'r' in mode:
1721
1762
        # We use the VFS layer as part of HTTP tunnelling tests.
1722
1763
        self._captureVar('BZR_NO_SMART_VFS', None)
1723
1764
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1724
 
        self.http_server = self.get_readonly_server()
1725
1765
 
1726
1766
    def create_transport_readonly_server(self):
1727
 
        server = http_utils.HTTPServerWithSmarts(
 
1767
        return http_utils.HTTPServerWithSmarts(
1728
1768
            protocol_version=self._protocol_version)
1729
 
        server._url_protocol = self._url_protocol
1730
 
        return server
1731
1769
 
1732
1770
    def test_open_bzrdir(self):
1733
1771
        branch = self.make_branch('relpath')
1734
 
        url = self.http_server.get_url() + 'relpath'
 
1772
        http_server = self.get_readonly_server()
 
1773
        url = http_server.get_url() + 'relpath'
1735
1774
        bd = bzrdir.BzrDir.open(url)
1736
 
        self.addCleanup(bd.transport.disconnect)
1737
1775
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1738
1776
 
1739
1777
    def test_bulk_data(self):
1741
1779
        # The 'readv' command in the smart protocol both sends and receives
1742
1780
        # bulk data, so we use that.
1743
1781
        self.build_tree(['data-file'])
1744
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1782
        http_server = self.get_readonly_server()
 
1783
        http_transport = self._transport(http_server.get_url())
1745
1784
        medium = http_transport.get_smart_medium()
1746
1785
        # Since we provide the medium, the url below will be mostly ignored
1747
1786
        # during the test, as long as the path is '/'.
1755
1794
        post_body = 'hello\n'
1756
1795
        expected_reply_body = 'ok\x012\n'
1757
1796
 
1758
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1797
        http_server = self.get_readonly_server()
 
1798
        http_transport = self._transport(http_server.get_url())
1759
1799
        medium = http_transport.get_smart_medium()
1760
1800
        response = medium.send_http_smart_request(post_body)
1761
1801
        reply_body = response.read()
1762
1802
        self.assertEqual(expected_reply_body, reply_body)
1763
1803
 
1764
1804
    def test_smart_http_server_post_request_handler(self):
1765
 
        httpd = self.http_server.server
 
1805
        httpd = self.get_readonly_server()._get_httpd()
1766
1806
 
1767
1807
        socket = SampleSocket(
1768
1808
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1800
1840
 
1801
1841
    def test_probe_smart_server(self):
1802
1842
        """Test error handling against server refusing smart requests."""
1803
 
        t = self.get_readonly_transport()
 
1843
        server = self.get_readonly_server()
 
1844
        t = self._transport(server.get_url())
1804
1845
        # No need to build a valid smart request here, the server will not even
1805
1846
        # try to interpret it.
1806
1847
        self.assertRaises(errors.SmartProtocolError,
1807
1848
                          t.get_smart_medium().send_http_smart_request,
1808
1849
                          'whatever')
1809
1850
 
1810
 
 
1811
1851
class Test_redirected_to(tests.TestCase):
1812
1852
 
1813
1853
    def test_redirected_to_subdir(self):
1816
1856
                             'http://www.example.com/foo/subdir')
1817
1857
        self.assertIsInstance(r, type(t))
1818
1858
        # Both transports share the some connection
1819
 
        self.assertEqual(t._get_connection(), r._get_connection())
 
1859
        self.assertEquals(t._get_connection(), r._get_connection())
1820
1860
 
1821
1861
    def test_redirected_to_self_with_slash(self):
1822
1862
        t = self._transport('http://www.example.com/foo')
1826
1866
        # Both transports share the some connection (one can argue that we
1827
1867
        # should return the exact same transport here, but that seems
1828
1868
        # overkill).
1829
 
        self.assertEqual(t._get_connection(), r._get_connection())
 
1869
        self.assertEquals(t._get_connection(), r._get_connection())
1830
1870
 
1831
1871
    def test_redirected_to_host(self):
1832
1872
        t = self._transport('http://www.example.com/foo')
1851
1891
        r = t._redirected_to('http://www.example.com/foo',
1852
1892
                             'https://foo.example.com/foo')
1853
1893
        self.assertIsInstance(r, type(t))
1854
 
        self.assertEqual(t._user, r._user)
 
1894
        self.assertEquals(t._user, r._user)
1855
1895
 
1856
1896
 
1857
1897
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1866
1906
    line.
1867
1907
    """
1868
1908
 
1869
 
    def _handle_one_request(self):
 
1909
    def handle_one_request(self):
1870
1910
        tcs = self.server.test_case_server
1871
1911
        requestline = self.rfile.readline()
1872
1912
        headers = self.MessageClass(self.rfile, 0)
1916
1956
        pass
1917
1957
 
1918
1958
 
1919
 
class TestActivityMixin(object):
 
1959
class TestActivity(tests.TestCase):
1920
1960
    """Test socket activity reporting.
1921
1961
 
1922
1962
    We use a special purpose server to control the bytes sent and received and
1926
1966
    def setUp(self):
1927
1967
        tests.TestCase.setUp(self)
1928
1968
        self.server = self._activity_server(self._protocol_version)
1929
 
        self.server.start_server()
 
1969
        self.server.setUp()
1930
1970
        self.activities = {}
1931
1971
        def report_activity(t, bytes, direction):
1932
1972
            count = self.activities.get(direction, 0)
1936
1976
        # We override at class level because constructors may propagate the
1937
1977
        # bound method and render instance overriding ineffective (an
1938
1978
        # alternative would be to define a specific ui factory instead...)
1939
 
        self.overrideAttr(self._transport, '_report_activity', report_activity)
1940
 
        self.addCleanup(self.server.stop_server)
 
1979
        self.orig_report_activity = self._transport._report_activity
 
1980
        self._transport._report_activity = report_activity
 
1981
 
 
1982
    def tearDown(self):
 
1983
        self._transport._report_activity = self.orig_report_activity
 
1984
        self.server.tearDown()
 
1985
        tests.TestCase.tearDown(self)
1941
1986
 
1942
1987
    def get_transport(self):
1943
 
        t = self._transport(self.server.get_url())
1944
 
        # FIXME: Needs cleanup -- vila 20100611
1945
 
        return t
 
1988
        return self._transport(self.server.get_url())
1946
1989
 
1947
1990
    def assertActivitiesMatch(self):
1948
1991
        self.assertEqual(self.server.bytes_read,
2053
2096
'''
2054
2097
        t = self.get_transport()
2055
2098
        # We must send a single line of body bytes, see
2056
 
        # PredefinedRequestHandler._handle_one_request
 
2099
        # PredefinedRequestHandler.handle_one_request
2057
2100
        code, f = t._post('abc def end-of-body\n')
2058
2101
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2059
2102
        self.assertActivitiesMatch()
2060
 
 
2061
 
 
2062
 
class TestActivity(tests.TestCase, TestActivityMixin):
2063
 
 
2064
 
    def setUp(self):
2065
 
        TestActivityMixin.setUp(self)
2066
 
 
2067
 
 
2068
 
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2069
 
 
2070
 
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2071
 
    # ReportingSocket, so we don't need all the parametrization. Since
2072
 
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2073
 
    # test them through their use by the transport than directly (that's a
2074
 
    # bit less clean but far more simpler and effective).
2075
 
    _activity_server = ActivityHTTPServer
2076
 
    _protocol_version = 'HTTP/1.1'
2077
 
 
2078
 
    def setUp(self):
2079
 
        self._transport =_urllib.HttpTransport_urllib
2080
 
        TestActivityMixin.setUp(self)
2081
 
 
2082
 
    def assertActivitiesMatch(self):
2083
 
        # Nothing to check here
2084
 
        pass
2085
 
 
2086
 
 
2087
 
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2088
 
    """Test authentication on the redirected http server."""
2089
 
 
2090
 
    _auth_header = 'Authorization'
2091
 
    _password_prompt_prefix = ''
2092
 
    _username_prompt_prefix = ''
2093
 
    _auth_server = http_utils.HTTPBasicAuthServer
2094
 
    _transport = _urllib.HttpTransport_urllib
2095
 
 
2096
 
    def setUp(self):
2097
 
        super(TestAuthOnRedirected, self).setUp()
2098
 
        self.build_tree_contents([('a','a'),
2099
 
                                  ('1/',),
2100
 
                                  ('1/a', 'redirected once'),
2101
 
                                  ],)
2102
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2103
 
                                       self.new_server.port)
2104
 
        self.old_server.redirections = [
2105
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2106
 
        self.old_transport = self.get_old_transport()
2107
 
        self.new_server.add_user('joe', 'foo')
2108
 
        cleanup_http_redirection_connections(self)
2109
 
 
2110
 
    def create_transport_readonly_server(self):
2111
 
        server = self._auth_server(protocol_version=self._protocol_version)
2112
 
        server._url_protocol = self._url_protocol
2113
 
        return server
2114
 
 
2115
 
    def get_a(self, t):
2116
 
        return t.get('a')
2117
 
 
2118
 
    def test_auth_on_redirected_via_do_catching_redirections(self):
2119
 
        self.redirections = 0
2120
 
 
2121
 
        def redirected(t, exception, redirection_notice):
2122
 
            self.redirections += 1
2123
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2124
 
            self.addCleanup(redirected_t.disconnect)
2125
 
            return redirected_t
2126
 
 
2127
 
        stdout = tests.StringIOWrapper()
2128
 
        stderr = tests.StringIOWrapper()
2129
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2130
 
                                            stdout=stdout, stderr=stderr)
2131
 
        self.assertEqual('redirected once',
2132
 
                         transport.do_catching_redirections(
2133
 
                self.get_a, self.old_transport, redirected).read())
2134
 
        self.assertEqual(1, self.redirections)
2135
 
        # stdin should be empty
2136
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2137
 
        # stdout should be empty, stderr will contains the prompts
2138
 
        self.assertEqual('', stdout.getvalue())
2139
 
 
2140
 
    def test_auth_on_redirected_via_following_redirections(self):
2141
 
        self.new_server.add_user('joe', 'foo')
2142
 
        stdout = tests.StringIOWrapper()
2143
 
        stderr = tests.StringIOWrapper()
2144
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2145
 
                                            stdout=stdout, stderr=stderr)
2146
 
        t = self.old_transport
2147
 
        req = RedirectedRequest('GET', t.abspath('a'))
2148
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2149
 
                                       self.new_server.port)
2150
 
        self.old_server.redirections = [
2151
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2152
 
        self.assertEqual('redirected once', t._perform(req).read())
2153
 
        # stdin should be empty
2154
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2155
 
        # stdout should be empty, stderr will contains the prompts
2156
 
        self.assertEqual('', stdout.getvalue())
2157
 
 
2158