~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Martin von Gagern
  • Date: 2010-04-20 08:47:38 UTC
  • mfrom: (5167 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5195.
  • Revision ID: martin.vgagern@gmx.net-20100420084738-ygymnqmdllzrhpfn
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
51
    features,
49
52
    http_server,
50
53
    http_utils,
51
 
    test_server,
52
54
    )
53
55
from bzrlib.transport import (
54
56
    http,
78
80
    transport_scenarios = [
79
81
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
80
82
                        _server=http_server.HttpServer_urllib,
81
 
                        _url_protocol='http+urllib',)),
 
83
                        _qualified_prefix='http+urllib',)),
82
84
        ]
83
85
    if features.pycurl.available():
84
86
        transport_scenarios.append(
85
87
            ('pycurl', dict(_transport=PyCurlTransport,
86
88
                            _server=http_server.HttpServer_PyCurl,
87
 
                            _url_protocol='http+pycurl',)))
 
89
                            _qualified_prefix='http+pycurl',)))
88
90
    tests.multiply_tests(t_tests, transport_scenarios, result)
89
91
 
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
92
    # each implementation tested with each HTTP version
103
93
    tp_tests, remaining_tests = tests.split_suite_by_condition(
104
94
        remaining_tests, tests.condition_isinstance((
113
103
                TestRanges,
114
104
                TestSpecificRequestHandler,
115
105
                )))
 
106
    protocol_scenarios = [
 
107
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
 
108
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
109
            ]
116
110
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
117
111
                                            protocol_scenarios)
118
112
    tests.multiply_tests(tp_tests, tp_scenarios, result)
229
223
        self._sock.bind(('127.0.0.1', 0))
230
224
        self.host, self.port = self._sock.getsockname()
231
225
        self._ready = threading.Event()
232
 
        self._thread = test_server.ThreadWithException(
233
 
            event=self._ready, target=self._accept_read_and_reply)
 
226
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
227
        self._thread.setDaemon(True)
234
228
        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()
 
229
        self._ready.wait(5)
238
230
 
239
231
    def _accept_read_and_reply(self):
240
232
        self._sock.listen(1)
241
233
        self._ready.set()
242
 
        conn, address = self._sock.accept()
243
 
        if self._expect_body_tail is not None:
 
234
        self._sock.settimeout(5)
 
235
        try:
 
236
            conn, address = self._sock.accept()
 
237
            # On win32, the accepted connection will be non-blocking to start
 
238
            # with because we're using settimeout.
 
239
            conn.setblocking(True)
244
240
            while not self.received_bytes.endswith(self._expect_body_tail):
245
241
                self.received_bytes += conn.recv(4096)
246
242
            conn.sendall('HTTP/1.1 200 OK\r\n')
247
 
        try:
 
243
        except socket.timeout:
 
244
            # Make sure the client isn't stuck waiting for us to e.g. accept.
248
245
            self._sock.close()
249
246
        except socket.error:
250
247
            # The client may have already closed the socket.
252
249
 
253
250
    def stop_server(self):
254
251
        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()
 
252
            self._sock.close()
259
253
        except socket.error:
260
254
            # We might have already closed it.  We don't care.
261
255
            pass
262
256
        self.host = None
263
257
        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
258
 
268
259
 
269
260
class TestAuthHeader(tests.TestCase):
313
304
 
314
305
            protocol_version = 'HTTP/0.1'
315
306
 
316
 
        self.assertRaises(httplib.UnknownProtocol,
317
 
                          http_server.HttpServer, BogusRequestHandler)
 
307
        server = http_server.HttpServer(BogusRequestHandler)
 
308
        try:
 
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
310
        except:
 
311
            server.stop_server()
 
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
318
313
 
319
314
    def test_force_invalid_protocol(self):
320
 
        self.assertRaises(httplib.UnknownProtocol,
321
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
316
        try:
 
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
318
        except:
 
319
            server.stop_server()
 
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
322
321
 
323
322
    def test_server_start_and_stop(self):
324
323
        server = http_server.HttpServer()
325
 
        self.addCleanup(server.stop_server)
326
324
        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)
 
325
        try:
 
326
            self.assertTrue(server._http_running)
 
327
        finally:
 
328
            server.stop_server()
 
329
        self.assertFalse(server._http_running)
330
330
 
331
331
    def test_create_http_server_one_zero(self):
332
332
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
335
335
 
336
336
        server = http_server.HttpServer(RequestHandlerOneZero)
337
337
        self.start_server(server)
338
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
338
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
339
339
 
340
340
    def test_create_http_server_one_one(self):
341
341
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
344
344
 
345
345
        server = http_server.HttpServer(RequestHandlerOneOne)
346
346
        self.start_server(server)
347
 
        self.assertIsInstance(server.server,
 
347
        self.assertIsInstance(server._httpd,
348
348
                              http_server.TestingThreadingHTTPServer)
349
349
 
350
350
    def test_create_http_server_force_one_one(self):
355
355
        server = http_server.HttpServer(RequestHandlerOneZero,
356
356
                                        protocol_version='HTTP/1.1')
357
357
        self.start_server(server)
358
 
        self.assertIsInstance(server.server,
 
358
        self.assertIsInstance(server._httpd,
359
359
                              http_server.TestingThreadingHTTPServer)
360
360
 
361
361
    def test_create_http_server_force_one_zero(self):
366
366
        server = http_server.HttpServer(RequestHandlerOneOne,
367
367
                                        protocol_version='HTTP/1.0')
368
368
        self.start_server(server)
369
 
        self.assertIsInstance(server.server,
 
369
        self.assertIsInstance(server._httpd,
370
370
                              http_server.TestingHTTPServer)
371
371
 
372
372
 
431
431
        server.start_server()
432
432
        try:
433
433
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
435
        finally:
436
436
            server.stop_server()
437
437
 
482
482
 
483
483
    def test_http_has(self):
484
484
        server = self.get_readonly_server()
485
 
        t = self.get_readonly_transport()
 
485
        t = self._transport(server.get_url())
486
486
        self.assertEqual(t.has('foo/bar'), True)
487
487
        self.assertEqual(len(server.logs), 1)
488
488
        self.assertContainsRe(server.logs[0],
490
490
 
491
491
    def test_http_has_not_found(self):
492
492
        server = self.get_readonly_server()
493
 
        t = self.get_readonly_transport()
 
493
        t = self._transport(server.get_url())
494
494
        self.assertEqual(t.has('not-found'), False)
495
495
        self.assertContainsRe(server.logs[1],
496
496
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
497
497
 
498
498
    def test_http_get(self):
499
499
        server = self.get_readonly_server()
500
 
        t = self.get_readonly_transport()
 
500
        t = self._transport(server.get_url())
501
501
        fp = t.get('foo/bar')
502
502
        self.assertEqualDiff(
503
503
            fp.read(),
526
526
    """Test registrations of various http implementations"""
527
527
 
528
528
    def test_http_registered(self):
529
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
529
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
530
530
        self.assertIsInstance(t, transport.Transport)
531
531
        self.assertIsInstance(t, self._transport)
532
532
 
535
535
 
536
536
    def test_post_body_is_received(self):
537
537
        server = RecordingServer(expect_body_tail='end-of-body',
538
 
                                 scheme=self._url_protocol)
 
538
            scheme=self._qualified_prefix)
539
539
        self.start_server(server)
540
540
        url = server.get_url()
541
 
        # FIXME: needs a cleanup -- vila 20100611
542
 
        http_transport = transport.get_transport(url)
 
541
        http_transport = self._transport(url)
543
542
        code, response = http_transport._post('abc def end-of-body')
544
543
        self.assertTrue(
545
544
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
589
588
    _req_handler_class = http_server.TestingHTTPRequestHandler
590
589
 
591
590
    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
 
591
        return http_server.HttpServer(self._req_handler_class,
 
592
                                      protocol_version=self._protocol_version)
596
593
 
597
594
    def _testing_pycurl(self):
598
595
        # TODO: This is duplicated for lots of the classes in this file
603
600
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
604
601
    """Whatever request comes in, close the connection"""
605
602
 
606
 
    def _handle_one_request(self):
 
603
    def handle_one_request(self):
607
604
        """Handle a single HTTP request, by abruptly closing the connection"""
608
605
        self.close_connection = 1
609
606
 
614
611
    _req_handler_class = WallRequestHandler
615
612
 
616
613
    def test_http_has(self):
617
 
        t = self.get_readonly_transport()
 
614
        server = self.get_readonly_server()
 
615
        t = self._transport(server.get_url())
618
616
        # Unfortunately httplib (see HTTPResponse._read_status
619
617
        # for details) make no distinction between a closed
620
618
        # socket and badly formatted status line, so we can't
626
624
                          t.has, 'foo/bar')
627
625
 
628
626
    def test_http_get(self):
629
 
        t = self.get_readonly_transport()
 
627
        server = self.get_readonly_server()
 
628
        t = self._transport(server.get_url())
630
629
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
631
630
                           errors.InvalidHttpResponse),
632
631
                          t.get, 'foo/bar')
649
648
    _req_handler_class = BadStatusRequestHandler
650
649
 
651
650
    def test_http_has(self):
652
 
        t = self.get_readonly_transport()
 
651
        server = self.get_readonly_server()
 
652
        t = self._transport(server.get_url())
653
653
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
654
654
 
655
655
    def test_http_get(self):
656
 
        t = self.get_readonly_transport()
 
656
        server = self.get_readonly_server()
 
657
        t = self._transport(server.get_url())
657
658
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
658
659
 
659
660
 
664
665
        """Fakes handling a single HTTP request, returns a bad status"""
665
666
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
666
667
        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
668
        return False
672
669
 
673
670
 
679
676
 
680
677
    _req_handler_class = InvalidStatusRequestHandler
681
678
 
 
679
    def test_http_has(self):
 
680
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
681
            raise tests.KnownFailure(
 
682
                'pycurl hangs if the server send back garbage')
 
683
        super(TestInvalidStatusServer, self).test_http_has()
 
684
 
 
685
    def test_http_get(self):
 
686
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
687
            raise tests.KnownFailure(
 
688
                'pycurl hangs if the server send back garbage')
 
689
        super(TestInvalidStatusServer, self).test_http_get()
 
690
 
682
691
 
683
692
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
684
693
    """Whatever request comes in, returns a bad protocol version"""
706
715
        super(TestBadProtocolServer, self).setUp()
707
716
 
708
717
    def test_http_has(self):
709
 
        t = self.get_readonly_transport()
 
718
        server = self.get_readonly_server()
 
719
        t = self._transport(server.get_url())
710
720
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
711
721
 
712
722
    def test_http_get(self):
713
 
        t = self.get_readonly_transport()
 
723
        server = self.get_readonly_server()
 
724
        t = self._transport(server.get_url())
714
725
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
715
726
 
716
727
 
730
741
    _req_handler_class = ForbiddenRequestHandler
731
742
 
732
743
    def test_http_has(self):
733
 
        t = self.get_readonly_transport()
 
744
        server = self.get_readonly_server()
 
745
        t = self._transport(server.get_url())
734
746
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
735
747
 
736
748
    def test_http_get(self):
737
 
        t = self.get_readonly_transport()
 
749
        server = self.get_readonly_server()
 
750
        t = self._transport(server.get_url())
738
751
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
739
752
 
740
753
 
779
792
        self.build_tree_contents([('a', '0123456789')],)
780
793
 
781
794
    def test_readv(self):
782
 
        t = self.get_readonly_transport()
 
795
        server = self.get_readonly_server()
 
796
        t = self._transport(server.get_url())
783
797
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
784
798
        self.assertEqual(l[0], (0, '0'))
785
799
        self.assertEqual(l[1], (1, '1'))
787
801
        self.assertEqual(l[3], (9, '9'))
788
802
 
789
803
    def test_readv_out_of_order(self):
790
 
        t = self.get_readonly_transport()
 
804
        server = self.get_readonly_server()
 
805
        t = self._transport(server.get_url())
791
806
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
792
807
        self.assertEqual(l[0], (1, '1'))
793
808
        self.assertEqual(l[1], (9, '9'))
795
810
        self.assertEqual(l[3], (3, '34'))
796
811
 
797
812
    def test_readv_invalid_ranges(self):
798
 
        t = self.get_readonly_transport()
 
813
        server = self.get_readonly_server()
 
814
        t = self._transport(server.get_url())
799
815
 
800
816
        # This is intentionally reading off the end of the file
801
817
        # since we are sure that it cannot get there
809
825
 
810
826
    def test_readv_multiple_get_requests(self):
811
827
        server = self.get_readonly_server()
812
 
        t = self.get_readonly_transport()
 
828
        t = self._transport(server.get_url())
813
829
        # force transport to issue multiple requests
814
830
        t._max_readv_combine = 1
815
831
        t._max_get_ranges = 1
823
839
 
824
840
    def test_readv_get_max_size(self):
825
841
        server = self.get_readonly_server()
826
 
        t = self.get_readonly_transport()
 
842
        t = self._transport(server.get_url())
827
843
        # force transport to issue multiple requests by limiting the number of
828
844
        # bytes by request. Note that this apply to coalesced offsets only, a
829
845
        # single range will keep its size even if bigger than the limit.
838
854
 
839
855
    def test_complete_readv_leave_pipe_clean(self):
840
856
        server = self.get_readonly_server()
841
 
        t = self.get_readonly_transport()
 
857
        t = self._transport(server.get_url())
842
858
        # force transport to issue multiple requests
843
859
        t._get_max_size = 2
844
860
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
849
865
 
850
866
    def test_incomplete_readv_leave_pipe_clean(self):
851
867
        server = self.get_readonly_server()
852
 
        t = self.get_readonly_transport()
 
868
        t = self._transport(server.get_url())
853
869
        # force transport to issue multiple requests
854
870
        t._get_max_size = 2
855
871
        # Don't collapse readv results into a list so that we leave unread
1005
1021
 
1006
1022
    def test_readv_with_short_reads(self):
1007
1023
        server = self.get_readonly_server()
1008
 
        t = self.get_readonly_transport()
 
1024
        t = self._transport(server.get_url())
1009
1025
        # Force separate ranges for each offset
1010
1026
        t._bytes_to_read_before_seek = 0
1011
1027
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1062
1078
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1063
1079
                                      protocol_version=self._protocol_version)
1064
1080
 
 
1081
    def get_transport(self):
 
1082
        return self._transport(self.get_readonly_server().get_url())
 
1083
 
1065
1084
    def setUp(self):
1066
1085
        http_utils.TestCaseWithWebserver.setUp(self)
1067
1086
        # We need to manipulate ranges that correspond to real chunks in the
1071
1090
        self.build_tree_contents([('a', content)],)
1072
1091
 
1073
1092
    def test_few_ranges(self):
1074
 
        t = self.get_readonly_transport()
 
1093
        t = self.get_transport()
1075
1094
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
1095
        self.assertEqual(l[0], (0, '0000'))
1077
1096
        self.assertEqual(l[1], (1024, '0001'))
1078
1097
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1079
1098
 
1080
1099
    def test_more_ranges(self):
1081
 
        t = self.get_readonly_transport()
 
1100
        t = self.get_transport()
1082
1101
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
1102
        self.assertEqual(l[0], (0, '0000'))
1084
1103
        self.assertEqual(l[1], (1024, '0001'))
1098
1117
    def setUp(self):
1099
1118
        tests.TestCase.setUp(self)
1100
1119
        self._old_env = {}
1101
 
        self.addCleanup(self._restore_env)
 
1120
 
 
1121
    def tearDown(self):
 
1122
        self._restore_env()
 
1123
        tests.TestCase.tearDown(self)
1102
1124
 
1103
1125
    def _install_env(self, env):
1104
1126
        for name, value in env.iteritems():
1135
1157
    """
1136
1158
 
1137
1159
    # FIXME: We don't have an https server available, so we don't
1138
 
    # test https connections. --vila toolongago
 
1160
    # test https connections.
1139
1161
 
1140
1162
    def setUp(self):
1141
1163
        super(TestProxyHttpServer, self).setUp()
1142
 
        self.transport_secondary_server = http_utils.ProxyServer
1143
1164
        self.build_tree_contents([('foo', 'contents of foo\n'),
1144
1165
                                  ('foo-proxied', 'proxied contents of foo\n')])
1145
1166
        # Let's setup some attributes for tests
1146
 
        server = self.get_readonly_server()
1147
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1167
        self.server = self.get_readonly_server()
 
1168
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1148
1169
        if self._testing_pycurl():
1149
1170
            # Oh my ! pycurl does not check for the port as part of
1150
1171
            # no_proxy :-( So we just test the host part
1151
 
            self.no_proxy_host = server.host
 
1172
            self.no_proxy_host = self.server.host
1152
1173
        else:
1153
 
            self.no_proxy_host = self.server_host_port
 
1174
            self.no_proxy_host = self.proxy_address
1154
1175
        # The secondary server is the proxy
1155
 
        self.proxy_url = self.get_secondary_url()
 
1176
        self.proxy = self.get_secondary_server()
 
1177
        self.proxy_url = self.proxy.get_url()
1156
1178
        self._old_env = {}
1157
1179
 
1158
1180
    def _testing_pycurl(self):
1160
1182
        return (features.pycurl.available()
1161
1183
                and self._transport == PyCurlTransport)
1162
1184
 
 
1185
    def create_transport_secondary_server(self):
 
1186
        """Creates an http server that will serve files with
 
1187
        '-proxied' appended to their names.
 
1188
        """
 
1189
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
 
1190
 
1163
1191
    def _install_env(self, env):
1164
1192
        for name, value in env.iteritems():
1165
1193
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1170
1198
 
1171
1199
    def proxied_in_env(self, env):
1172
1200
        self._install_env(env)
1173
 
        t = self.get_readonly_transport()
 
1201
        url = self.server.get_url()
 
1202
        t = self._transport(url)
1174
1203
        try:
1175
1204
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1176
1205
        finally:
1178
1207
 
1179
1208
    def not_proxied_in_env(self, env):
1180
1209
        self._install_env(env)
1181
 
        t = self.get_readonly_transport()
 
1210
        url = self.server.get_url()
 
1211
        t = self._transport(url)
1182
1212
        try:
1183
1213
            self.assertEqual('contents of foo\n', t.get('foo').read())
1184
1214
        finally:
1226
1256
            # pycurl *ignores* invalid proxy env variables. If that ever change
1227
1257
            # in the future, this test will fail indicating that pycurl do not
1228
1258
            # ignore anymore such variables.
1229
 
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
 
1259
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1230
1260
        else:
1231
1261
            self.assertRaises(errors.InvalidURL,
1232
1262
                              self.proxied_in_env,
1233
 
                              {'http_proxy': self.server_host_port})
 
1263
                              {'http_proxy': self.proxy_address})
1234
1264
 
1235
1265
 
1236
1266
class TestRanges(http_utils.TestCaseWithWebserver):
1239
1269
    def setUp(self):
1240
1270
        http_utils.TestCaseWithWebserver.setUp(self)
1241
1271
        self.build_tree_contents([('a', '0123456789')],)
 
1272
        server = self.get_readonly_server()
 
1273
        self.transport = self._transport(server.get_url())
1242
1274
 
1243
1275
    def create_transport_readonly_server(self):
1244
1276
        return http_server.HttpServer(protocol_version=self._protocol_version)
1245
1277
 
1246
1278
    def _file_contents(self, relpath, ranges):
1247
 
        t = self.get_readonly_transport()
1248
1279
        offsets = [ (start, end - start + 1) for start, end in ranges]
1249
 
        coalesce = t._coalesce_offsets
 
1280
        coalesce = self.transport._coalesce_offsets
1250
1281
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1251
 
        code, data = t._get(relpath, coalesced)
 
1282
        code, data = self.transport._get(relpath, coalesced)
1252
1283
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1253
1284
        for start, end in ranges:
1254
1285
            data.seek(start)
1255
1286
            yield data.read(end - start + 1)
1256
1287
 
1257
1288
    def _file_tail(self, relpath, tail_amount):
1258
 
        t = self.get_readonly_transport()
1259
 
        code, data = t._get(relpath, [], tail_amount)
 
1289
        code, data = self.transport._get(relpath, [], tail_amount)
1260
1290
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1261
1291
        data.seek(-tail_amount, 2)
1262
1292
        return data.read(tail_amount)
1281
1311
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1282
1312
    """Test redirection between http servers."""
1283
1313
 
 
1314
    def create_transport_secondary_server(self):
 
1315
        """Create the secondary server redirecting to the primary server"""
 
1316
        new = self.get_readonly_server()
 
1317
 
 
1318
        redirecting = http_utils.HTTPServerRedirecting(
 
1319
            protocol_version=self._protocol_version)
 
1320
        redirecting.redirect_to(new.host, new.port)
 
1321
        return redirecting
 
1322
 
1284
1323
    def setUp(self):
1285
1324
        super(TestHTTPRedirections, self).setUp()
1286
1325
        self.build_tree_contents([('a', '0123456789'),
1287
1326
                                  ('bundle',
1288
1327
                                  '# Bazaar revision bundle v0.9\n#\n')
1289
1328
                                  ],)
 
1329
        # The requests to the old server will be redirected to the new server
 
1330
        self.old_transport = self._transport(self.old_server.get_url())
1290
1331
 
1291
1332
    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())
 
1333
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1334
        t = self._transport(self.new_server.get_url())
 
1335
        self.assertEqual('0123456789', t.get('a').read())
 
1336
 
 
1337
    def test_read_redirected_bundle_from_url(self):
 
1338
        from bzrlib.bundle import read_bundle_from_url
 
1339
        url = self.old_transport.abspath('bundle')
 
1340
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
 
1341
                read_bundle_from_url, url)
 
1342
        # If read_bundle_from_url was successful we get an empty bundle
 
1343
        self.assertEqual([], bundle.revisions)
1295
1344
 
1296
1345
 
1297
1346
class RedirectedRequest(_urllib2_wrappers.Request):
1314
1363
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1315
1364
 
1316
1365
 
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
1366
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1339
1367
    """Test redirections.
1340
1368
 
1353
1381
        if (features.pycurl.available()
1354
1382
            and self._transport == PyCurlTransport):
1355
1383
            raise tests.TestNotApplicable(
1356
 
                "pycurl doesn't redirect silently anymore")
 
1384
                "pycurl doesn't redirect silently annymore")
1357
1385
        super(TestHTTPSilentRedirections, self).setUp()
1358
1386
        install_redirected_request(self)
1359
 
        cleanup_http_redirection_connections(self)
1360
1387
        self.build_tree_contents([('a','a'),
1361
1388
                                  ('1/',),
1362
1389
                                  ('1/a', 'redirected once'),
1370
1397
                                  ('5/a', 'redirected 5 times'),
1371
1398
                                  ],)
1372
1399
 
 
1400
        self.old_transport = self._transport(self.old_server.get_url())
 
1401
 
 
1402
    def create_transport_secondary_server(self):
 
1403
        """Create the secondary server, redirections are defined in the tests"""
 
1404
        return http_utils.HTTPServerRedirecting(
 
1405
            protocol_version=self._protocol_version)
 
1406
 
1373
1407
    def test_one_redirection(self):
1374
 
        t = self.get_old_transport()
1375
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1408
        t = self.old_transport
 
1409
 
 
1410
        req = RedirectedRequest('GET', t.abspath('a'))
1376
1411
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1377
1412
                                       self.new_server.port)
1378
1413
        self.old_server.redirections = \
1379
1414
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1380
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1415
        self.assertEqual('redirected once',t._perform(req).read())
1381
1416
 
1382
1417
    def test_five_redirections(self):
1383
 
        t = self.get_old_transport()
1384
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1418
        t = self.old_transport
 
1419
 
 
1420
        req = RedirectedRequest('GET', t.abspath('a'))
1385
1421
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1386
1422
                                       self.old_server.port)
1387
1423
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1393
1429
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1394
1430
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1395
1431
            ]
1396
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1432
        self.assertEqual('redirected 5 times',t._perform(req).read())
1397
1433
 
1398
1434
 
1399
1435
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1402
1438
    def setUp(self):
1403
1439
        super(TestDoCatchRedirections, self).setUp()
1404
1440
        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')
 
1441
 
 
1442
        self.old_transport = self._transport(self.old_server.get_url())
 
1443
 
 
1444
    def get_a(self, transport):
 
1445
        return transport.get('a')
1411
1446
 
1412
1447
    def test_no_redirection(self):
1413
 
        t = self.get_new_transport()
 
1448
        t = self._transport(self.new_server.get_url())
1414
1449
 
1415
1450
        # We use None for redirected so that we fail if redirected
1416
1451
        self.assertEqual('0123456789',
1420
1455
    def test_one_redirection(self):
1421
1456
        self.redirections = 0
1422
1457
 
1423
 
        def redirected(t, exception, redirection_notice):
 
1458
        def redirected(transport, exception, redirection_notice):
1424
1459
            self.redirections += 1
1425
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1426
 
            return redirected_t
 
1460
            dir, file = urlutils.split(exception.target)
 
1461
            return self._transport(dir)
1427
1462
 
1428
1463
        self.assertEqual('0123456789',
1429
1464
                         transport.do_catching_redirections(
1459
1494
                                  ('b', 'contents of b\n'),])
1460
1495
 
1461
1496
    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
 
1497
        return self._auth_server(protocol_version=self._protocol_version)
1465
1498
 
1466
1499
    def _testing_pycurl(self):
1467
1500
        # TODO: This is duplicated for lots of the classes in this file
1480
1513
        return url
1481
1514
 
1482
1515
    def get_user_transport(self, user, password):
1483
 
        t = transport.get_transport(self.get_user_url(user, password))
1484
 
        return t
 
1516
        return self._transport(self.get_user_url(user, password))
1485
1517
 
1486
1518
    def test_no_user(self):
1487
1519
        self.server.add_user('joe', 'foo')
1672
1704
 
1673
1705
    def get_user_transport(self, user, password):
1674
1706
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1675
 
        return TestAuth.get_user_transport(self, user, password)
 
1707
        return self._transport(self.server.get_url())
1676
1708
 
1677
1709
    def _install_env(self, env):
1678
1710
        for name, value in env.iteritems():
1705
1737
        self.readfile = StringIO(socket_read_content)
1706
1738
        self.writefile = StringIO()
1707
1739
        self.writefile.close = lambda: None
1708
 
        self.close = lambda: None
1709
1740
 
1710
1741
    def makefile(self, mode='r', bufsize=None):
1711
1742
        if 'r' in mode:
1721
1752
        # We use the VFS layer as part of HTTP tunnelling tests.
1722
1753
        self._captureVar('BZR_NO_SMART_VFS', None)
1723
1754
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1724
 
        self.http_server = self.get_readonly_server()
1725
1755
 
1726
1756
    def create_transport_readonly_server(self):
1727
 
        server = http_utils.HTTPServerWithSmarts(
 
1757
        return http_utils.HTTPServerWithSmarts(
1728
1758
            protocol_version=self._protocol_version)
1729
 
        server._url_protocol = self._url_protocol
1730
 
        return server
1731
1759
 
1732
1760
    def test_open_bzrdir(self):
1733
1761
        branch = self.make_branch('relpath')
1734
 
        url = self.http_server.get_url() + 'relpath'
 
1762
        http_server = self.get_readonly_server()
 
1763
        url = http_server.get_url() + 'relpath'
1735
1764
        bd = bzrdir.BzrDir.open(url)
1736
 
        self.addCleanup(bd.transport.disconnect)
1737
1765
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1738
1766
 
1739
1767
    def test_bulk_data(self):
1741
1769
        # The 'readv' command in the smart protocol both sends and receives
1742
1770
        # bulk data, so we use that.
1743
1771
        self.build_tree(['data-file'])
1744
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1772
        http_server = self.get_readonly_server()
 
1773
        http_transport = self._transport(http_server.get_url())
1745
1774
        medium = http_transport.get_smart_medium()
1746
1775
        # Since we provide the medium, the url below will be mostly ignored
1747
1776
        # during the test, as long as the path is '/'.
1755
1784
        post_body = 'hello\n'
1756
1785
        expected_reply_body = 'ok\x012\n'
1757
1786
 
1758
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1787
        http_server = self.get_readonly_server()
 
1788
        http_transport = self._transport(http_server.get_url())
1759
1789
        medium = http_transport.get_smart_medium()
1760
1790
        response = medium.send_http_smart_request(post_body)
1761
1791
        reply_body = response.read()
1762
1792
        self.assertEqual(expected_reply_body, reply_body)
1763
1793
 
1764
1794
    def test_smart_http_server_post_request_handler(self):
1765
 
        httpd = self.http_server.server
 
1795
        httpd = self.get_readonly_server()._get_httpd()
1766
1796
 
1767
1797
        socket = SampleSocket(
1768
1798
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1800
1830
 
1801
1831
    def test_probe_smart_server(self):
1802
1832
        """Test error handling against server refusing smart requests."""
1803
 
        t = self.get_readonly_transport()
 
1833
        server = self.get_readonly_server()
 
1834
        t = self._transport(server.get_url())
1804
1835
        # No need to build a valid smart request here, the server will not even
1805
1836
        # try to interpret it.
1806
1837
        self.assertRaises(errors.SmartProtocolError,
1807
1838
                          t.get_smart_medium().send_http_smart_request,
1808
1839
                          'whatever')
1809
1840
 
1810
 
 
1811
1841
class Test_redirected_to(tests.TestCase):
1812
1842
 
1813
1843
    def test_redirected_to_subdir(self):
1866
1896
    line.
1867
1897
    """
1868
1898
 
1869
 
    def _handle_one_request(self):
 
1899
    def handle_one_request(self):
1870
1900
        tcs = self.server.test_case_server
1871
1901
        requestline = self.rfile.readline()
1872
1902
        headers = self.MessageClass(self.rfile, 0)
1936
1966
        # We override at class level because constructors may propagate the
1937
1967
        # bound method and render instance overriding ineffective (an
1938
1968
        # 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)
 
1969
        self.orig_report_activity = self._transport._report_activity
 
1970
        self._transport._report_activity = report_activity
 
1971
 
 
1972
    def tearDown(self):
 
1973
        self._transport._report_activity = self.orig_report_activity
 
1974
        self.server.stop_server()
 
1975
        tests.TestCase.tearDown(self)
1941
1976
 
1942
1977
    def get_transport(self):
1943
 
        t = self._transport(self.server.get_url())
1944
 
        # FIXME: Needs cleanup -- vila 20100611
1945
 
        return t
 
1978
        return self._transport(self.server.get_url())
1946
1979
 
1947
1980
    def assertActivitiesMatch(self):
1948
1981
        self.assertEqual(self.server.bytes_read,
2053
2086
'''
2054
2087
        t = self.get_transport()
2055
2088
        # We must send a single line of body bytes, see
2056
 
        # PredefinedRequestHandler._handle_one_request
 
2089
        # PredefinedRequestHandler.handle_one_request
2057
2090
        code, f = t._post('abc def end-of-body\n')
2058
2091
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2059
2092
        self.assertActivitiesMatch()
2062
2095
class TestActivity(tests.TestCase, TestActivityMixin):
2063
2096
 
2064
2097
    def setUp(self):
2065
 
        TestActivityMixin.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)
2066
2117
 
2067
2118
 
2068
2119
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2069
2120
 
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
2121
    def setUp(self):
2079
 
        self._transport =_urllib.HttpTransport_urllib
2080
 
        TestActivityMixin.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)
2081
2143
 
2082
2144
    def assertActivitiesMatch(self):
2083
2145
        # Nothing to check here
2093
2155
    _auth_server = http_utils.HTTPBasicAuthServer
2094
2156
    _transport = _urllib.HttpTransport_urllib
2095
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
 
2096
2169
    def setUp(self):
2097
2170
        super(TestAuthOnRedirected, self).setUp()
2098
2171
        self.build_tree_contents([('a','a'),
2103
2176
                                       self.new_server.port)
2104
2177
        self.old_server.redirections = [
2105
2178
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2106
 
        self.old_transport = self.get_old_transport()
 
2179
        self.old_transport = self._transport(self.old_server.get_url())
2107
2180
        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')
 
2181
 
 
2182
    def get_a(self, transport):
 
2183
        return transport.get('a')
2117
2184
 
2118
2185
    def test_auth_on_redirected_via_do_catching_redirections(self):
2119
2186
        self.redirections = 0
2120
2187
 
2121
 
        def redirected(t, exception, redirection_notice):
 
2188
        def redirected(transport, exception, redirection_notice):
2122
2189
            self.redirections += 1
2123
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2124
 
            self.addCleanup(redirected_t.disconnect)
2125
 
            return redirected_t
 
2190
            dir, file = urlutils.split(exception.target)
 
2191
            return self._transport(dir)
2126
2192
 
2127
2193
        stdout = tests.StringIOWrapper()
2128
2194
        stderr = tests.StringIOWrapper()
2149
2215
                                       self.new_server.port)
2150
2216
        self.old_server.redirections = [
2151
2217
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2152
 
        self.assertEqual('redirected once', t._perform(req).read())
 
2218
        self.assertEqual('redirected once',t._perform(req).read())
2153
2219
        # stdin should be empty
2154
2220
        self.assertEqual('', ui.ui_factory.stdin.readline())
2155
2221
        # stdout should be empty, stderr will contains the prompts