~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: John Arbash Meinel
  • Date: 2010-08-24 19:21:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5390.
  • Revision ID: john@arbash-meinel.com-20100824192132-2ktt5adkbk5bk1ct
Handle test_source and extensions. Also define an 'extern' protocol, to allow
the test suite to recognize that returning an object of that type is a Python object.

Show diffs side-by-side

added added

removed removed

Lines of Context:
48
48
    features,
49
49
    http_server,
50
50
    http_utils,
51
 
    test_server,
52
51
    )
53
52
from bzrlib.transport import (
54
53
    http,
78
77
    transport_scenarios = [
79
78
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
80
79
                        _server=http_server.HttpServer_urllib,
81
 
                        _url_protocol='http+urllib',)),
 
80
                        _qualified_prefix='http+urllib',)),
82
81
        ]
83
82
    if features.pycurl.available():
84
83
        transport_scenarios.append(
85
84
            ('pycurl', dict(_transport=PyCurlTransport,
86
85
                            _server=http_server.HttpServer_PyCurl,
87
 
                            _url_protocol='http+pycurl',)))
 
86
                            _qualified_prefix='http+pycurl',)))
88
87
    tests.multiply_tests(t_tests, transport_scenarios, result)
89
88
 
90
89
    protocol_scenarios = [
229
228
        self._sock.bind(('127.0.0.1', 0))
230
229
        self.host, self.port = self._sock.getsockname()
231
230
        self._ready = threading.Event()
232
 
        self._thread = test_server.ThreadWithException(
233
 
            event=self._ready, target=self._accept_read_and_reply)
 
231
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
232
        self._thread.setDaemon(True)
234
233
        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()
 
234
        self._ready.wait(5)
238
235
 
239
236
    def _accept_read_and_reply(self):
240
237
        self._sock.listen(1)
241
238
        self._ready.set()
242
 
        conn, address = self._sock.accept()
243
 
        if self._expect_body_tail is not None:
 
239
        self._sock.settimeout(5)
 
240
        try:
 
241
            conn, address = self._sock.accept()
 
242
            # On win32, the accepted connection will be non-blocking to start
 
243
            # with because we're using settimeout.
 
244
            conn.setblocking(True)
244
245
            while not self.received_bytes.endswith(self._expect_body_tail):
245
246
                self.received_bytes += conn.recv(4096)
246
247
            conn.sendall('HTTP/1.1 200 OK\r\n')
247
 
        try:
 
248
        except socket.timeout:
 
249
            # Make sure the client isn't stuck waiting for us to e.g. accept.
248
250
            self._sock.close()
249
251
        except socket.error:
250
252
            # The client may have already closed the socket.
252
254
 
253
255
    def stop_server(self):
254
256
        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()
 
257
            self._sock.close()
259
258
        except socket.error:
260
259
            # We might have already closed it.  We don't care.
261
260
            pass
262
261
        self.host = None
263
262
        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
263
 
268
264
 
269
265
class TestAuthHeader(tests.TestCase):
313
309
 
314
310
            protocol_version = 'HTTP/0.1'
315
311
 
316
 
        self.assertRaises(httplib.UnknownProtocol,
317
 
                          http_server.HttpServer, BogusRequestHandler)
 
312
        server = http_server.HttpServer(BogusRequestHandler)
 
313
        try:
 
314
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
315
        except:
 
316
            server.stop_server()
 
317
            self.fail('HTTP Server creation did not raise UnknownProtocol')
318
318
 
319
319
    def test_force_invalid_protocol(self):
320
 
        self.assertRaises(httplib.UnknownProtocol,
321
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
320
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
321
        try:
 
322
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
323
        except:
 
324
            server.stop_server()
 
325
            self.fail('HTTP Server creation did not raise UnknownProtocol')
322
326
 
323
327
    def test_server_start_and_stop(self):
324
328
        server = http_server.HttpServer()
325
 
        self.addCleanup(server.stop_server)
326
329
        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)
 
330
        try:
 
331
            self.assertTrue(server._http_running)
 
332
        finally:
 
333
            server.stop_server()
 
334
        self.assertFalse(server._http_running)
330
335
 
331
336
    def test_create_http_server_one_zero(self):
332
337
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
335
340
 
336
341
        server = http_server.HttpServer(RequestHandlerOneZero)
337
342
        self.start_server(server)
338
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
343
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
339
344
 
340
345
    def test_create_http_server_one_one(self):
341
346
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
344
349
 
345
350
        server = http_server.HttpServer(RequestHandlerOneOne)
346
351
        self.start_server(server)
347
 
        self.assertIsInstance(server.server,
 
352
        self.assertIsInstance(server._httpd,
348
353
                              http_server.TestingThreadingHTTPServer)
349
354
 
350
355
    def test_create_http_server_force_one_one(self):
355
360
        server = http_server.HttpServer(RequestHandlerOneZero,
356
361
                                        protocol_version='HTTP/1.1')
357
362
        self.start_server(server)
358
 
        self.assertIsInstance(server.server,
 
363
        self.assertIsInstance(server._httpd,
359
364
                              http_server.TestingThreadingHTTPServer)
360
365
 
361
366
    def test_create_http_server_force_one_zero(self):
366
371
        server = http_server.HttpServer(RequestHandlerOneOne,
367
372
                                        protocol_version='HTTP/1.0')
368
373
        self.start_server(server)
369
 
        self.assertIsInstance(server.server,
 
374
        self.assertIsInstance(server._httpd,
370
375
                              http_server.TestingHTTPServer)
371
376
 
372
377
 
431
436
        server.start_server()
432
437
        try:
433
438
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
439
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
440
        finally:
436
441
            server.stop_server()
437
442
 
482
487
 
483
488
    def test_http_has(self):
484
489
        server = self.get_readonly_server()
485
 
        t = self.get_readonly_transport()
 
490
        t = self._transport(server.get_url())
486
491
        self.assertEqual(t.has('foo/bar'), True)
487
492
        self.assertEqual(len(server.logs), 1)
488
493
        self.assertContainsRe(server.logs[0],
490
495
 
491
496
    def test_http_has_not_found(self):
492
497
        server = self.get_readonly_server()
493
 
        t = self.get_readonly_transport()
 
498
        t = self._transport(server.get_url())
494
499
        self.assertEqual(t.has('not-found'), False)
495
500
        self.assertContainsRe(server.logs[1],
496
501
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
497
502
 
498
503
    def test_http_get(self):
499
504
        server = self.get_readonly_server()
500
 
        t = self.get_readonly_transport()
 
505
        t = self._transport(server.get_url())
501
506
        fp = t.get('foo/bar')
502
507
        self.assertEqualDiff(
503
508
            fp.read(),
526
531
    """Test registrations of various http implementations"""
527
532
 
528
533
    def test_http_registered(self):
529
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
534
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
530
535
        self.assertIsInstance(t, transport.Transport)
531
536
        self.assertIsInstance(t, self._transport)
532
537
 
535
540
 
536
541
    def test_post_body_is_received(self):
537
542
        server = RecordingServer(expect_body_tail='end-of-body',
538
 
                                 scheme=self._url_protocol)
 
543
            scheme=self._qualified_prefix)
539
544
        self.start_server(server)
540
545
        url = server.get_url()
541
 
        # FIXME: needs a cleanup -- vila 20100611
542
 
        http_transport = transport.get_transport(url)
 
546
        http_transport = self._transport(url)
543
547
        code, response = http_transport._post('abc def end-of-body')
544
548
        self.assertTrue(
545
549
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
589
593
    _req_handler_class = http_server.TestingHTTPRequestHandler
590
594
 
591
595
    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
 
596
        return http_server.HttpServer(self._req_handler_class,
 
597
                                      protocol_version=self._protocol_version)
596
598
 
597
599
    def _testing_pycurl(self):
598
600
        # TODO: This is duplicated for lots of the classes in this file
603
605
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
604
606
    """Whatever request comes in, close the connection"""
605
607
 
606
 
    def _handle_one_request(self):
 
608
    def handle_one_request(self):
607
609
        """Handle a single HTTP request, by abruptly closing the connection"""
608
610
        self.close_connection = 1
609
611
 
614
616
    _req_handler_class = WallRequestHandler
615
617
 
616
618
    def test_http_has(self):
617
 
        t = self.get_readonly_transport()
 
619
        server = self.get_readonly_server()
 
620
        t = self._transport(server.get_url())
618
621
        # Unfortunately httplib (see HTTPResponse._read_status
619
622
        # for details) make no distinction between a closed
620
623
        # socket and badly formatted status line, so we can't
626
629
                          t.has, 'foo/bar')
627
630
 
628
631
    def test_http_get(self):
629
 
        t = self.get_readonly_transport()
 
632
        server = self.get_readonly_server()
 
633
        t = self._transport(server.get_url())
630
634
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
631
635
                           errors.InvalidHttpResponse),
632
636
                          t.get, 'foo/bar')
649
653
    _req_handler_class = BadStatusRequestHandler
650
654
 
651
655
    def test_http_has(self):
652
 
        t = self.get_readonly_transport()
 
656
        server = self.get_readonly_server()
 
657
        t = self._transport(server.get_url())
653
658
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
654
659
 
655
660
    def test_http_get(self):
656
 
        t = self.get_readonly_transport()
 
661
        server = self.get_readonly_server()
 
662
        t = self._transport(server.get_url())
657
663
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
658
664
 
659
665
 
664
670
        """Fakes handling a single HTTP request, returns a bad status"""
665
671
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
666
672
        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
673
        return False
672
674
 
673
675
 
679
681
 
680
682
    _req_handler_class = InvalidStatusRequestHandler
681
683
 
 
684
    def test_http_has(self):
 
685
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
686
            raise tests.KnownFailure(
 
687
                'pycurl hangs if the server send back garbage')
 
688
        super(TestInvalidStatusServer, self).test_http_has()
 
689
 
 
690
    def test_http_get(self):
 
691
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
692
            raise tests.KnownFailure(
 
693
                'pycurl hangs if the server send back garbage')
 
694
        super(TestInvalidStatusServer, self).test_http_get()
 
695
 
682
696
 
683
697
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
684
698
    """Whatever request comes in, returns a bad protocol version"""
706
720
        super(TestBadProtocolServer, self).setUp()
707
721
 
708
722
    def test_http_has(self):
709
 
        t = self.get_readonly_transport()
 
723
        server = self.get_readonly_server()
 
724
        t = self._transport(server.get_url())
710
725
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
711
726
 
712
727
    def test_http_get(self):
713
 
        t = self.get_readonly_transport()
 
728
        server = self.get_readonly_server()
 
729
        t = self._transport(server.get_url())
714
730
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
715
731
 
716
732
 
730
746
    _req_handler_class = ForbiddenRequestHandler
731
747
 
732
748
    def test_http_has(self):
733
 
        t = self.get_readonly_transport()
 
749
        server = self.get_readonly_server()
 
750
        t = self._transport(server.get_url())
734
751
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
735
752
 
736
753
    def test_http_get(self):
737
 
        t = self.get_readonly_transport()
 
754
        server = self.get_readonly_server()
 
755
        t = self._transport(server.get_url())
738
756
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
739
757
 
740
758
 
779
797
        self.build_tree_contents([('a', '0123456789')],)
780
798
 
781
799
    def test_readv(self):
782
 
        t = self.get_readonly_transport()
 
800
        server = self.get_readonly_server()
 
801
        t = self._transport(server.get_url())
783
802
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
784
803
        self.assertEqual(l[0], (0, '0'))
785
804
        self.assertEqual(l[1], (1, '1'))
787
806
        self.assertEqual(l[3], (9, '9'))
788
807
 
789
808
    def test_readv_out_of_order(self):
790
 
        t = self.get_readonly_transport()
 
809
        server = self.get_readonly_server()
 
810
        t = self._transport(server.get_url())
791
811
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
792
812
        self.assertEqual(l[0], (1, '1'))
793
813
        self.assertEqual(l[1], (9, '9'))
795
815
        self.assertEqual(l[3], (3, '34'))
796
816
 
797
817
    def test_readv_invalid_ranges(self):
798
 
        t = self.get_readonly_transport()
 
818
        server = self.get_readonly_server()
 
819
        t = self._transport(server.get_url())
799
820
 
800
821
        # This is intentionally reading off the end of the file
801
822
        # since we are sure that it cannot get there
809
830
 
810
831
    def test_readv_multiple_get_requests(self):
811
832
        server = self.get_readonly_server()
812
 
        t = self.get_readonly_transport()
 
833
        t = self._transport(server.get_url())
813
834
        # force transport to issue multiple requests
814
835
        t._max_readv_combine = 1
815
836
        t._max_get_ranges = 1
823
844
 
824
845
    def test_readv_get_max_size(self):
825
846
        server = self.get_readonly_server()
826
 
        t = self.get_readonly_transport()
 
847
        t = self._transport(server.get_url())
827
848
        # force transport to issue multiple requests by limiting the number of
828
849
        # bytes by request. Note that this apply to coalesced offsets only, a
829
850
        # single range will keep its size even if bigger than the limit.
838
859
 
839
860
    def test_complete_readv_leave_pipe_clean(self):
840
861
        server = self.get_readonly_server()
841
 
        t = self.get_readonly_transport()
 
862
        t = self._transport(server.get_url())
842
863
        # force transport to issue multiple requests
843
864
        t._get_max_size = 2
844
865
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
849
870
 
850
871
    def test_incomplete_readv_leave_pipe_clean(self):
851
872
        server = self.get_readonly_server()
852
 
        t = self.get_readonly_transport()
 
873
        t = self._transport(server.get_url())
853
874
        # force transport to issue multiple requests
854
875
        t._get_max_size = 2
855
876
        # Don't collapse readv results into a list so that we leave unread
1005
1026
 
1006
1027
    def test_readv_with_short_reads(self):
1007
1028
        server = self.get_readonly_server()
1008
 
        t = self.get_readonly_transport()
 
1029
        t = self._transport(server.get_url())
1009
1030
        # Force separate ranges for each offset
1010
1031
        t._bytes_to_read_before_seek = 0
1011
1032
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1062
1083
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1063
1084
                                      protocol_version=self._protocol_version)
1064
1085
 
 
1086
    def get_transport(self):
 
1087
        return self._transport(self.get_readonly_server().get_url())
 
1088
 
1065
1089
    def setUp(self):
1066
1090
        http_utils.TestCaseWithWebserver.setUp(self)
1067
1091
        # We need to manipulate ranges that correspond to real chunks in the
1071
1095
        self.build_tree_contents([('a', content)],)
1072
1096
 
1073
1097
    def test_few_ranges(self):
1074
 
        t = self.get_readonly_transport()
 
1098
        t = self.get_transport()
1075
1099
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
1100
        self.assertEqual(l[0], (0, '0000'))
1077
1101
        self.assertEqual(l[1], (1024, '0001'))
1078
1102
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1079
1103
 
1080
1104
    def test_more_ranges(self):
1081
 
        t = self.get_readonly_transport()
 
1105
        t = self.get_transport()
1082
1106
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
1107
        self.assertEqual(l[0], (0, '0000'))
1084
1108
        self.assertEqual(l[1], (1024, '0001'))
1135
1159
    """
1136
1160
 
1137
1161
    # FIXME: We don't have an https server available, so we don't
1138
 
    # test https connections. --vila toolongago
 
1162
    # test https connections.
1139
1163
 
1140
1164
    def setUp(self):
1141
1165
        super(TestProxyHttpServer, self).setUp()
1142
 
        self.transport_secondary_server = http_utils.ProxyServer
1143
1166
        self.build_tree_contents([('foo', 'contents of foo\n'),
1144
1167
                                  ('foo-proxied', 'proxied contents of foo\n')])
1145
1168
        # Let's setup some attributes for tests
1146
 
        server = self.get_readonly_server()
1147
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1169
        self.server = self.get_readonly_server()
 
1170
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1148
1171
        if self._testing_pycurl():
1149
1172
            # Oh my ! pycurl does not check for the port as part of
1150
1173
            # no_proxy :-( So we just test the host part
1151
 
            self.no_proxy_host = server.host
 
1174
            self.no_proxy_host = self.server.host
1152
1175
        else:
1153
 
            self.no_proxy_host = self.server_host_port
 
1176
            self.no_proxy_host = self.proxy_address
1154
1177
        # The secondary server is the proxy
1155
 
        self.proxy_url = self.get_secondary_url()
 
1178
        self.proxy = self.get_secondary_server()
 
1179
        self.proxy_url = self.proxy.get_url()
1156
1180
        self._old_env = {}
1157
1181
 
1158
1182
    def _testing_pycurl(self):
1160
1184
        return (features.pycurl.available()
1161
1185
                and self._transport == PyCurlTransport)
1162
1186
 
 
1187
    def create_transport_secondary_server(self):
 
1188
        """Creates an http server that will serve files with
 
1189
        '-proxied' appended to their names.
 
1190
        """
 
1191
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
 
1192
 
1163
1193
    def _install_env(self, env):
1164
1194
        for name, value in env.iteritems():
1165
1195
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1170
1200
 
1171
1201
    def proxied_in_env(self, env):
1172
1202
        self._install_env(env)
1173
 
        t = self.get_readonly_transport()
 
1203
        url = self.server.get_url()
 
1204
        t = self._transport(url)
1174
1205
        try:
1175
1206
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1176
1207
        finally:
1178
1209
 
1179
1210
    def not_proxied_in_env(self, env):
1180
1211
        self._install_env(env)
1181
 
        t = self.get_readonly_transport()
 
1212
        url = self.server.get_url()
 
1213
        t = self._transport(url)
1182
1214
        try:
1183
1215
            self.assertEqual('contents of foo\n', t.get('foo').read())
1184
1216
        finally:
1226
1258
            # pycurl *ignores* invalid proxy env variables. If that ever change
1227
1259
            # in the future, this test will fail indicating that pycurl do not
1228
1260
            # ignore anymore such variables.
1229
 
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
 
1261
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1230
1262
        else:
1231
1263
            self.assertRaises(errors.InvalidURL,
1232
1264
                              self.proxied_in_env,
1233
 
                              {'http_proxy': self.server_host_port})
 
1265
                              {'http_proxy': self.proxy_address})
1234
1266
 
1235
1267
 
1236
1268
class TestRanges(http_utils.TestCaseWithWebserver):
1239
1271
    def setUp(self):
1240
1272
        http_utils.TestCaseWithWebserver.setUp(self)
1241
1273
        self.build_tree_contents([('a', '0123456789')],)
 
1274
        server = self.get_readonly_server()
 
1275
        self.transport = self._transport(server.get_url())
1242
1276
 
1243
1277
    def create_transport_readonly_server(self):
1244
1278
        return http_server.HttpServer(protocol_version=self._protocol_version)
1245
1279
 
1246
1280
    def _file_contents(self, relpath, ranges):
1247
 
        t = self.get_readonly_transport()
1248
1281
        offsets = [ (start, end - start + 1) for start, end in ranges]
1249
 
        coalesce = t._coalesce_offsets
 
1282
        coalesce = self.transport._coalesce_offsets
1250
1283
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1251
 
        code, data = t._get(relpath, coalesced)
 
1284
        code, data = self.transport._get(relpath, coalesced)
1252
1285
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1253
1286
        for start, end in ranges:
1254
1287
            data.seek(start)
1255
1288
            yield data.read(end - start + 1)
1256
1289
 
1257
1290
    def _file_tail(self, relpath, tail_amount):
1258
 
        t = self.get_readonly_transport()
1259
 
        code, data = t._get(relpath, [], tail_amount)
 
1291
        code, data = self.transport._get(relpath, [], tail_amount)
1260
1292
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1261
1293
        data.seek(-tail_amount, 2)
1262
1294
        return data.read(tail_amount)
1281
1313
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1282
1314
    """Test redirection between http servers."""
1283
1315
 
 
1316
    def create_transport_secondary_server(self):
 
1317
        """Create the secondary server redirecting to the primary server"""
 
1318
        new = self.get_readonly_server()
 
1319
 
 
1320
        redirecting = http_utils.HTTPServerRedirecting(
 
1321
            protocol_version=self._protocol_version)
 
1322
        redirecting.redirect_to(new.host, new.port)
 
1323
        return redirecting
 
1324
 
1284
1325
    def setUp(self):
1285
1326
        super(TestHTTPRedirections, self).setUp()
1286
1327
        self.build_tree_contents([('a', '0123456789'),
1287
1328
                                  ('bundle',
1288
1329
                                  '# Bazaar revision bundle v0.9\n#\n')
1289
1330
                                  ],)
 
1331
        # The requests to the old server will be redirected to the new server
 
1332
        self.old_transport = self._transport(self.old_server.get_url())
1290
1333
 
1291
1334
    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())
 
1335
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1336
        t = self._transport(self.new_server.get_url())
 
1337
        self.assertEqual('0123456789', t.get('a').read())
1295
1338
 
1296
1339
 
1297
1340
class RedirectedRequest(_urllib2_wrappers.Request):
1314
1357
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1315
1358
 
1316
1359
 
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
1360
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1339
1361
    """Test redirections.
1340
1362
 
1353
1375
        if (features.pycurl.available()
1354
1376
            and self._transport == PyCurlTransport):
1355
1377
            raise tests.TestNotApplicable(
1356
 
                "pycurl doesn't redirect silently anymore")
 
1378
                "pycurl doesn't redirect silently annymore")
1357
1379
        super(TestHTTPSilentRedirections, self).setUp()
1358
1380
        install_redirected_request(self)
1359
 
        cleanup_http_redirection_connections(self)
1360
1381
        self.build_tree_contents([('a','a'),
1361
1382
                                  ('1/',),
1362
1383
                                  ('1/a', 'redirected once'),
1370
1391
                                  ('5/a', 'redirected 5 times'),
1371
1392
                                  ],)
1372
1393
 
 
1394
        self.old_transport = self._transport(self.old_server.get_url())
 
1395
 
 
1396
    def create_transport_secondary_server(self):
 
1397
        """Create the secondary server, redirections are defined in the tests"""
 
1398
        return http_utils.HTTPServerRedirecting(
 
1399
            protocol_version=self._protocol_version)
 
1400
 
1373
1401
    def test_one_redirection(self):
1374
 
        t = self.get_old_transport()
1375
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1402
        t = self.old_transport
 
1403
 
 
1404
        req = RedirectedRequest('GET', t.abspath('a'))
1376
1405
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1377
1406
                                       self.new_server.port)
1378
1407
        self.old_server.redirections = \
1379
1408
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1380
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1409
        self.assertEqual('redirected once',t._perform(req).read())
1381
1410
 
1382
1411
    def test_five_redirections(self):
1383
 
        t = self.get_old_transport()
1384
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1412
        t = self.old_transport
 
1413
 
 
1414
        req = RedirectedRequest('GET', t.abspath('a'))
1385
1415
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1386
1416
                                       self.old_server.port)
1387
1417
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1393
1423
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1394
1424
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1395
1425
            ]
1396
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1426
        self.assertEqual('redirected 5 times',t._perform(req).read())
1397
1427
 
1398
1428
 
1399
1429
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1402
1432
    def setUp(self):
1403
1433
        super(TestDoCatchRedirections, self).setUp()
1404
1434
        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')
 
1435
 
 
1436
        self.old_transport = self._transport(self.old_server.get_url())
 
1437
 
 
1438
    def get_a(self, transport):
 
1439
        return transport.get('a')
1411
1440
 
1412
1441
    def test_no_redirection(self):
1413
 
        t = self.get_new_transport()
 
1442
        t = self._transport(self.new_server.get_url())
1414
1443
 
1415
1444
        # We use None for redirected so that we fail if redirected
1416
1445
        self.assertEqual('0123456789',
1420
1449
    def test_one_redirection(self):
1421
1450
        self.redirections = 0
1422
1451
 
1423
 
        def redirected(t, exception, redirection_notice):
 
1452
        def redirected(transport, exception, redirection_notice):
1424
1453
            self.redirections += 1
1425
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1426
 
            return redirected_t
 
1454
            dir, file = urlutils.split(exception.target)
 
1455
            return self._transport(dir)
1427
1456
 
1428
1457
        self.assertEqual('0123456789',
1429
1458
                         transport.do_catching_redirections(
1459
1488
                                  ('b', 'contents of b\n'),])
1460
1489
 
1461
1490
    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
 
1491
        return self._auth_server(protocol_version=self._protocol_version)
1465
1492
 
1466
1493
    def _testing_pycurl(self):
1467
1494
        # TODO: This is duplicated for lots of the classes in this file
1480
1507
        return url
1481
1508
 
1482
1509
    def get_user_transport(self, user, password):
1483
 
        t = transport.get_transport(self.get_user_url(user, password))
1484
 
        return t
 
1510
        return self._transport(self.get_user_url(user, password))
1485
1511
 
1486
1512
    def test_no_user(self):
1487
1513
        self.server.add_user('joe', 'foo')
1672
1698
 
1673
1699
    def get_user_transport(self, user, password):
1674
1700
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1675
 
        return TestAuth.get_user_transport(self, user, password)
 
1701
        return self._transport(self.server.get_url())
1676
1702
 
1677
1703
    def _install_env(self, env):
1678
1704
        for name, value in env.iteritems():
1705
1731
        self.readfile = StringIO(socket_read_content)
1706
1732
        self.writefile = StringIO()
1707
1733
        self.writefile.close = lambda: None
1708
 
        self.close = lambda: None
1709
1734
 
1710
1735
    def makefile(self, mode='r', bufsize=None):
1711
1736
        if 'r' in mode:
1721
1746
        # We use the VFS layer as part of HTTP tunnelling tests.
1722
1747
        self._captureVar('BZR_NO_SMART_VFS', None)
1723
1748
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1724
 
        self.http_server = self.get_readonly_server()
1725
1749
 
1726
1750
    def create_transport_readonly_server(self):
1727
 
        server = http_utils.HTTPServerWithSmarts(
 
1751
        return http_utils.HTTPServerWithSmarts(
1728
1752
            protocol_version=self._protocol_version)
1729
 
        server._url_protocol = self._url_protocol
1730
 
        return server
1731
1753
 
1732
1754
    def test_open_bzrdir(self):
1733
1755
        branch = self.make_branch('relpath')
1734
 
        url = self.http_server.get_url() + 'relpath'
 
1756
        http_server = self.get_readonly_server()
 
1757
        url = http_server.get_url() + 'relpath'
1735
1758
        bd = bzrdir.BzrDir.open(url)
1736
 
        self.addCleanup(bd.transport.disconnect)
1737
1759
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1738
1760
 
1739
1761
    def test_bulk_data(self):
1741
1763
        # The 'readv' command in the smart protocol both sends and receives
1742
1764
        # bulk data, so we use that.
1743
1765
        self.build_tree(['data-file'])
1744
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1766
        http_server = self.get_readonly_server()
 
1767
        http_transport = self._transport(http_server.get_url())
1745
1768
        medium = http_transport.get_smart_medium()
1746
1769
        # Since we provide the medium, the url below will be mostly ignored
1747
1770
        # during the test, as long as the path is '/'.
1755
1778
        post_body = 'hello\n'
1756
1779
        expected_reply_body = 'ok\x012\n'
1757
1780
 
1758
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1781
        http_server = self.get_readonly_server()
 
1782
        http_transport = self._transport(http_server.get_url())
1759
1783
        medium = http_transport.get_smart_medium()
1760
1784
        response = medium.send_http_smart_request(post_body)
1761
1785
        reply_body = response.read()
1762
1786
        self.assertEqual(expected_reply_body, reply_body)
1763
1787
 
1764
1788
    def test_smart_http_server_post_request_handler(self):
1765
 
        httpd = self.http_server.server
 
1789
        httpd = self.get_readonly_server()._get_httpd()
1766
1790
 
1767
1791
        socket = SampleSocket(
1768
1792
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1800
1824
 
1801
1825
    def test_probe_smart_server(self):
1802
1826
        """Test error handling against server refusing smart requests."""
1803
 
        t = self.get_readonly_transport()
 
1827
        server = self.get_readonly_server()
 
1828
        t = self._transport(server.get_url())
1804
1829
        # No need to build a valid smart request here, the server will not even
1805
1830
        # try to interpret it.
1806
1831
        self.assertRaises(errors.SmartProtocolError,
1807
1832
                          t.get_smart_medium().send_http_smart_request,
1808
1833
                          'whatever')
1809
1834
 
1810
 
 
1811
1835
class Test_redirected_to(tests.TestCase):
1812
1836
 
1813
1837
    def test_redirected_to_subdir(self):
1866
1890
    line.
1867
1891
    """
1868
1892
 
1869
 
    def _handle_one_request(self):
 
1893
    def handle_one_request(self):
1870
1894
        tcs = self.server.test_case_server
1871
1895
        requestline = self.rfile.readline()
1872
1896
        headers = self.MessageClass(self.rfile, 0)
1940
1964
        self.addCleanup(self.server.stop_server)
1941
1965
 
1942
1966
    def get_transport(self):
1943
 
        t = self._transport(self.server.get_url())
1944
 
        # FIXME: Needs cleanup -- vila 20100611
1945
 
        return t
 
1967
        return self._transport(self.server.get_url())
1946
1968
 
1947
1969
    def assertActivitiesMatch(self):
1948
1970
        self.assertEqual(self.server.bytes_read,
2053
2075
'''
2054
2076
        t = self.get_transport()
2055
2077
        # We must send a single line of body bytes, see
2056
 
        # PredefinedRequestHandler._handle_one_request
 
2078
        # PredefinedRequestHandler.handle_one_request
2057
2079
        code, f = t._post('abc def end-of-body\n')
2058
2080
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2059
2081
        self.assertActivitiesMatch()
2093
2115
    _auth_server = http_utils.HTTPBasicAuthServer
2094
2116
    _transport = _urllib.HttpTransport_urllib
2095
2117
 
 
2118
    def create_transport_readonly_server(self):
 
2119
        return self._auth_server(protocol_version=self._protocol_version)
 
2120
 
 
2121
    def create_transport_secondary_server(self):
 
2122
        """Create the secondary server redirecting to the primary server"""
 
2123
        new = self.get_readonly_server()
 
2124
 
 
2125
        redirecting = http_utils.HTTPServerRedirecting(
 
2126
            protocol_version=self._protocol_version)
 
2127
        redirecting.redirect_to(new.host, new.port)
 
2128
        return redirecting
 
2129
 
2096
2130
    def setUp(self):
2097
2131
        super(TestAuthOnRedirected, self).setUp()
2098
2132
        self.build_tree_contents([('a','a'),
2103
2137
                                       self.new_server.port)
2104
2138
        self.old_server.redirections = [
2105
2139
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2106
 
        self.old_transport = self.get_old_transport()
 
2140
        self.old_transport = self._transport(self.old_server.get_url())
2107
2141
        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')
 
2142
 
 
2143
    def get_a(self, transport):
 
2144
        return transport.get('a')
2117
2145
 
2118
2146
    def test_auth_on_redirected_via_do_catching_redirections(self):
2119
2147
        self.redirections = 0
2120
2148
 
2121
 
        def redirected(t, exception, redirection_notice):
 
2149
        def redirected(transport, exception, redirection_notice):
2122
2150
            self.redirections += 1
2123
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2124
 
            self.addCleanup(redirected_t.disconnect)
2125
 
            return redirected_t
 
2151
            dir, file = urlutils.split(exception.target)
 
2152
            return self._transport(dir)
2126
2153
 
2127
2154
        stdout = tests.StringIOWrapper()
2128
2155
        stderr = tests.StringIOWrapper()
2149
2176
                                       self.new_server.port)
2150
2177
        self.old_server.redirections = [
2151
2178
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2152
 
        self.assertEqual('redirected once', t._perform(req).read())
 
2179
        self.assertEqual('redirected once',t._perform(req).read())
2153
2180
        # stdin should be empty
2154
2181
        self.assertEqual('', ui.ui_factory.stdin.readline())
2155
2182
        # stdout should be empty, stderr will contains the prompts