~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-09-23 09:00:18 UTC
  • mfrom: (5439.1.1 merge-2.2-into-devel)
  • Revision ID: pqm@pqm.ubuntu.com-20100923090018-01aj4ifyzaps50bo
(spiv) Merge lp:bzr/2.2. (Andrew Bennetts)

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
 
    )
50
47
from bzrlib.tests import (
51
48
    features,
52
49
    http_server,
53
50
    http_utils,
 
51
    test_server,
54
52
    )
55
53
from bzrlib.transport import (
56
54
    http,
80
78
    transport_scenarios = [
81
79
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
82
80
                        _server=http_server.HttpServer_urllib,
83
 
                        _qualified_prefix='http+urllib',)),
 
81
                        _url_protocol='http+urllib',)),
84
82
        ]
85
83
    if features.pycurl.available():
86
84
        transport_scenarios.append(
87
85
            ('pycurl', dict(_transport=PyCurlTransport,
88
86
                            _server=http_server.HttpServer_PyCurl,
89
 
                            _qualified_prefix='http+pycurl',)))
 
87
                            _url_protocol='http+pycurl',)))
90
88
    tests.multiply_tests(t_tests, transport_scenarios, result)
91
89
 
92
90
    protocol_scenarios = [
231
229
        self._sock.bind(('127.0.0.1', 0))
232
230
        self.host, self.port = self._sock.getsockname()
233
231
        self._ready = threading.Event()
234
 
        self._thread = threading.Thread(target=self._accept_read_and_reply)
235
 
        self._thread.setDaemon(True)
 
232
        self._thread = test_server.ThreadWithException(
 
233
            event=self._ready, target=self._accept_read_and_reply)
236
234
        self._thread.start()
237
 
        self._ready.wait(5)
 
235
        if 'threads' in tests.selftest_debug_flags:
 
236
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
 
237
        self._ready.wait()
238
238
 
239
239
    def _accept_read_and_reply(self):
240
240
        self._sock.listen(1)
241
241
        self._ready.set()
242
 
        self._sock.settimeout(5)
243
 
        try:
244
 
            conn, address = self._sock.accept()
245
 
            # On win32, the accepted connection will be non-blocking to start
246
 
            # with because we're using settimeout.
247
 
            conn.setblocking(True)
 
242
        conn, address = self._sock.accept()
 
243
        if self._expect_body_tail is not None:
248
244
            while not self.received_bytes.endswith(self._expect_body_tail):
249
245
                self.received_bytes += conn.recv(4096)
250
246
            conn.sendall('HTTP/1.1 200 OK\r\n')
251
 
        except socket.timeout:
252
 
            # Make sure the client isn't stuck waiting for us to e.g. accept.
 
247
        try:
253
248
            self._sock.close()
254
249
        except socket.error:
255
250
            # The client may have already closed the socket.
257
252
 
258
253
    def stop_server(self):
259
254
        try:
260
 
            self._sock.close()
 
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()
261
259
        except socket.error:
262
260
            # We might have already closed it.  We don't care.
263
261
            pass
264
262
        self.host = None
265
263
        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,))
266
267
 
267
268
 
268
269
class TestAuthHeader(tests.TestCase):
312
313
 
313
314
            protocol_version = 'HTTP/0.1'
314
315
 
315
 
        server = http_server.HttpServer(BogusRequestHandler)
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')
 
316
        self.assertRaises(httplib.UnknownProtocol,
 
317
                          http_server.HttpServer, BogusRequestHandler)
321
318
 
322
319
    def test_force_invalid_protocol(self):
323
 
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
324
 
        try:
325
 
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
326
 
        except:
327
 
            server.stop_server()
328
 
            self.fail('HTTP Server creation did not raise UnknownProtocol')
 
320
        self.assertRaises(httplib.UnknownProtocol,
 
321
                          http_server.HttpServer, protocol_version='HTTP/0.1')
329
322
 
330
323
    def test_server_start_and_stop(self):
331
324
        server = http_server.HttpServer()
 
325
        self.addCleanup(server.stop_server)
332
326
        server.start_server()
333
 
        try:
334
 
            self.assertTrue(server._http_running)
335
 
        finally:
336
 
            server.stop_server()
337
 
        self.assertFalse(server._http_running)
 
327
        self.assertTrue(server.server is not None)
 
328
        self.assertTrue(server.server.serving is not None)
 
329
        self.assertTrue(server.server.serving)
338
330
 
339
331
    def test_create_http_server_one_zero(self):
340
332
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
343
335
 
344
336
        server = http_server.HttpServer(RequestHandlerOneZero)
345
337
        self.start_server(server)
346
 
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
 
338
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
347
339
 
348
340
    def test_create_http_server_one_one(self):
349
341
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
352
344
 
353
345
        server = http_server.HttpServer(RequestHandlerOneOne)
354
346
        self.start_server(server)
355
 
        self.assertIsInstance(server._httpd,
 
347
        self.assertIsInstance(server.server,
356
348
                              http_server.TestingThreadingHTTPServer)
357
349
 
358
350
    def test_create_http_server_force_one_one(self):
363
355
        server = http_server.HttpServer(RequestHandlerOneZero,
364
356
                                        protocol_version='HTTP/1.1')
365
357
        self.start_server(server)
366
 
        self.assertIsInstance(server._httpd,
 
358
        self.assertIsInstance(server.server,
367
359
                              http_server.TestingThreadingHTTPServer)
368
360
 
369
361
    def test_create_http_server_force_one_zero(self):
374
366
        server = http_server.HttpServer(RequestHandlerOneOne,
375
367
                                        protocol_version='HTTP/1.0')
376
368
        self.start_server(server)
377
 
        self.assertIsInstance(server._httpd,
 
369
        self.assertIsInstance(server.server,
378
370
                              http_server.TestingHTTPServer)
379
371
 
380
372
 
439
431
        server.start_server()
440
432
        try:
441
433
            url = server.get_url()
442
 
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
 
434
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
443
435
        finally:
444
436
            server.stop_server()
445
437
 
490
482
 
491
483
    def test_http_has(self):
492
484
        server = self.get_readonly_server()
493
 
        t = self._transport(server.get_url())
 
485
        t = self.get_readonly_transport()
494
486
        self.assertEqual(t.has('foo/bar'), True)
495
487
        self.assertEqual(len(server.logs), 1)
496
488
        self.assertContainsRe(server.logs[0],
498
490
 
499
491
    def test_http_has_not_found(self):
500
492
        server = self.get_readonly_server()
501
 
        t = self._transport(server.get_url())
 
493
        t = self.get_readonly_transport()
502
494
        self.assertEqual(t.has('not-found'), False)
503
495
        self.assertContainsRe(server.logs[1],
504
496
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
505
497
 
506
498
    def test_http_get(self):
507
499
        server = self.get_readonly_server()
508
 
        t = self._transport(server.get_url())
 
500
        t = self.get_readonly_transport()
509
501
        fp = t.get('foo/bar')
510
502
        self.assertEqualDiff(
511
503
            fp.read(),
534
526
    """Test registrations of various http implementations"""
535
527
 
536
528
    def test_http_registered(self):
537
 
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
 
529
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
538
530
        self.assertIsInstance(t, transport.Transport)
539
531
        self.assertIsInstance(t, self._transport)
540
532
 
543
535
 
544
536
    def test_post_body_is_received(self):
545
537
        server = RecordingServer(expect_body_tail='end-of-body',
546
 
            scheme=self._qualified_prefix)
 
538
                                 scheme=self._url_protocol)
547
539
        self.start_server(server)
548
540
        url = server.get_url()
549
 
        http_transport = self._transport(url)
 
541
        # FIXME: needs a cleanup -- vila 20100611
 
542
        http_transport = transport.get_transport(url)
550
543
        code, response = http_transport._post('abc def end-of-body')
551
544
        self.assertTrue(
552
545
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
596
589
    _req_handler_class = http_server.TestingHTTPRequestHandler
597
590
 
598
591
    def create_transport_readonly_server(self):
599
 
        return http_server.HttpServer(self._req_handler_class,
600
 
                                      protocol_version=self._protocol_version)
 
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
601
596
 
602
597
    def _testing_pycurl(self):
603
598
        # TODO: This is duplicated for lots of the classes in this file
608
603
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
609
604
    """Whatever request comes in, close the connection"""
610
605
 
611
 
    def handle_one_request(self):
 
606
    def _handle_one_request(self):
612
607
        """Handle a single HTTP request, by abruptly closing the connection"""
613
608
        self.close_connection = 1
614
609
 
619
614
    _req_handler_class = WallRequestHandler
620
615
 
621
616
    def test_http_has(self):
622
 
        server = self.get_readonly_server()
623
 
        t = self._transport(server.get_url())
 
617
        t = self.get_readonly_transport()
624
618
        # Unfortunately httplib (see HTTPResponse._read_status
625
619
        # for details) make no distinction between a closed
626
620
        # socket and badly formatted status line, so we can't
632
626
                          t.has, 'foo/bar')
633
627
 
634
628
    def test_http_get(self):
635
 
        server = self.get_readonly_server()
636
 
        t = self._transport(server.get_url())
 
629
        t = self.get_readonly_transport()
637
630
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
638
631
                           errors.InvalidHttpResponse),
639
632
                          t.get, 'foo/bar')
656
649
    _req_handler_class = BadStatusRequestHandler
657
650
 
658
651
    def test_http_has(self):
659
 
        server = self.get_readonly_server()
660
 
        t = self._transport(server.get_url())
 
652
        t = self.get_readonly_transport()
661
653
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
662
654
 
663
655
    def test_http_get(self):
664
 
        server = self.get_readonly_server()
665
 
        t = self._transport(server.get_url())
 
656
        t = self.get_readonly_transport()
666
657
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
667
658
 
668
659
 
673
664
        """Fakes handling a single HTTP request, returns a bad status"""
674
665
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
675
666
        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
676
671
        return False
677
672
 
678
673
 
684
679
 
685
680
    _req_handler_class = InvalidStatusRequestHandler
686
681
 
687
 
    def test_http_has(self):
688
 
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
689
 
            raise tests.KnownFailure(
690
 
                'pycurl hangs if the server send back garbage')
691
 
        super(TestInvalidStatusServer, self).test_http_has()
692
 
 
693
 
    def test_http_get(self):
694
 
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
695
 
            raise tests.KnownFailure(
696
 
                'pycurl hangs if the server send back garbage')
697
 
        super(TestInvalidStatusServer, self).test_http_get()
698
 
 
699
682
 
700
683
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
701
684
    """Whatever request comes in, returns a bad protocol version"""
723
706
        super(TestBadProtocolServer, self).setUp()
724
707
 
725
708
    def test_http_has(self):
726
 
        server = self.get_readonly_server()
727
 
        t = self._transport(server.get_url())
 
709
        t = self.get_readonly_transport()
728
710
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
729
711
 
730
712
    def test_http_get(self):
731
 
        server = self.get_readonly_server()
732
 
        t = self._transport(server.get_url())
 
713
        t = self.get_readonly_transport()
733
714
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
734
715
 
735
716
 
749
730
    _req_handler_class = ForbiddenRequestHandler
750
731
 
751
732
    def test_http_has(self):
752
 
        server = self.get_readonly_server()
753
 
        t = self._transport(server.get_url())
 
733
        t = self.get_readonly_transport()
754
734
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
755
735
 
756
736
    def test_http_get(self):
757
 
        server = self.get_readonly_server()
758
 
        t = self._transport(server.get_url())
 
737
        t = self.get_readonly_transport()
759
738
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
760
739
 
761
740
 
800
779
        self.build_tree_contents([('a', '0123456789')],)
801
780
 
802
781
    def test_readv(self):
803
 
        server = self.get_readonly_server()
804
 
        t = self._transport(server.get_url())
 
782
        t = self.get_readonly_transport()
805
783
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
806
784
        self.assertEqual(l[0], (0, '0'))
807
785
        self.assertEqual(l[1], (1, '1'))
809
787
        self.assertEqual(l[3], (9, '9'))
810
788
 
811
789
    def test_readv_out_of_order(self):
812
 
        server = self.get_readonly_server()
813
 
        t = self._transport(server.get_url())
 
790
        t = self.get_readonly_transport()
814
791
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
815
792
        self.assertEqual(l[0], (1, '1'))
816
793
        self.assertEqual(l[1], (9, '9'))
818
795
        self.assertEqual(l[3], (3, '34'))
819
796
 
820
797
    def test_readv_invalid_ranges(self):
821
 
        server = self.get_readonly_server()
822
 
        t = self._transport(server.get_url())
 
798
        t = self.get_readonly_transport()
823
799
 
824
800
        # This is intentionally reading off the end of the file
825
801
        # since we are sure that it cannot get there
833
809
 
834
810
    def test_readv_multiple_get_requests(self):
835
811
        server = self.get_readonly_server()
836
 
        t = self._transport(server.get_url())
 
812
        t = self.get_readonly_transport()
837
813
        # force transport to issue multiple requests
838
814
        t._max_readv_combine = 1
839
815
        t._max_get_ranges = 1
847
823
 
848
824
    def test_readv_get_max_size(self):
849
825
        server = self.get_readonly_server()
850
 
        t = self._transport(server.get_url())
 
826
        t = self.get_readonly_transport()
851
827
        # force transport to issue multiple requests by limiting the number of
852
828
        # bytes by request. Note that this apply to coalesced offsets only, a
853
829
        # single range will keep its size even if bigger than the limit.
862
838
 
863
839
    def test_complete_readv_leave_pipe_clean(self):
864
840
        server = self.get_readonly_server()
865
 
        t = self._transport(server.get_url())
 
841
        t = self.get_readonly_transport()
866
842
        # force transport to issue multiple requests
867
843
        t._get_max_size = 2
868
844
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
873
849
 
874
850
    def test_incomplete_readv_leave_pipe_clean(self):
875
851
        server = self.get_readonly_server()
876
 
        t = self._transport(server.get_url())
 
852
        t = self.get_readonly_transport()
877
853
        # force transport to issue multiple requests
878
854
        t._get_max_size = 2
879
855
        # Don't collapse readv results into a list so that we leave unread
1029
1005
 
1030
1006
    def test_readv_with_short_reads(self):
1031
1007
        server = self.get_readonly_server()
1032
 
        t = self._transport(server.get_url())
 
1008
        t = self.get_readonly_transport()
1033
1009
        # Force separate ranges for each offset
1034
1010
        t._bytes_to_read_before_seek = 0
1035
1011
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1086
1062
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1087
1063
                                      protocol_version=self._protocol_version)
1088
1064
 
1089
 
    def get_transport(self):
1090
 
        return self._transport(self.get_readonly_server().get_url())
1091
 
 
1092
1065
    def setUp(self):
1093
1066
        http_utils.TestCaseWithWebserver.setUp(self)
1094
1067
        # We need to manipulate ranges that correspond to real chunks in the
1098
1071
        self.build_tree_contents([('a', content)],)
1099
1072
 
1100
1073
    def test_few_ranges(self):
1101
 
        t = self.get_transport()
 
1074
        t = self.get_readonly_transport()
1102
1075
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1103
1076
        self.assertEqual(l[0], (0, '0000'))
1104
1077
        self.assertEqual(l[1], (1024, '0001'))
1105
1078
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1106
1079
 
1107
1080
    def test_more_ranges(self):
1108
 
        t = self.get_transport()
 
1081
        t = self.get_readonly_transport()
1109
1082
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1110
1083
        self.assertEqual(l[0], (0, '0000'))
1111
1084
        self.assertEqual(l[1], (1024, '0001'))
1125
1098
    def setUp(self):
1126
1099
        tests.TestCase.setUp(self)
1127
1100
        self._old_env = {}
1128
 
 
1129
 
    def tearDown(self):
1130
 
        self._restore_env()
1131
 
        tests.TestCase.tearDown(self)
 
1101
        self.addCleanup(self._restore_env)
1132
1102
 
1133
1103
    def _install_env(self, env):
1134
1104
        for name, value in env.iteritems():
1165
1135
    """
1166
1136
 
1167
1137
    # FIXME: We don't have an https server available, so we don't
1168
 
    # test https connections.
 
1138
    # test https connections. --vila toolongago
1169
1139
 
1170
1140
    def setUp(self):
1171
1141
        super(TestProxyHttpServer, self).setUp()
 
1142
        self.transport_secondary_server = http_utils.ProxyServer
1172
1143
        self.build_tree_contents([('foo', 'contents of foo\n'),
1173
1144
                                  ('foo-proxied', 'proxied contents of foo\n')])
1174
1145
        # Let's setup some attributes for tests
1175
 
        self.server = self.get_readonly_server()
1176
 
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
 
1146
        server = self.get_readonly_server()
 
1147
        self.server_host_port = '%s:%d' % (server.host, server.port)
1177
1148
        if self._testing_pycurl():
1178
1149
            # Oh my ! pycurl does not check for the port as part of
1179
1150
            # no_proxy :-( So we just test the host part
1180
 
            self.no_proxy_host = self.server.host
 
1151
            self.no_proxy_host = server.host
1181
1152
        else:
1182
 
            self.no_proxy_host = self.proxy_address
 
1153
            self.no_proxy_host = self.server_host_port
1183
1154
        # The secondary server is the proxy
1184
 
        self.proxy = self.get_secondary_server()
1185
 
        self.proxy_url = self.proxy.get_url()
 
1155
        self.proxy_url = self.get_secondary_url()
1186
1156
        self._old_env = {}
1187
1157
 
1188
1158
    def _testing_pycurl(self):
1190
1160
        return (features.pycurl.available()
1191
1161
                and self._transport == PyCurlTransport)
1192
1162
 
1193
 
    def create_transport_secondary_server(self):
1194
 
        """Creates an http server that will serve files with
1195
 
        '-proxied' appended to their names.
1196
 
        """
1197
 
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
1198
 
 
1199
1163
    def _install_env(self, env):
1200
1164
        for name, value in env.iteritems():
1201
1165
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1206
1170
 
1207
1171
    def proxied_in_env(self, env):
1208
1172
        self._install_env(env)
1209
 
        url = self.server.get_url()
1210
 
        t = self._transport(url)
 
1173
        t = self.get_readonly_transport()
1211
1174
        try:
1212
1175
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1213
1176
        finally:
1215
1178
 
1216
1179
    def not_proxied_in_env(self, env):
1217
1180
        self._install_env(env)
1218
 
        url = self.server.get_url()
1219
 
        t = self._transport(url)
 
1181
        t = self.get_readonly_transport()
1220
1182
        try:
1221
1183
            self.assertEqual('contents of foo\n', t.get('foo').read())
1222
1184
        finally:
1264
1226
            # pycurl *ignores* invalid proxy env variables. If that ever change
1265
1227
            # in the future, this test will fail indicating that pycurl do not
1266
1228
            # ignore anymore such variables.
1267
 
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
 
1229
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
1268
1230
        else:
1269
1231
            self.assertRaises(errors.InvalidURL,
1270
1232
                              self.proxied_in_env,
1271
 
                              {'http_proxy': self.proxy_address})
 
1233
                              {'http_proxy': self.server_host_port})
1272
1234
 
1273
1235
 
1274
1236
class TestRanges(http_utils.TestCaseWithWebserver):
1277
1239
    def setUp(self):
1278
1240
        http_utils.TestCaseWithWebserver.setUp(self)
1279
1241
        self.build_tree_contents([('a', '0123456789')],)
1280
 
        server = self.get_readonly_server()
1281
 
        self.transport = self._transport(server.get_url())
1282
1242
 
1283
1243
    def create_transport_readonly_server(self):
1284
1244
        return http_server.HttpServer(protocol_version=self._protocol_version)
1285
1245
 
1286
1246
    def _file_contents(self, relpath, ranges):
 
1247
        t = self.get_readonly_transport()
1287
1248
        offsets = [ (start, end - start + 1) for start, end in ranges]
1288
 
        coalesce = self.transport._coalesce_offsets
 
1249
        coalesce = t._coalesce_offsets
1289
1250
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1290
 
        code, data = self.transport._get(relpath, coalesced)
 
1251
        code, data = t._get(relpath, coalesced)
1291
1252
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1292
1253
        for start, end in ranges:
1293
1254
            data.seek(start)
1294
1255
            yield data.read(end - start + 1)
1295
1256
 
1296
1257
    def _file_tail(self, relpath, tail_amount):
1297
 
        code, data = self.transport._get(relpath, [], tail_amount)
 
1258
        t = self.get_readonly_transport()
 
1259
        code, data = t._get(relpath, [], tail_amount)
1298
1260
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1299
1261
        data.seek(-tail_amount, 2)
1300
1262
        return data.read(tail_amount)
1319
1281
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1320
1282
    """Test redirection between http servers."""
1321
1283
 
1322
 
    def create_transport_secondary_server(self):
1323
 
        """Create the secondary server redirecting to the primary server"""
1324
 
        new = self.get_readonly_server()
1325
 
 
1326
 
        redirecting = http_utils.HTTPServerRedirecting(
1327
 
            protocol_version=self._protocol_version)
1328
 
        redirecting.redirect_to(new.host, new.port)
1329
 
        return redirecting
1330
 
 
1331
1284
    def setUp(self):
1332
1285
        super(TestHTTPRedirections, self).setUp()
1333
1286
        self.build_tree_contents([('a', '0123456789'),
1334
1287
                                  ('bundle',
1335
1288
                                  '# Bazaar revision bundle v0.9\n#\n')
1336
1289
                                  ],)
1337
 
        # The requests to the old server will be redirected to the new server
1338
 
        self.old_transport = self._transport(self.old_server.get_url())
1339
1290
 
1340
1291
    def test_redirected(self):
1341
 
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1342
 
        t = self._transport(self.new_server.get_url())
1343
 
        self.assertEqual('0123456789', t.get('a').read())
1344
 
 
1345
 
    def test_read_redirected_bundle_from_url(self):
1346
 
        from bzrlib.bundle import read_bundle_from_url
1347
 
        url = self.old_transport.abspath('bundle')
1348
 
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1349
 
                read_bundle_from_url, url)
1350
 
        # If read_bundle_from_url was successful we get an empty bundle
1351
 
        self.assertEqual([], bundle.revisions)
 
1292
        self.assertRaises(errors.RedirectRequested,
 
1293
                          self.get_old_transport().get, 'a')
 
1294
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
1352
1295
 
1353
1296
 
1354
1297
class RedirectedRequest(_urllib2_wrappers.Request):
1371
1314
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1372
1315
 
1373
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
 
1374
1338
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1375
1339
    """Test redirections.
1376
1340
 
1389
1353
        if (features.pycurl.available()
1390
1354
            and self._transport == PyCurlTransport):
1391
1355
            raise tests.TestNotApplicable(
1392
 
                "pycurl doesn't redirect silently annymore")
 
1356
                "pycurl doesn't redirect silently anymore")
1393
1357
        super(TestHTTPSilentRedirections, self).setUp()
1394
1358
        install_redirected_request(self)
 
1359
        cleanup_http_redirection_connections(self)
1395
1360
        self.build_tree_contents([('a','a'),
1396
1361
                                  ('1/',),
1397
1362
                                  ('1/a', 'redirected once'),
1405
1370
                                  ('5/a', 'redirected 5 times'),
1406
1371
                                  ],)
1407
1372
 
1408
 
        self.old_transport = self._transport(self.old_server.get_url())
1409
 
 
1410
 
    def create_transport_secondary_server(self):
1411
 
        """Create the secondary server, redirections are defined in the tests"""
1412
 
        return http_utils.HTTPServerRedirecting(
1413
 
            protocol_version=self._protocol_version)
1414
 
 
1415
1373
    def test_one_redirection(self):
1416
 
        t = self.old_transport
1417
 
 
1418
 
        req = RedirectedRequest('GET', t.abspath('a'))
 
1374
        t = self.get_old_transport()
 
1375
        req = RedirectedRequest('GET', t._remote_path('a'))
1419
1376
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1420
1377
                                       self.new_server.port)
1421
1378
        self.old_server.redirections = \
1422
1379
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1423
 
        self.assertEqual('redirected once',t._perform(req).read())
 
1380
        self.assertEqual('redirected once', t._perform(req).read())
1424
1381
 
1425
1382
    def test_five_redirections(self):
1426
 
        t = self.old_transport
1427
 
 
1428
 
        req = RedirectedRequest('GET', t.abspath('a'))
 
1383
        t = self.get_old_transport()
 
1384
        req = RedirectedRequest('GET', t._remote_path('a'))
1429
1385
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1430
1386
                                       self.old_server.port)
1431
1387
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1437
1393
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1438
1394
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1439
1395
            ]
1440
 
        self.assertEqual('redirected 5 times',t._perform(req).read())
 
1396
        self.assertEqual('redirected 5 times', t._perform(req).read())
1441
1397
 
1442
1398
 
1443
1399
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1446
1402
    def setUp(self):
1447
1403
        super(TestDoCatchRedirections, self).setUp()
1448
1404
        self.build_tree_contents([('a', '0123456789'),],)
1449
 
 
1450
 
        self.old_transport = self._transport(self.old_server.get_url())
1451
 
 
1452
 
    def get_a(self, transport):
1453
 
        return transport.get('a')
 
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')
1454
1411
 
1455
1412
    def test_no_redirection(self):
1456
 
        t = self._transport(self.new_server.get_url())
 
1413
        t = self.get_new_transport()
1457
1414
 
1458
1415
        # We use None for redirected so that we fail if redirected
1459
1416
        self.assertEqual('0123456789',
1463
1420
    def test_one_redirection(self):
1464
1421
        self.redirections = 0
1465
1422
 
1466
 
        def redirected(transport, exception, redirection_notice):
 
1423
        def redirected(t, exception, redirection_notice):
1467
1424
            self.redirections += 1
1468
 
            dir, file = urlutils.split(exception.target)
1469
 
            return self._transport(dir)
 
1425
            redirected_t = t._redirected_to(exception.source, exception.target)
 
1426
            return redirected_t
1470
1427
 
1471
1428
        self.assertEqual('0123456789',
1472
1429
                         transport.do_catching_redirections(
1502
1459
                                  ('b', 'contents of b\n'),])
1503
1460
 
1504
1461
    def create_transport_readonly_server(self):
1505
 
        return self._auth_server(protocol_version=self._protocol_version)
 
1462
        server = self._auth_server(protocol_version=self._protocol_version)
 
1463
        server._url_protocol = self._url_protocol
 
1464
        return server
1506
1465
 
1507
1466
    def _testing_pycurl(self):
1508
1467
        # TODO: This is duplicated for lots of the classes in this file
1521
1480
        return url
1522
1481
 
1523
1482
    def get_user_transport(self, user, password):
1524
 
        return self._transport(self.get_user_url(user, password))
 
1483
        t = transport.get_transport(self.get_user_url(user, password))
 
1484
        return t
1525
1485
 
1526
1486
    def test_no_user(self):
1527
1487
        self.server.add_user('joe', 'foo')
1712
1672
 
1713
1673
    def get_user_transport(self, user, password):
1714
1674
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1715
 
        return self._transport(self.server.get_url())
 
1675
        return TestAuth.get_user_transport(self, user, password)
1716
1676
 
1717
1677
    def _install_env(self, env):
1718
1678
        for name, value in env.iteritems():
1745
1705
        self.readfile = StringIO(socket_read_content)
1746
1706
        self.writefile = StringIO()
1747
1707
        self.writefile.close = lambda: None
 
1708
        self.close = lambda: None
1748
1709
 
1749
1710
    def makefile(self, mode='r', bufsize=None):
1750
1711
        if 'r' in mode:
1760
1721
        # We use the VFS layer as part of HTTP tunnelling tests.
1761
1722
        self._captureVar('BZR_NO_SMART_VFS', None)
1762
1723
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
 
1724
        self.http_server = self.get_readonly_server()
1763
1725
 
1764
1726
    def create_transport_readonly_server(self):
1765
 
        return http_utils.HTTPServerWithSmarts(
 
1727
        server = http_utils.HTTPServerWithSmarts(
1766
1728
            protocol_version=self._protocol_version)
 
1729
        server._url_protocol = self._url_protocol
 
1730
        return server
1767
1731
 
1768
1732
    def test_open_bzrdir(self):
1769
1733
        branch = self.make_branch('relpath')
1770
 
        http_server = self.get_readonly_server()
1771
 
        url = http_server.get_url() + 'relpath'
 
1734
        url = self.http_server.get_url() + 'relpath'
1772
1735
        bd = bzrdir.BzrDir.open(url)
 
1736
        self.addCleanup(bd.transport.disconnect)
1773
1737
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1774
1738
 
1775
1739
    def test_bulk_data(self):
1777
1741
        # The 'readv' command in the smart protocol both sends and receives
1778
1742
        # bulk data, so we use that.
1779
1743
        self.build_tree(['data-file'])
1780
 
        http_server = self.get_readonly_server()
1781
 
        http_transport = self._transport(http_server.get_url())
 
1744
        http_transport = transport.get_transport(self.http_server.get_url())
1782
1745
        medium = http_transport.get_smart_medium()
1783
1746
        # Since we provide the medium, the url below will be mostly ignored
1784
1747
        # during the test, as long as the path is '/'.
1792
1755
        post_body = 'hello\n'
1793
1756
        expected_reply_body = 'ok\x012\n'
1794
1757
 
1795
 
        http_server = self.get_readonly_server()
1796
 
        http_transport = self._transport(http_server.get_url())
 
1758
        http_transport = transport.get_transport(self.http_server.get_url())
1797
1759
        medium = http_transport.get_smart_medium()
1798
1760
        response = medium.send_http_smart_request(post_body)
1799
1761
        reply_body = response.read()
1800
1762
        self.assertEqual(expected_reply_body, reply_body)
1801
1763
 
1802
1764
    def test_smart_http_server_post_request_handler(self):
1803
 
        httpd = self.get_readonly_server()._get_httpd()
 
1765
        httpd = self.http_server.server
1804
1766
 
1805
1767
        socket = SampleSocket(
1806
1768
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1838
1800
 
1839
1801
    def test_probe_smart_server(self):
1840
1802
        """Test error handling against server refusing smart requests."""
1841
 
        server = self.get_readonly_server()
1842
 
        t = self._transport(server.get_url())
 
1803
        t = self.get_readonly_transport()
1843
1804
        # No need to build a valid smart request here, the server will not even
1844
1805
        # try to interpret it.
1845
1806
        self.assertRaises(errors.SmartProtocolError,
1846
1807
                          t.get_smart_medium().send_http_smart_request,
1847
1808
                          'whatever')
1848
1809
 
 
1810
 
1849
1811
class Test_redirected_to(tests.TestCase):
1850
1812
 
1851
1813
    def test_redirected_to_subdir(self):
1904
1866
    line.
1905
1867
    """
1906
1868
 
1907
 
    def handle_one_request(self):
 
1869
    def _handle_one_request(self):
1908
1870
        tcs = self.server.test_case_server
1909
1871
        requestline = self.rfile.readline()
1910
1872
        headers = self.MessageClass(self.rfile, 0)
1974
1936
        # We override at class level because constructors may propagate the
1975
1937
        # bound method and render instance overriding ineffective (an
1976
1938
        # alternative would be to define a specific ui factory instead...)
1977
 
        self.orig_report_activity = self._transport._report_activity
1978
 
        self._transport._report_activity = report_activity
1979
 
 
1980
 
    def tearDown(self):
1981
 
        self._transport._report_activity = self.orig_report_activity
1982
 
        self.server.stop_server()
1983
 
        tests.TestCase.tearDown(self)
 
1939
        self.overrideAttr(self._transport, '_report_activity', report_activity)
 
1940
        self.addCleanup(self.server.stop_server)
1984
1941
 
1985
1942
    def get_transport(self):
1986
 
        return self._transport(self.server.get_url())
 
1943
        t = self._transport(self.server.get_url())
 
1944
        # FIXME: Needs cleanup -- vila 20100611
 
1945
        return t
1987
1946
 
1988
1947
    def assertActivitiesMatch(self):
1989
1948
        self.assertEqual(self.server.bytes_read,
2094
2053
'''
2095
2054
        t = self.get_transport()
2096
2055
        # We must send a single line of body bytes, see
2097
 
        # PredefinedRequestHandler.handle_one_request
 
2056
        # PredefinedRequestHandler._handle_one_request
2098
2057
        code, f = t._post('abc def end-of-body\n')
2099
2058
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2100
2059
        self.assertActivitiesMatch()
2103
2062
class TestActivity(tests.TestCase, TestActivityMixin):
2104
2063
 
2105
2064
    def setUp(self):
2106
 
        tests.TestCase.setUp(self)
2107
 
        self.server = self._activity_server(self._protocol_version)
2108
 
        self.server.start_server()
2109
 
        self.activities = {}
2110
 
        def report_activity(t, bytes, direction):
2111
 
            count = self.activities.get(direction, 0)
2112
 
            count += bytes
2113
 
            self.activities[direction] = count
2114
 
 
2115
 
        # We override at class level because constructors may propagate the
2116
 
        # bound method and render instance overriding ineffective (an
2117
 
        # alternative would be to define a specific ui factory instead...)
2118
 
        self.orig_report_activity = self._transport._report_activity
2119
 
        self._transport._report_activity = report_activity
2120
 
 
2121
 
    def tearDown(self):
2122
 
        self._transport._report_activity = self.orig_report_activity
2123
 
        self.server.stop_server()
2124
 
        tests.TestCase.tearDown(self)
 
2065
        TestActivityMixin.setUp(self)
2125
2066
 
2126
2067
 
2127
2068
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2128
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
 
2129
2078
    def setUp(self):
2130
 
        tests.TestCase.setUp(self)
2131
 
        # Unlike TestActivity, we are really testing ReportingFileSocket and
2132
 
        # ReportingSocket, so we don't need all the parametrization. Since
2133
 
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2134
 
        # test them through their use by the transport than directly (that's a
2135
 
        # bit less clean but far more simpler and effective).
2136
 
        self.server = ActivityHTTPServer('HTTP/1.1')
2137
 
        self._transport=_urllib.HttpTransport_urllib
2138
 
 
2139
 
        self.server.start_server()
2140
 
 
2141
 
        # We override at class level because constructors may propagate the
2142
 
        # bound method and render instance overriding ineffective (an
2143
 
        # alternative would be to define a specific ui factory instead...)
2144
 
        self.orig_report_activity = self._transport._report_activity
2145
 
        self._transport._report_activity = None
2146
 
 
2147
 
    def tearDown(self):
2148
 
        self._transport._report_activity = self.orig_report_activity
2149
 
        self.server.stop_server()
2150
 
        tests.TestCase.tearDown(self)
 
2079
        self._transport =_urllib.HttpTransport_urllib
 
2080
        TestActivityMixin.setUp(self)
2151
2081
 
2152
2082
    def assertActivitiesMatch(self):
2153
2083
        # Nothing to check here
2163
2093
    _auth_server = http_utils.HTTPBasicAuthServer
2164
2094
    _transport = _urllib.HttpTransport_urllib
2165
2095
 
2166
 
    def create_transport_readonly_server(self):
2167
 
        return self._auth_server(protocol_version=self._protocol_version)
2168
 
 
2169
 
    def create_transport_secondary_server(self):
2170
 
        """Create the secondary server redirecting to the primary server"""
2171
 
        new = self.get_readonly_server()
2172
 
 
2173
 
        redirecting = http_utils.HTTPServerRedirecting(
2174
 
            protocol_version=self._protocol_version)
2175
 
        redirecting.redirect_to(new.host, new.port)
2176
 
        return redirecting
2177
 
 
2178
2096
    def setUp(self):
2179
2097
        super(TestAuthOnRedirected, self).setUp()
2180
2098
        self.build_tree_contents([('a','a'),
2185
2103
                                       self.new_server.port)
2186
2104
        self.old_server.redirections = [
2187
2105
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2188
 
        self.old_transport = self._transport(self.old_server.get_url())
 
2106
        self.old_transport = self.get_old_transport()
2189
2107
        self.new_server.add_user('joe', 'foo')
2190
 
 
2191
 
    def get_a(self, transport):
2192
 
        return transport.get('a')
 
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')
2193
2117
 
2194
2118
    def test_auth_on_redirected_via_do_catching_redirections(self):
2195
2119
        self.redirections = 0
2196
2120
 
2197
 
        def redirected(transport, exception, redirection_notice):
 
2121
        def redirected(t, exception, redirection_notice):
2198
2122
            self.redirections += 1
2199
 
            dir, file = urlutils.split(exception.target)
2200
 
            return self._transport(dir)
 
2123
            redirected_t = t._redirected_to(exception.source, exception.target)
 
2124
            self.addCleanup(redirected_t.disconnect)
 
2125
            return redirected_t
2201
2126
 
2202
2127
        stdout = tests.StringIOWrapper()
2203
2128
        stderr = tests.StringIOWrapper()
2224
2149
                                       self.new_server.port)
2225
2150
        self.old_server.redirections = [
2226
2151
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2227
 
        self.assertEqual('redirected once',t._perform(req).read())
 
2152
        self.assertEqual('redirected once', t._perform(req).read())
2228
2153
        # stdin should be empty
2229
2154
        self.assertEqual('', ui.ui_factory.stdin.readline())
2230
2155
        # stdout should be empty, stderr will contains the prompts