~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Martin
  • Date: 2010-07-04 07:09:09 UTC
  • mto: This revision was merged to the branch mainline in revision 5333.
  • Revision ID: gzlist@googlemail.com-20100704070909-r51s2leny0wjcqtn
Use same timestamp rounding logic as Inno, just in case

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