~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-05-28 00:25:32 UTC
  • mfrom: (5264.1.2 command-help-bug-177500)
  • Revision ID: pqm@pqm.ubuntu.com-20100528002532-9bzj1fajyxckd1rg
(lifeless) Stop raising at runtime when a command has no help,
 instead have a test in the test suite that checks all known command objects.
 (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
23
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
24
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
25
25
 
 
26
from cStringIO import StringIO
26
27
import httplib
 
28
import os
 
29
import select
27
30
import SimpleHTTPServer
28
31
import socket
29
32
import sys
32
35
import bzrlib
33
36
from bzrlib import (
34
37
    bzrdir,
35
 
    cethread,
36
38
    config,
37
 
    debug,
38
39
    errors,
39
40
    osutils,
40
41
    remote as _mod_remote,
41
42
    tests,
42
 
    trace,
43
43
    transport,
44
44
    ui,
 
45
    urlutils,
 
46
    )
 
47
from bzrlib.symbol_versioning import (
 
48
    deprecated_in,
45
49
    )
46
50
from bzrlib.tests import (
47
51
    features,
48
52
    http_server,
49
53
    http_utils,
50
 
    test_server,
51
 
    )
52
 
from bzrlib.tests.scenarios import (
53
 
    load_tests_apply_scenarios,
54
 
    multiply_scenarios,
55
54
    )
56
55
from bzrlib.transport import (
57
56
    http,
67
66
    from bzrlib.transport.http._pycurl import PyCurlTransport
68
67
 
69
68
 
70
 
load_tests = load_tests_apply_scenarios
71
 
 
72
 
 
73
 
def vary_by_http_client_implementation():
74
 
    """Test the two libraries we can use, pycurl and urllib."""
 
69
def load_tests(standard_tests, module, loader):
 
70
    """Multiply tests for http clients and protocol versions."""
 
71
    result = loader.suiteClass()
 
72
 
 
73
    # one for each transport implementation
 
74
    t_tests, remaining_tests = tests.split_suite_by_condition(
 
75
        standard_tests, tests.condition_isinstance((
 
76
                TestHttpTransportRegistration,
 
77
                TestHttpTransportUrls,
 
78
                Test_redirected_to,
 
79
                )))
75
80
    transport_scenarios = [
76
81
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
77
82
                        _server=http_server.HttpServer_urllib,
78
 
                        _url_protocol='http+urllib',)),
 
83
                        _qualified_prefix='http+urllib',)),
79
84
        ]
80
85
    if features.pycurl.available():
81
86
        transport_scenarios.append(
82
87
            ('pycurl', dict(_transport=PyCurlTransport,
83
88
                            _server=http_server.HttpServer_PyCurl,
84
 
                            _url_protocol='http+pycurl',)))
85
 
    return transport_scenarios
86
 
 
87
 
 
88
 
def vary_by_http_protocol_version():
89
 
    """Test on http/1.0 and 1.1"""
90
 
    return [
91
 
        ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
92
 
        ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
89
                            _qualified_prefix='http+pycurl',)))
 
90
    tests.multiply_tests(t_tests, transport_scenarios, result)
 
91
 
 
92
    # each implementation tested with each HTTP version
 
93
    tp_tests, remaining_tests = tests.split_suite_by_condition(
 
94
        remaining_tests, tests.condition_isinstance((
 
95
                SmartHTTPTunnellingTest,
 
96
                TestDoCatchRedirections,
 
97
                TestHTTPConnections,
 
98
                TestHTTPRedirections,
 
99
                TestHTTPSilentRedirections,
 
100
                TestLimitedRangeRequestServer,
 
101
                TestPost,
 
102
                TestProxyHttpServer,
 
103
                TestRanges,
 
104
                TestSpecificRequestHandler,
 
105
                )))
 
106
    protocol_scenarios = [
 
107
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
 
108
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
109
            ]
 
110
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
 
111
                                            protocol_scenarios)
 
112
    tests.multiply_tests(tp_tests, tp_scenarios, result)
 
113
 
 
114
    # proxy auth: each auth scheme on all http versions on all implementations.
 
115
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
 
116
        remaining_tests, tests.condition_isinstance((
 
117
                TestProxyAuth,
 
118
                )))
 
119
    proxy_auth_scheme_scenarios = [
 
120
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
 
121
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
 
122
        ('basicdigest',
 
123
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
93
124
        ]
94
 
 
95
 
 
96
 
def vary_by_http_auth_scheme():
97
 
    scenarios = [
 
125
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
 
126
                                              proxy_auth_scheme_scenarios)
 
127
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
 
128
 
 
129
    # auth: each auth scheme on all http versions on all implementations.
 
130
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
 
131
        remaining_tests, tests.condition_isinstance((
 
132
                TestAuth,
 
133
                )))
 
134
    auth_scheme_scenarios = [
98
135
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
99
136
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
100
137
        ('basicdigest',
101
 
            dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
102
 
        ]
103
 
    # Add some attributes common to all scenarios
104
 
    for scenario_id, scenario_dict in scenarios:
105
 
        scenario_dict.update(_auth_header='Authorization',
106
 
                             _username_prompt_prefix='',
107
 
                             _password_prompt_prefix='')
108
 
    return scenarios
109
 
 
110
 
 
111
 
def vary_by_http_proxy_auth_scheme():
112
 
    scenarios = [
113
 
        ('proxy-basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
114
 
        ('proxy-digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
115
 
        ('proxy-basicdigest',
116
 
            dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
117
 
        ]
118
 
    # Add some attributes common to all scenarios
119
 
    for scenario_id, scenario_dict in scenarios:
120
 
        scenario_dict.update(_auth_header='Proxy-Authorization',
121
 
                             _username_prompt_prefix='Proxy ',
122
 
                             _password_prompt_prefix='Proxy ')
123
 
    return scenarios
124
 
 
125
 
 
126
 
def vary_by_http_activity():
 
138
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
 
139
        ]
 
140
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
 
141
                                             auth_scheme_scenarios)
 
142
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
 
143
 
 
144
    # activity: on all http[s] versions on all implementations
 
145
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
 
146
        remaining_tests, tests.condition_isinstance((
 
147
                TestActivity,
 
148
                )))
127
149
    activity_scenarios = [
128
150
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
129
 
                            _transport=_urllib.HttpTransport_urllib,)),
 
151
                             _transport=_urllib.HttpTransport_urllib,)),
130
152
        ]
131
153
    if tests.HTTPSServerFeature.available():
132
154
        activity_scenarios.append(
133
155
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
134
 
                                _transport=_urllib.HttpTransport_urllib,)),)
 
156
                                  _transport=_urllib.HttpTransport_urllib,)),)
135
157
    if features.pycurl.available():
136
158
        activity_scenarios.append(
137
159
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
138
 
                                _transport=PyCurlTransport,)),)
 
160
                                 _transport=PyCurlTransport,)),)
139
161
        if tests.HTTPSServerFeature.available():
140
162
            from bzrlib.tests import (
141
163
                ssl_certs,
153
175
 
154
176
            activity_scenarios.append(
155
177
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
156
 
                                    _transport=HTTPS_pycurl_transport,)),)
157
 
    return activity_scenarios
 
178
                                      _transport=HTTPS_pycurl_transport,)),)
 
179
 
 
180
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
 
181
                                               protocol_scenarios)
 
182
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
 
183
 
 
184
    # No parametrization for the remaining tests
 
185
    result.addTests(remaining_tests)
 
186
 
 
187
    return result
158
188
 
159
189
 
160
190
class FakeManager(object):
193
223
        self._sock.bind(('127.0.0.1', 0))
194
224
        self.host, self.port = self._sock.getsockname()
195
225
        self._ready = threading.Event()
196
 
        self._thread = test_server.TestThread(
197
 
            sync_event=self._ready, target=self._accept_read_and_reply)
 
226
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
227
        self._thread.setDaemon(True)
198
228
        self._thread.start()
199
 
        if 'threads' in tests.selftest_debug_flags:
200
 
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
201
 
        self._ready.wait()
 
229
        self._ready.wait(5)
202
230
 
203
231
    def _accept_read_and_reply(self):
204
232
        self._sock.listen(1)
205
233
        self._ready.set()
206
 
        conn, address = self._sock.accept()
207
 
        if self._expect_body_tail is not None:
 
234
        self._sock.settimeout(5)
 
235
        try:
 
236
            conn, address = self._sock.accept()
 
237
            # On win32, the accepted connection will be non-blocking to start
 
238
            # with because we're using settimeout.
 
239
            conn.setblocking(True)
208
240
            while not self.received_bytes.endswith(self._expect_body_tail):
209
241
                self.received_bytes += conn.recv(4096)
210
242
            conn.sendall('HTTP/1.1 200 OK\r\n')
211
 
        try:
 
243
        except socket.timeout:
 
244
            # Make sure the client isn't stuck waiting for us to e.g. accept.
212
245
            self._sock.close()
213
246
        except socket.error:
214
247
            # The client may have already closed the socket.
216
249
 
217
250
    def stop_server(self):
218
251
        try:
219
 
            # Issue a fake connection to wake up the server and allow it to
220
 
            # finish quickly
221
 
            fake_conn = osutils.connect_socket((self.host, self.port))
222
 
            fake_conn.close()
 
252
            self._sock.close()
223
253
        except socket.error:
224
254
            # We might have already closed it.  We don't care.
225
255
            pass
226
256
        self.host = None
227
257
        self.port = None
228
 
        self._thread.join()
229
 
        if 'threads' in tests.selftest_debug_flags:
230
 
            sys.stderr.write('Thread  joined: %s\n' % (self._thread.ident,))
231
258
 
232
259
 
233
260
class TestAuthHeader(tests.TestCase):
269
296
        self.assertEqual('realm="Thou should not pass"', remainder)
270
297
 
271
298
 
272
 
class TestHTTPRangeParsing(tests.TestCase):
273
 
 
274
 
    def setUp(self):
275
 
        super(TestHTTPRangeParsing, self).setUp()
276
 
        # We focus on range  parsing here and ignore everything else
277
 
        class RequestHandler(http_server.TestingHTTPRequestHandler):
278
 
            def setup(self): pass
279
 
            def handle(self): pass
280
 
            def finish(self): pass
281
 
 
282
 
        self.req_handler = RequestHandler(None, None, None)
283
 
 
284
 
    def assertRanges(self, ranges, header, file_size):
285
 
        self.assertEquals(ranges,
286
 
                          self.req_handler._parse_ranges(header, file_size))
287
 
 
288
 
    def test_simple_range(self):
289
 
        self.assertRanges([(0,2)], 'bytes=0-2', 12)
290
 
 
291
 
    def test_tail(self):
292
 
        self.assertRanges([(8, 11)], 'bytes=-4', 12)
293
 
 
294
 
    def test_tail_bigger_than_file(self):
295
 
        self.assertRanges([(0, 11)], 'bytes=-99', 12)
296
 
 
297
 
    def test_range_without_end(self):
298
 
        self.assertRanges([(4, 11)], 'bytes=4-', 12)
299
 
 
300
 
    def test_invalid_ranges(self):
301
 
        self.assertRanges(None, 'bytes=12-22', 12)
302
 
        self.assertRanges(None, 'bytes=1-3,12-22', 12)
303
 
        self.assertRanges(None, 'bytes=-', 12)
304
 
 
305
 
 
306
299
class TestHTTPServer(tests.TestCase):
307
300
    """Test the HTTP servers implementations."""
308
301
 
311
304
 
312
305
            protocol_version = 'HTTP/0.1'
313
306
 
314
 
        self.assertRaises(httplib.UnknownProtocol,
315
 
                          http_server.HttpServer, BogusRequestHandler)
 
307
        server = http_server.HttpServer(BogusRequestHandler)
 
308
        try:
 
309
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
310
        except:
 
311
            server.stop_server()
 
312
            self.fail('HTTP Server creation did not raise UnknownProtocol')
316
313
 
317
314
    def test_force_invalid_protocol(self):
318
 
        self.assertRaises(httplib.UnknownProtocol,
319
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
315
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
316
        try:
 
317
            self.assertRaises(httplib.UnknownProtocol, server.start_server)
 
318
        except:
 
319
            server.stop_server()
 
320
            self.fail('HTTP Server creation did not raise UnknownProtocol')
320
321
 
321
322
    def test_server_start_and_stop(self):
322
323
        server = http_server.HttpServer()
323
 
        self.addCleanup(server.stop_server)
324
324
        server.start_server()
325
 
        self.assertTrue(server.server is not None)
326
 
        self.assertTrue(server.server.serving is not None)
327
 
        self.assertTrue(server.server.serving)
 
325
        try:
 
326
            self.assertTrue(server._http_running)
 
327
        finally:
 
328
            server.stop_server()
 
329
        self.assertFalse(server._http_running)
328
330
 
329
331
    def test_create_http_server_one_zero(self):
330
332
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
333
335
 
334
336
        server = http_server.HttpServer(RequestHandlerOneZero)
335
337
        self.start_server(server)
336
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
338
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
337
339
 
338
340
    def test_create_http_server_one_one(self):
339
341
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
342
344
 
343
345
        server = http_server.HttpServer(RequestHandlerOneOne)
344
346
        self.start_server(server)
345
 
        self.assertIsInstance(server.server,
 
347
        self.assertIsInstance(server._httpd,
346
348
                              http_server.TestingThreadingHTTPServer)
347
349
 
348
350
    def test_create_http_server_force_one_one(self):
353
355
        server = http_server.HttpServer(RequestHandlerOneZero,
354
356
                                        protocol_version='HTTP/1.1')
355
357
        self.start_server(server)
356
 
        self.assertIsInstance(server.server,
 
358
        self.assertIsInstance(server._httpd,
357
359
                              http_server.TestingThreadingHTTPServer)
358
360
 
359
361
    def test_create_http_server_force_one_zero(self):
364
366
        server = http_server.HttpServer(RequestHandlerOneOne,
365
367
                                        protocol_version='HTTP/1.0')
366
368
        self.start_server(server)
367
 
        self.assertIsInstance(server.server,
 
369
        self.assertIsInstance(server._httpd,
368
370
                              http_server.TestingHTTPServer)
369
371
 
370
372
 
399
401
class TestHttpTransportUrls(tests.TestCase):
400
402
    """Test the http urls."""
401
403
 
402
 
    scenarios = vary_by_http_client_implementation()
403
 
 
404
404
    def test_abs_url(self):
405
405
        """Construction of absolute http URLs"""
406
 
        t = self._transport('http://example.com/bzr/bzr.dev/')
 
406
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
407
407
        eq = self.assertEqualDiff
408
 
        eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
409
 
        eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
410
 
        eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
 
408
        eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
 
409
        eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
 
410
        eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
411
411
        eq(t.abspath('.bzr/1//2/./3'),
412
 
           'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
 
412
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
413
413
 
414
414
    def test_invalid_http_urls(self):
415
415
        """Trap invalid construction of urls"""
416
 
        self._transport('http://example.com/bzr/bzr.dev/')
 
416
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
417
417
        self.assertRaises(errors.InvalidURL,
418
418
                          self._transport,
419
 
                          'http://http://example.com/bzr/bzr.dev/')
 
419
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
420
420
 
421
421
    def test_http_root_urls(self):
422
422
        """Construction of URLs from server root"""
423
 
        t = self._transport('http://example.com/')
 
423
        t = self._transport('http://bzr.ozlabs.org/')
424
424
        eq = self.assertEqualDiff
425
425
        eq(t.abspath('.bzr/tree-version'),
426
 
           'http://example.com/.bzr/tree-version')
 
426
           'http://bzr.ozlabs.org/.bzr/tree-version')
427
427
 
428
428
    def test_http_impl_urls(self):
429
429
        """There are servers which ask for particular clients to connect"""
431
431
        server.start_server()
432
432
        try:
433
433
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
434
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
435
        finally:
436
436
            server.stop_server()
437
437
 
475
475
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
476
476
    """Test the http connections."""
477
477
 
478
 
    scenarios = multiply_scenarios(
479
 
        vary_by_http_client_implementation(),
480
 
        vary_by_http_protocol_version(),
481
 
        )
482
 
 
483
478
    def setUp(self):
484
479
        http_utils.TestCaseWithWebserver.setUp(self)
485
480
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
487
482
 
488
483
    def test_http_has(self):
489
484
        server = self.get_readonly_server()
490
 
        t = self.get_readonly_transport()
 
485
        t = self._transport(server.get_url())
491
486
        self.assertEqual(t.has('foo/bar'), True)
492
487
        self.assertEqual(len(server.logs), 1)
493
488
        self.assertContainsRe(server.logs[0],
495
490
 
496
491
    def test_http_has_not_found(self):
497
492
        server = self.get_readonly_server()
498
 
        t = self.get_readonly_transport()
 
493
        t = self._transport(server.get_url())
499
494
        self.assertEqual(t.has('not-found'), False)
500
495
        self.assertContainsRe(server.logs[1],
501
496
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
502
497
 
503
498
    def test_http_get(self):
504
499
        server = self.get_readonly_server()
505
 
        t = self.get_readonly_transport()
 
500
        t = self._transport(server.get_url())
506
501
        fp = t.get('foo/bar')
507
502
        self.assertEqualDiff(
508
503
            fp.read(),
530
525
class TestHttpTransportRegistration(tests.TestCase):
531
526
    """Test registrations of various http implementations"""
532
527
 
533
 
    scenarios = vary_by_http_client_implementation()
534
 
 
535
528
    def test_http_registered(self):
536
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
529
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
537
530
        self.assertIsInstance(t, transport.Transport)
538
531
        self.assertIsInstance(t, self._transport)
539
532
 
540
533
 
541
534
class TestPost(tests.TestCase):
542
535
 
543
 
    scenarios = multiply_scenarios(
544
 
        vary_by_http_client_implementation(),
545
 
        vary_by_http_protocol_version(),
546
 
        )
547
 
 
548
536
    def test_post_body_is_received(self):
549
537
        server = RecordingServer(expect_body_tail='end-of-body',
550
 
                                 scheme=self._url_protocol)
 
538
            scheme=self._qualified_prefix)
551
539
        self.start_server(server)
552
540
        url = server.get_url()
553
 
        # FIXME: needs a cleanup -- vila 20100611
554
 
        http_transport = transport.get_transport(url)
 
541
        http_transport = self._transport(url)
555
542
        code, response = http_transport._post('abc def end-of-body')
556
543
        self.assertTrue(
557
544
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
558
545
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
559
 
        self.assertTrue('content-type: application/octet-stream\r'
560
 
                        in server.received_bytes.lower())
561
546
        # The transport should not be assuming that the server can accept
562
547
        # chunked encoding the first time it connects, because HTTP/1.1, so we
563
548
        # check for the literal string.
599
584
    Daughter classes are expected to override _req_handler_class
600
585
    """
601
586
 
602
 
    scenarios = multiply_scenarios(
603
 
        vary_by_http_client_implementation(),
604
 
        vary_by_http_protocol_version(),
605
 
        )
606
 
 
607
587
    # Provide a useful default
608
588
    _req_handler_class = http_server.TestingHTTPRequestHandler
609
589
 
610
590
    def create_transport_readonly_server(self):
611
 
        server = http_server.HttpServer(self._req_handler_class,
612
 
                                        protocol_version=self._protocol_version)
613
 
        server._url_protocol = self._url_protocol
614
 
        return server
 
591
        return http_server.HttpServer(self._req_handler_class,
 
592
                                      protocol_version=self._protocol_version)
615
593
 
616
594
    def _testing_pycurl(self):
617
595
        # TODO: This is duplicated for lots of the classes in this file
622
600
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
623
601
    """Whatever request comes in, close the connection"""
624
602
 
625
 
    def _handle_one_request(self):
 
603
    def handle_one_request(self):
626
604
        """Handle a single HTTP request, by abruptly closing the connection"""
627
605
        self.close_connection = 1
628
606
 
633
611
    _req_handler_class = WallRequestHandler
634
612
 
635
613
    def test_http_has(self):
636
 
        t = self.get_readonly_transport()
 
614
        server = self.get_readonly_server()
 
615
        t = self._transport(server.get_url())
637
616
        # Unfortunately httplib (see HTTPResponse._read_status
638
617
        # for details) make no distinction between a closed
639
618
        # socket and badly formatted status line, so we can't
645
624
                          t.has, 'foo/bar')
646
625
 
647
626
    def test_http_get(self):
648
 
        t = self.get_readonly_transport()
 
627
        server = self.get_readonly_server()
 
628
        t = self._transport(server.get_url())
649
629
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
650
630
                           errors.InvalidHttpResponse),
651
631
                          t.get, 'foo/bar')
668
648
    _req_handler_class = BadStatusRequestHandler
669
649
 
670
650
    def test_http_has(self):
671
 
        t = self.get_readonly_transport()
 
651
        server = self.get_readonly_server()
 
652
        t = self._transport(server.get_url())
672
653
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
673
654
 
674
655
    def test_http_get(self):
675
 
        t = self.get_readonly_transport()
 
656
        server = self.get_readonly_server()
 
657
        t = self._transport(server.get_url())
676
658
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
677
659
 
678
660
 
683
665
        """Fakes handling a single HTTP request, returns a bad status"""
684
666
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
685
667
        self.wfile.write("Invalid status line\r\n")
686
 
        # If we don't close the connection pycurl will hang. Since this is a
687
 
        # stress test we don't *have* to respect the protocol, but we don't
688
 
        # have to sabotage it too much either.
689
 
        self.close_connection = True
690
668
        return False
691
669
 
692
670
 
698
676
 
699
677
    _req_handler_class = InvalidStatusRequestHandler
700
678
 
 
679
    def test_http_has(self):
 
680
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
681
            raise tests.KnownFailure(
 
682
                'pycurl hangs if the server send back garbage')
 
683
        super(TestInvalidStatusServer, self).test_http_has()
 
684
 
 
685
    def test_http_get(self):
 
686
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
687
            raise tests.KnownFailure(
 
688
                'pycurl hangs if the server send back garbage')
 
689
        super(TestInvalidStatusServer, self).test_http_get()
 
690
 
701
691
 
702
692
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
703
693
    """Whatever request comes in, returns a bad protocol version"""
725
715
        super(TestBadProtocolServer, self).setUp()
726
716
 
727
717
    def test_http_has(self):
728
 
        t = self.get_readonly_transport()
 
718
        server = self.get_readonly_server()
 
719
        t = self._transport(server.get_url())
729
720
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
730
721
 
731
722
    def test_http_get(self):
732
 
        t = self.get_readonly_transport()
 
723
        server = self.get_readonly_server()
 
724
        t = self._transport(server.get_url())
733
725
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
734
726
 
735
727
 
749
741
    _req_handler_class = ForbiddenRequestHandler
750
742
 
751
743
    def test_http_has(self):
752
 
        t = self.get_readonly_transport()
 
744
        server = self.get_readonly_server()
 
745
        t = self._transport(server.get_url())
753
746
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
754
747
 
755
748
    def test_http_get(self):
756
 
        t = self.get_readonly_transport()
 
749
        server = self.get_readonly_server()
 
750
        t = self._transport(server.get_url())
757
751
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
758
752
 
759
753
 
798
792
        self.build_tree_contents([('a', '0123456789')],)
799
793
 
800
794
    def test_readv(self):
801
 
        t = self.get_readonly_transport()
 
795
        server = self.get_readonly_server()
 
796
        t = self._transport(server.get_url())
802
797
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
803
798
        self.assertEqual(l[0], (0, '0'))
804
799
        self.assertEqual(l[1], (1, '1'))
806
801
        self.assertEqual(l[3], (9, '9'))
807
802
 
808
803
    def test_readv_out_of_order(self):
809
 
        t = self.get_readonly_transport()
 
804
        server = self.get_readonly_server()
 
805
        t = self._transport(server.get_url())
810
806
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
811
807
        self.assertEqual(l[0], (1, '1'))
812
808
        self.assertEqual(l[1], (9, '9'))
814
810
        self.assertEqual(l[3], (3, '34'))
815
811
 
816
812
    def test_readv_invalid_ranges(self):
817
 
        t = self.get_readonly_transport()
 
813
        server = self.get_readonly_server()
 
814
        t = self._transport(server.get_url())
818
815
 
819
816
        # This is intentionally reading off the end of the file
820
817
        # since we are sure that it cannot get there
828
825
 
829
826
    def test_readv_multiple_get_requests(self):
830
827
        server = self.get_readonly_server()
831
 
        t = self.get_readonly_transport()
 
828
        t = self._transport(server.get_url())
832
829
        # force transport to issue multiple requests
833
830
        t._max_readv_combine = 1
834
831
        t._max_get_ranges = 1
842
839
 
843
840
    def test_readv_get_max_size(self):
844
841
        server = self.get_readonly_server()
845
 
        t = self.get_readonly_transport()
 
842
        t = self._transport(server.get_url())
846
843
        # force transport to issue multiple requests by limiting the number of
847
844
        # bytes by request. Note that this apply to coalesced offsets only, a
848
845
        # single range will keep its size even if bigger than the limit.
857
854
 
858
855
    def test_complete_readv_leave_pipe_clean(self):
859
856
        server = self.get_readonly_server()
860
 
        t = self.get_readonly_transport()
 
857
        t = self._transport(server.get_url())
861
858
        # force transport to issue multiple requests
862
859
        t._get_max_size = 2
863
 
        list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
 
860
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
864
861
        # The server should have issued 3 requests
865
862
        self.assertEqual(3, server.GET_request_nb)
866
863
        self.assertEqual('0123456789', t.get_bytes('a'))
868
865
 
869
866
    def test_incomplete_readv_leave_pipe_clean(self):
870
867
        server = self.get_readonly_server()
871
 
        t = self.get_readonly_transport()
 
868
        t = self._transport(server.get_url())
872
869
        # force transport to issue multiple requests
873
870
        t._get_max_size = 2
874
871
        # Don't collapse readv results into a list so that we leave unread
943
940
    def get_multiple_ranges(self, file, file_size, ranges):
944
941
        self.send_response(206)
945
942
        self.send_header('Accept-Ranges', 'bytes')
946
 
        # XXX: this is strange; the 'random' name below seems undefined and
947
 
        # yet the tests pass -- mbp 2010-10-11 bug 658773
948
943
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
949
944
        self.send_header("Content-Type",
950
945
                         "multipart/byteranges; boundary=%s" % boundary)
1012
1007
                return
1013
1008
            self.send_range_content(file, start, end - start + 1)
1014
1009
            cur += 1
1015
 
        # Final boundary
 
1010
        # No final boundary
1016
1011
        self.wfile.write(boundary_line)
1017
1012
 
1018
1013
 
1026
1021
 
1027
1022
    def test_readv_with_short_reads(self):
1028
1023
        server = self.get_readonly_server()
1029
 
        t = self.get_readonly_transport()
 
1024
        t = self._transport(server.get_url())
1030
1025
        # Force separate ranges for each offset
1031
1026
        t._bytes_to_read_before_seek = 0
1032
1027
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1047
1042
        # that mode
1048
1043
        self.assertEqual('single', t._range_hint)
1049
1044
 
1050
 
 
1051
1045
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1052
1046
    """Errors out when range specifiers exceed the limit"""
1053
1047
 
1077
1071
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1078
1072
    """Tests readv requests against a server erroring out on too much ranges."""
1079
1073
 
1080
 
    scenarios = multiply_scenarios(
1081
 
        vary_by_http_client_implementation(),
1082
 
        vary_by_http_protocol_version(),
1083
 
        )
1084
 
 
1085
1074
    # Requests with more range specifiers will error out
1086
1075
    range_limit = 3
1087
1076
 
1089
1078
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1090
1079
                                      protocol_version=self._protocol_version)
1091
1080
 
 
1081
    def get_transport(self):
 
1082
        return self._transport(self.get_readonly_server().get_url())
 
1083
 
1092
1084
    def setUp(self):
1093
1085
        http_utils.TestCaseWithWebserver.setUp(self)
1094
1086
        # We need to manipulate ranges that correspond to real chunks in the
1098
1090
        self.build_tree_contents([('a', content)],)
1099
1091
 
1100
1092
    def test_few_ranges(self):
1101
 
        t = self.get_readonly_transport()
 
1093
        t = self.get_transport()
1102
1094
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1103
1095
        self.assertEqual(l[0], (0, '0000'))
1104
1096
        self.assertEqual(l[1], (1024, '0001'))
1105
1097
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1106
1098
 
1107
1099
    def test_more_ranges(self):
1108
 
        t = self.get_readonly_transport()
 
1100
        t = self.get_transport()
1109
1101
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1110
1102
        self.assertEqual(l[0], (0, '0000'))
1111
1103
        self.assertEqual(l[1], (1024, '0001'))
1122
1114
    Only the urllib implementation is tested here.
1123
1115
    """
1124
1116
 
 
1117
    def setUp(self):
 
1118
        tests.TestCase.setUp(self)
 
1119
        self._old_env = {}
 
1120
 
 
1121
    def tearDown(self):
 
1122
        self._restore_env()
 
1123
        tests.TestCase.tearDown(self)
 
1124
 
 
1125
    def _install_env(self, env):
 
1126
        for name, value in env.iteritems():
 
1127
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1128
 
 
1129
    def _restore_env(self):
 
1130
        for name, value in self._old_env.iteritems():
 
1131
            osutils.set_or_unset_env(name, value)
 
1132
 
1125
1133
    def _proxied_request(self):
1126
1134
        handler = _urllib2_wrappers.ProxyHandler()
1127
 
        request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
 
1135
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
1128
1136
        handler.set_proxy(request, 'http')
1129
1137
        return request
1130
1138
 
1131
 
    def assertEvaluateProxyBypass(self, expected, host, no_proxy):
1132
 
        handler = _urllib2_wrappers.ProxyHandler()
1133
 
        self.assertEquals(expected,
1134
 
                          handler.evaluate_proxy_bypass(host, no_proxy))
1135
 
 
1136
1139
    def test_empty_user(self):
1137
 
        self.overrideEnv('http_proxy', 'http://bar.com')
1138
 
        request = self._proxied_request()
1139
 
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1140
 
 
1141
 
    def test_user_with_at(self):
1142
 
        self.overrideEnv('http_proxy',
1143
 
                         'http://username@domain:password@proxy_host:1234')
 
1140
        self._install_env({'http_proxy': 'http://bar.com'})
1144
1141
        request = self._proxied_request()
1145
1142
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1146
1143
 
1147
1144
    def test_invalid_proxy(self):
1148
1145
        """A proxy env variable without scheme"""
1149
 
        self.overrideEnv('http_proxy', 'host:1234')
 
1146
        self._install_env({'http_proxy': 'host:1234'})
1150
1147
        self.assertRaises(errors.InvalidURL, self._proxied_request)
1151
1148
 
1152
 
    def test_evaluate_proxy_bypass_true(self):
1153
 
        """The host is not proxied"""
1154
 
        self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
1155
 
        self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
1156
 
 
1157
 
    def test_evaluate_proxy_bypass_false(self):
1158
 
        """The host is proxied"""
1159
 
        self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
1160
 
 
1161
 
    def test_evaluate_proxy_bypass_unknown(self):
1162
 
        """The host is not explicitly proxied"""
1163
 
        self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
1164
 
        self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
1165
 
 
1166
 
    def test_evaluate_proxy_bypass_empty_entries(self):
1167
 
        """Ignore empty entries"""
1168
 
        self.assertEvaluateProxyBypass(None, 'example.com', '')
1169
 
        self.assertEvaluateProxyBypass(None, 'example.com', ',')
1170
 
        self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
1171
 
 
1172
1149
 
1173
1150
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1174
1151
    """Tests proxy server.
1179
1156
    to the file names).
1180
1157
    """
1181
1158
 
1182
 
    scenarios = multiply_scenarios(
1183
 
        vary_by_http_client_implementation(),
1184
 
        vary_by_http_protocol_version(),
1185
 
        )
1186
 
 
1187
1159
    # FIXME: We don't have an https server available, so we don't
1188
 
    # test https connections. --vila toolongago
 
1160
    # test https connections.
1189
1161
 
1190
1162
    def setUp(self):
1191
1163
        super(TestProxyHttpServer, self).setUp()
1192
 
        self.transport_secondary_server = http_utils.ProxyServer
1193
1164
        self.build_tree_contents([('foo', 'contents of foo\n'),
1194
1165
                                  ('foo-proxied', 'proxied contents of foo\n')])
1195
1166
        # Let's setup some attributes for tests
1196
 
        server = self.get_readonly_server()
1197
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1167
        self.server = self.get_readonly_server()
 
1168
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1198
1169
        if self._testing_pycurl():
1199
1170
            # Oh my ! pycurl does not check for the port as part of
1200
1171
            # no_proxy :-( So we just test the host part
1201
 
            self.no_proxy_host = server.host
 
1172
            self.no_proxy_host = self.server.host
1202
1173
        else:
1203
 
            self.no_proxy_host = self.server_host_port
 
1174
            self.no_proxy_host = self.proxy_address
1204
1175
        # The secondary server is the proxy
1205
 
        self.proxy_url = self.get_secondary_url()
 
1176
        self.proxy = self.get_secondary_server()
 
1177
        self.proxy_url = self.proxy.get_url()
 
1178
        self._old_env = {}
1206
1179
 
1207
1180
    def _testing_pycurl(self):
1208
1181
        # TODO: This is duplicated for lots of the classes in this file
1209
1182
        return (features.pycurl.available()
1210
1183
                and self._transport == PyCurlTransport)
1211
1184
 
1212
 
    def assertProxied(self):
1213
 
        t = self.get_readonly_transport()
1214
 
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1215
 
 
1216
 
    def assertNotProxied(self):
1217
 
        t = self.get_readonly_transport()
1218
 
        self.assertEqual('contents of foo\n', t.get('foo').read())
 
1185
    def create_transport_secondary_server(self):
 
1186
        """Creates an http server that will serve files with
 
1187
        '-proxied' appended to their names.
 
1188
        """
 
1189
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
 
1190
 
 
1191
    def _install_env(self, env):
 
1192
        for name, value in env.iteritems():
 
1193
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1194
 
 
1195
    def _restore_env(self):
 
1196
        for name, value in self._old_env.iteritems():
 
1197
            osutils.set_or_unset_env(name, value)
 
1198
 
 
1199
    def proxied_in_env(self, env):
 
1200
        self._install_env(env)
 
1201
        url = self.server.get_url()
 
1202
        t = self._transport(url)
 
1203
        try:
 
1204
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
 
1205
        finally:
 
1206
            self._restore_env()
 
1207
 
 
1208
    def not_proxied_in_env(self, env):
 
1209
        self._install_env(env)
 
1210
        url = self.server.get_url()
 
1211
        t = self._transport(url)
 
1212
        try:
 
1213
            self.assertEqual('contents of foo\n', t.get('foo').read())
 
1214
        finally:
 
1215
            self._restore_env()
1219
1216
 
1220
1217
    def test_http_proxy(self):
1221
 
        self.overrideEnv('http_proxy', self.proxy_url)
1222
 
        self.assertProxied()
 
1218
        self.proxied_in_env({'http_proxy': self.proxy_url})
1223
1219
 
1224
1220
    def test_HTTP_PROXY(self):
1225
1221
        if self._testing_pycurl():
1228
1224
            # about. Should we ?)
1229
1225
            raise tests.TestNotApplicable(
1230
1226
                'pycurl does not check HTTP_PROXY for security reasons')
1231
 
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1232
 
        self.assertProxied()
 
1227
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1233
1228
 
1234
1229
    def test_all_proxy(self):
1235
 
        self.overrideEnv('all_proxy', self.proxy_url)
1236
 
        self.assertProxied()
 
1230
        self.proxied_in_env({'all_proxy': self.proxy_url})
1237
1231
 
1238
1232
    def test_ALL_PROXY(self):
1239
 
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1240
 
        self.assertProxied()
 
1233
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1241
1234
 
1242
1235
    def test_http_proxy_with_no_proxy(self):
1243
 
        self.overrideEnv('no_proxy', self.no_proxy_host)
1244
 
        self.overrideEnv('http_proxy', self.proxy_url)
1245
 
        self.assertNotProxied()
 
1236
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
 
1237
                                 'no_proxy': self.no_proxy_host})
1246
1238
 
1247
1239
    def test_HTTP_PROXY_with_NO_PROXY(self):
1248
1240
        if self._testing_pycurl():
1249
1241
            raise tests.TestNotApplicable(
1250
1242
                'pycurl does not check HTTP_PROXY for security reasons')
1251
 
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1252
 
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1253
 
        self.assertNotProxied()
 
1243
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
 
1244
                                 'NO_PROXY': self.no_proxy_host})
1254
1245
 
1255
1246
    def test_all_proxy_with_no_proxy(self):
1256
 
        self.overrideEnv('no_proxy', self.no_proxy_host)
1257
 
        self.overrideEnv('all_proxy', self.proxy_url)
1258
 
        self.assertNotProxied()
 
1247
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
 
1248
                                 'no_proxy': self.no_proxy_host})
1259
1249
 
1260
1250
    def test_ALL_PROXY_with_NO_PROXY(self):
1261
 
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1262
 
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1263
 
        self.assertNotProxied()
 
1251
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
 
1252
                                 'NO_PROXY': self.no_proxy_host})
1264
1253
 
1265
1254
    def test_http_proxy_without_scheme(self):
1266
 
        self.overrideEnv('http_proxy', self.server_host_port)
1267
1255
        if self._testing_pycurl():
1268
1256
            # pycurl *ignores* invalid proxy env variables. If that ever change
1269
1257
            # in the future, this test will fail indicating that pycurl do not
1270
1258
            # ignore anymore such variables.
1271
 
            self.assertNotProxied()
 
1259
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1272
1260
        else:
1273
 
            self.assertRaises(errors.InvalidURL, self.assertProxied)
 
1261
            self.assertRaises(errors.InvalidURL,
 
1262
                              self.proxied_in_env,
 
1263
                              {'http_proxy': self.proxy_address})
1274
1264
 
1275
1265
 
1276
1266
class TestRanges(http_utils.TestCaseWithWebserver):
1277
1267
    """Test the Range header in GET methods."""
1278
1268
 
1279
 
    scenarios = multiply_scenarios(
1280
 
        vary_by_http_client_implementation(),
1281
 
        vary_by_http_protocol_version(),
1282
 
        )
1283
 
 
1284
1269
    def setUp(self):
1285
1270
        http_utils.TestCaseWithWebserver.setUp(self)
1286
1271
        self.build_tree_contents([('a', '0123456789')],)
 
1272
        server = self.get_readonly_server()
 
1273
        self.transport = self._transport(server.get_url())
1287
1274
 
1288
1275
    def create_transport_readonly_server(self):
1289
1276
        return http_server.HttpServer(protocol_version=self._protocol_version)
1290
1277
 
1291
1278
    def _file_contents(self, relpath, ranges):
1292
 
        t = self.get_readonly_transport()
1293
1279
        offsets = [ (start, end - start + 1) for start, end in ranges]
1294
 
        coalesce = t._coalesce_offsets
 
1280
        coalesce = self.transport._coalesce_offsets
1295
1281
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1296
 
        code, data = t._get(relpath, coalesced)
 
1282
        code, data = self.transport._get(relpath, coalesced)
1297
1283
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1298
1284
        for start, end in ranges:
1299
1285
            data.seek(start)
1300
1286
            yield data.read(end - start + 1)
1301
1287
 
1302
1288
    def _file_tail(self, relpath, tail_amount):
1303
 
        t = self.get_readonly_transport()
1304
 
        code, data = t._get(relpath, [], tail_amount)
 
1289
        code, data = self.transport._get(relpath, [], tail_amount)
1305
1290
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1306
1291
        data.seek(-tail_amount, 2)
1307
1292
        return data.read(tail_amount)
1326
1311
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1327
1312
    """Test redirection between http servers."""
1328
1313
 
1329
 
    scenarios = multiply_scenarios(
1330
 
        vary_by_http_client_implementation(),
1331
 
        vary_by_http_protocol_version(),
1332
 
        )
 
1314
    def create_transport_secondary_server(self):
 
1315
        """Create the secondary server redirecting to the primary server"""
 
1316
        new = self.get_readonly_server()
 
1317
 
 
1318
        redirecting = http_utils.HTTPServerRedirecting(
 
1319
            protocol_version=self._protocol_version)
 
1320
        redirecting.redirect_to(new.host, new.port)
 
1321
        return redirecting
1333
1322
 
1334
1323
    def setUp(self):
1335
1324
        super(TestHTTPRedirections, self).setUp()
1337
1326
                                  ('bundle',
1338
1327
                                  '# Bazaar revision bundle v0.9\n#\n')
1339
1328
                                  ],)
 
1329
        # The requests to the old server will be redirected to the new server
 
1330
        self.old_transport = self._transport(self.old_server.get_url())
1340
1331
 
1341
1332
    def test_redirected(self):
1342
 
        self.assertRaises(errors.RedirectRequested,
1343
 
                          self.get_old_transport().get, 'a')
1344
 
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
 
1333
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1334
        t = self._transport(self.new_server.get_url())
 
1335
        self.assertEqual('0123456789', t.get('a').read())
 
1336
 
 
1337
    def test_read_redirected_bundle_from_url(self):
 
1338
        from bzrlib.bundle import read_bundle_from_url
 
1339
        url = self.old_transport.abspath('bundle')
 
1340
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
 
1341
                read_bundle_from_url, url)
 
1342
        # If read_bundle_from_url was successful we get an empty bundle
 
1343
        self.assertEqual([], bundle.revisions)
1345
1344
 
1346
1345
 
1347
1346
class RedirectedRequest(_urllib2_wrappers.Request):
1364
1363
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1365
1364
 
1366
1365
 
1367
 
def cleanup_http_redirection_connections(test):
1368
 
    # Some sockets are opened but never seen by _urllib, so we trap them at
1369
 
    # the _urllib2_wrappers level to be able to clean them up.
1370
 
    def socket_disconnect(sock):
1371
 
        try:
1372
 
            sock.shutdown(socket.SHUT_RDWR)
1373
 
            sock.close()
1374
 
        except socket.error:
1375
 
            pass
1376
 
    def connect(connection):
1377
 
        test.http_connect_orig(connection)
1378
 
        test.addCleanup(socket_disconnect, connection.sock)
1379
 
    test.http_connect_orig = test.overrideAttr(
1380
 
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1381
 
    def connect(connection):
1382
 
        test.https_connect_orig(connection)
1383
 
        test.addCleanup(socket_disconnect, connection.sock)
1384
 
    test.https_connect_orig = test.overrideAttr(
1385
 
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1386
 
 
1387
 
 
1388
1366
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1389
1367
    """Test redirections.
1390
1368
 
1399
1377
    -- vila 20070212
1400
1378
    """
1401
1379
 
1402
 
    scenarios = multiply_scenarios(
1403
 
        vary_by_http_client_implementation(),
1404
 
        vary_by_http_protocol_version(),
1405
 
        )
1406
 
 
1407
1380
    def setUp(self):
1408
1381
        if (features.pycurl.available()
1409
1382
            and self._transport == PyCurlTransport):
1410
1383
            raise tests.TestNotApplicable(
1411
 
                "pycurl doesn't redirect silently anymore")
 
1384
                "pycurl doesn't redirect silently annymore")
1412
1385
        super(TestHTTPSilentRedirections, self).setUp()
1413
1386
        install_redirected_request(self)
1414
 
        cleanup_http_redirection_connections(self)
1415
1387
        self.build_tree_contents([('a','a'),
1416
1388
                                  ('1/',),
1417
1389
                                  ('1/a', 'redirected once'),
1425
1397
                                  ('5/a', 'redirected 5 times'),
1426
1398
                                  ],)
1427
1399
 
 
1400
        self.old_transport = self._transport(self.old_server.get_url())
 
1401
 
 
1402
    def create_transport_secondary_server(self):
 
1403
        """Create the secondary server, redirections are defined in the tests"""
 
1404
        return http_utils.HTTPServerRedirecting(
 
1405
            protocol_version=self._protocol_version)
 
1406
 
1428
1407
    def test_one_redirection(self):
1429
 
        t = self.get_old_transport()
1430
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1408
        t = self.old_transport
 
1409
 
 
1410
        req = RedirectedRequest('GET', t.abspath('a'))
1431
1411
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1432
1412
                                       self.new_server.port)
1433
1413
        self.old_server.redirections = \
1434
1414
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1435
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1415
        self.assertEqual('redirected once',t._perform(req).read())
1436
1416
 
1437
1417
    def test_five_redirections(self):
1438
 
        t = self.get_old_transport()
1439
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1418
        t = self.old_transport
 
1419
 
 
1420
        req = RedirectedRequest('GET', t.abspath('a'))
1440
1421
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1441
1422
                                       self.old_server.port)
1442
1423
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1448
1429
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1449
1430
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1450
1431
            ]
1451
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1432
        self.assertEqual('redirected 5 times',t._perform(req).read())
1452
1433
 
1453
1434
 
1454
1435
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1455
1436
    """Test transport.do_catching_redirections."""
1456
1437
 
1457
 
    scenarios = multiply_scenarios(
1458
 
        vary_by_http_client_implementation(),
1459
 
        vary_by_http_protocol_version(),
1460
 
        )
1461
 
 
1462
1438
    def setUp(self):
1463
1439
        super(TestDoCatchRedirections, self).setUp()
1464
1440
        self.build_tree_contents([('a', '0123456789'),],)
1465
 
        cleanup_http_redirection_connections(self)
1466
 
 
1467
 
        self.old_transport = self.get_old_transport()
1468
 
 
1469
 
    def get_a(self, t):
1470
 
        return t.get('a')
 
1441
 
 
1442
        self.old_transport = self._transport(self.old_server.get_url())
 
1443
 
 
1444
    def get_a(self, transport):
 
1445
        return transport.get('a')
1471
1446
 
1472
1447
    def test_no_redirection(self):
1473
 
        t = self.get_new_transport()
 
1448
        t = self._transport(self.new_server.get_url())
1474
1449
 
1475
1450
        # We use None for redirected so that we fail if redirected
1476
1451
        self.assertEqual('0123456789',
1480
1455
    def test_one_redirection(self):
1481
1456
        self.redirections = 0
1482
1457
 
1483
 
        def redirected(t, exception, redirection_notice):
 
1458
        def redirected(transport, exception, redirection_notice):
1484
1459
            self.redirections += 1
1485
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1486
 
            return redirected_t
 
1460
            dir, file = urlutils.split(exception.target)
 
1461
            return self._transport(dir)
1487
1462
 
1488
1463
        self.assertEqual('0123456789',
1489
1464
                         transport.do_catching_redirections(
1503
1478
                          self.get_a, self.old_transport, redirected)
1504
1479
 
1505
1480
 
1506
 
def _setup_authentication_config(**kwargs):
1507
 
    conf = config.AuthenticationConfig()
1508
 
    conf._get_config().update({'httptest': kwargs})
1509
 
    conf._save()
1510
 
 
1511
 
 
1512
 
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
1513
 
    """Unit tests for glue by which urllib2 asks us for authentication"""
1514
 
 
1515
 
    def test_get_user_password_without_port(self):
1516
 
        """We cope if urllib2 doesn't tell us the port.
1517
 
 
1518
 
        See https://bugs.launchpad.net/bzr/+bug/654684
1519
 
        """
1520
 
        user = 'joe'
1521
 
        password = 'foo'
1522
 
        _setup_authentication_config(scheme='http', host='localhost',
1523
 
                                     user=user, password=password)
1524
 
        handler = _urllib2_wrappers.HTTPAuthHandler()
1525
 
        got_pass = handler.get_user_password(dict(
1526
 
            user='joe',
1527
 
            protocol='http',
1528
 
            host='localhost',
1529
 
            path='/',
1530
 
            realm='Realm',
1531
 
            ))
1532
 
        self.assertEquals((user, password), got_pass)
1533
 
 
1534
 
 
1535
1481
class TestAuth(http_utils.TestCaseWithWebserver):
1536
1482
    """Test authentication scheme"""
1537
1483
 
1538
 
    scenarios = multiply_scenarios(
1539
 
        vary_by_http_client_implementation(),
1540
 
        vary_by_http_protocol_version(),
1541
 
        vary_by_http_auth_scheme(),
1542
 
        )
 
1484
    _auth_header = 'Authorization'
 
1485
    _password_prompt_prefix = ''
 
1486
    _username_prompt_prefix = ''
 
1487
    # Set by load_tests
 
1488
    _auth_server = None
1543
1489
 
1544
1490
    def setUp(self):
1545
1491
        super(TestAuth, self).setUp()
1548
1494
                                  ('b', 'contents of b\n'),])
1549
1495
 
1550
1496
    def create_transport_readonly_server(self):
1551
 
        server = self._auth_server(protocol_version=self._protocol_version)
1552
 
        server._url_protocol = self._url_protocol
1553
 
        return server
 
1497
        return self._auth_server(protocol_version=self._protocol_version)
1554
1498
 
1555
1499
    def _testing_pycurl(self):
1556
1500
        # TODO: This is duplicated for lots of the classes in this file
1569
1513
        return url
1570
1514
 
1571
1515
    def get_user_transport(self, user, password):
1572
 
        t = transport.get_transport(self.get_user_url(user, password))
1573
 
        return t
 
1516
        return self._transport(self.get_user_url(user, password))
1574
1517
 
1575
1518
    def test_no_user(self):
1576
1519
        self.server.add_user('joe', 'foo')
1687
1630
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1688
1631
                                            stderr=tests.StringIOWrapper())
1689
1632
        # Create a minimal config file with the right password
1690
 
        _setup_authentication_config(scheme='http', port=self.server.port,
1691
 
                                     user=user, password=password)
 
1633
        conf = config.AuthenticationConfig()
 
1634
        conf._get_config().update(
 
1635
            {'httptest': {'scheme': 'http', 'port': self.server.port,
 
1636
                          'user': user, 'password': password}})
 
1637
        conf._save()
1692
1638
        # Issue a request to the server to connect
1693
1639
        self.assertEqual('contents of a\n',t.get('a').read())
1694
1640
        # stdin should have  been left untouched
1696
1642
        # Only one 'Authentication Required' error should occur
1697
1643
        self.assertEqual(1, self.server.auth_required_errors)
1698
1644
 
 
1645
    def test_user_from_auth_conf(self):
 
1646
        if self._testing_pycurl():
 
1647
            raise tests.TestNotApplicable(
 
1648
                'pycurl does not support authentication.conf')
 
1649
        user = 'joe'
 
1650
        password = 'foo'
 
1651
        self.server.add_user(user, password)
 
1652
        # Create a minimal config file with the right password
 
1653
        conf = config.AuthenticationConfig()
 
1654
        conf._get_config().update(
 
1655
            {'httptest': {'scheme': 'http', 'port': self.server.port,
 
1656
                          'user': user, 'password': password}})
 
1657
        conf._save()
 
1658
        t = self.get_user_transport(None, None)
 
1659
        # Issue a request to the server to connect
 
1660
        self.assertEqual('contents of a\n', t.get('a').read())
 
1661
        # Only one 'Authentication Required' error should occur
 
1662
        self.assertEqual(1, self.server.auth_required_errors)
 
1663
 
1699
1664
    def test_changing_nonce(self):
1700
1665
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1701
1666
                                     http_utils.ProxyDigestAuthServer):
1717
1682
        # initial 'who are you' and a second 'who are you' with the new nonce)
1718
1683
        self.assertEqual(2, self.server.auth_required_errors)
1719
1684
 
1720
 
    def test_user_from_auth_conf(self):
1721
 
        if self._testing_pycurl():
1722
 
            raise tests.TestNotApplicable(
1723
 
                'pycurl does not support authentication.conf')
1724
 
        user = 'joe'
1725
 
        password = 'foo'
1726
 
        self.server.add_user(user, password)
1727
 
        _setup_authentication_config(scheme='http', port=self.server.port,
1728
 
                                     user=user, password=password)
1729
 
        t = self.get_user_transport(None, None)
1730
 
        # Issue a request to the server to connect
1731
 
        self.assertEqual('contents of a\n', t.get('a').read())
1732
 
        # Only one 'Authentication Required' error should occur
1733
 
        self.assertEqual(1, self.server.auth_required_errors)
1734
 
 
1735
 
    def test_no_credential_leaks_in_log(self):
1736
 
        self.overrideAttr(debug, 'debug_flags', set(['http']))
1737
 
        user = 'joe'
1738
 
        password = 'very-sensitive-password'
1739
 
        self.server.add_user(user, password)
1740
 
        t = self.get_user_transport(user, password)
1741
 
        # Capture the debug calls to mutter
1742
 
        self.mutters = []
1743
 
        def mutter(*args):
1744
 
            lines = args[0] % args[1:]
1745
 
            # Some calls output multiple lines, just split them now since we
1746
 
            # care about a single one later.
1747
 
            self.mutters.extend(lines.splitlines())
1748
 
        self.overrideAttr(trace, 'mutter', mutter)
1749
 
        # Issue a request to the server to connect
1750
 
        self.assertEqual(True, t.has('a'))
1751
 
        # Only one 'Authentication Required' error should occur
1752
 
        self.assertEqual(1, self.server.auth_required_errors)
1753
 
        # Since the authentification succeeded, there should be a corresponding
1754
 
        # debug line
1755
 
        sent_auth_headers = [line for line in self.mutters
1756
 
                             if line.startswith('> %s' % (self._auth_header,))]
1757
 
        self.assertLength(1, sent_auth_headers)
1758
 
        self.assertStartsWith(sent_auth_headers[0],
1759
 
                              '> %s: <masked>' % (self._auth_header,))
1760
1685
 
1761
1686
 
1762
1687
class TestProxyAuth(TestAuth):
1763
 
    """Test proxy authentication schemes.
1764
 
 
1765
 
    This inherits from TestAuth to tweak the setUp and filter some failing
1766
 
    tests.
1767
 
    """
1768
 
 
1769
 
    scenarios = multiply_scenarios(
1770
 
        vary_by_http_client_implementation(),
1771
 
        vary_by_http_protocol_version(),
1772
 
        vary_by_http_proxy_auth_scheme(),
1773
 
        )
 
1688
    """Test proxy authentication schemes."""
 
1689
 
 
1690
    _auth_header = 'Proxy-authorization'
 
1691
    _password_prompt_prefix = 'Proxy '
 
1692
    _username_prompt_prefix = 'Proxy '
1774
1693
 
1775
1694
    def setUp(self):
1776
1695
        super(TestProxyAuth, self).setUp()
 
1696
        self._old_env = {}
 
1697
        self.addCleanup(self._restore_env)
1777
1698
        # Override the contents to avoid false positives
1778
1699
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1779
1700
                                  ('b', 'not proxied contents of b\n'),
1782
1703
                                  ])
1783
1704
 
1784
1705
    def get_user_transport(self, user, password):
1785
 
        self.overrideEnv('all_proxy', self.get_user_url(user, password))
1786
 
        return TestAuth.get_user_transport(self, user, password)
 
1706
        self._install_env({'all_proxy': self.get_user_url(user, password)})
 
1707
        return self._transport(self.server.get_url())
 
1708
 
 
1709
    def _install_env(self, env):
 
1710
        for name, value in env.iteritems():
 
1711
            self._old_env[name] = osutils.set_or_unset_env(name, value)
 
1712
 
 
1713
    def _restore_env(self):
 
1714
        for name, value in self._old_env.iteritems():
 
1715
            osutils.set_or_unset_env(name, value)
1787
1716
 
1788
1717
    def test_empty_pass(self):
1789
1718
        if self._testing_pycurl():
1808
1737
        self.readfile = StringIO(socket_read_content)
1809
1738
        self.writefile = StringIO()
1810
1739
        self.writefile.close = lambda: None
1811
 
        self.close = lambda: None
1812
1740
 
1813
1741
    def makefile(self, mode='r', bufsize=None):
1814
1742
        if 'r' in mode:
1819
1747
 
1820
1748
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1821
1749
 
1822
 
    scenarios = multiply_scenarios(
1823
 
        vary_by_http_client_implementation(),
1824
 
        vary_by_http_protocol_version(),
1825
 
        )
1826
 
 
1827
1750
    def setUp(self):
1828
1751
        super(SmartHTTPTunnellingTest, self).setUp()
1829
1752
        # We use the VFS layer as part of HTTP tunnelling tests.
1830
 
        self.overrideEnv('BZR_NO_SMART_VFS', None)
 
1753
        self._captureVar('BZR_NO_SMART_VFS', None)
1831
1754
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1832
 
        self.http_server = self.get_readonly_server()
1833
1755
 
1834
1756
    def create_transport_readonly_server(self):
1835
 
        server = http_utils.HTTPServerWithSmarts(
 
1757
        return http_utils.HTTPServerWithSmarts(
1836
1758
            protocol_version=self._protocol_version)
1837
 
        server._url_protocol = self._url_protocol
1838
 
        return server
1839
1759
 
1840
1760
    def test_open_bzrdir(self):
1841
1761
        branch = self.make_branch('relpath')
1842
 
        url = self.http_server.get_url() + 'relpath'
 
1762
        http_server = self.get_readonly_server()
 
1763
        url = http_server.get_url() + 'relpath'
1843
1764
        bd = bzrdir.BzrDir.open(url)
1844
 
        self.addCleanup(bd.transport.disconnect)
1845
1765
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1846
1766
 
1847
1767
    def test_bulk_data(self):
1849
1769
        # The 'readv' command in the smart protocol both sends and receives
1850
1770
        # bulk data, so we use that.
1851
1771
        self.build_tree(['data-file'])
1852
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1772
        http_server = self.get_readonly_server()
 
1773
        http_transport = self._transport(http_server.get_url())
1853
1774
        medium = http_transport.get_smart_medium()
1854
1775
        # Since we provide the medium, the url below will be mostly ignored
1855
1776
        # during the test, as long as the path is '/'.
1863
1784
        post_body = 'hello\n'
1864
1785
        expected_reply_body = 'ok\x012\n'
1865
1786
 
1866
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1787
        http_server = self.get_readonly_server()
 
1788
        http_transport = self._transport(http_server.get_url())
1867
1789
        medium = http_transport.get_smart_medium()
1868
1790
        response = medium.send_http_smart_request(post_body)
1869
1791
        reply_body = response.read()
1870
1792
        self.assertEqual(expected_reply_body, reply_body)
1871
1793
 
1872
1794
    def test_smart_http_server_post_request_handler(self):
1873
 
        httpd = self.http_server.server
 
1795
        httpd = self.get_readonly_server()._get_httpd()
1874
1796
 
1875
1797
        socket = SampleSocket(
1876
1798
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1908
1830
 
1909
1831
    def test_probe_smart_server(self):
1910
1832
        """Test error handling against server refusing smart requests."""
1911
 
        t = self.get_readonly_transport()
 
1833
        server = self.get_readonly_server()
 
1834
        t = self._transport(server.get_url())
1912
1835
        # No need to build a valid smart request here, the server will not even
1913
1836
        # try to interpret it.
1914
1837
        self.assertRaises(errors.SmartProtocolError,
1915
1838
                          t.get_smart_medium().send_http_smart_request,
1916
1839
                          'whatever')
1917
1840
 
1918
 
 
1919
1841
class Test_redirected_to(tests.TestCase):
1920
1842
 
1921
 
    scenarios = vary_by_http_client_implementation()
1922
 
 
1923
1843
    def test_redirected_to_subdir(self):
1924
1844
        t = self._transport('http://www.example.com/foo')
1925
1845
        r = t._redirected_to('http://www.example.com/foo',
1976
1896
    line.
1977
1897
    """
1978
1898
 
1979
 
    def _handle_one_request(self):
 
1899
    def handle_one_request(self):
1980
1900
        tcs = self.server.test_case_server
1981
1901
        requestline = self.rfile.readline()
1982
1902
        headers = self.MessageClass(self.rfile, 0)
2037
1957
        tests.TestCase.setUp(self)
2038
1958
        self.server = self._activity_server(self._protocol_version)
2039
1959
        self.server.start_server()
2040
 
        _activities = {} # Don't close over self and create a cycle
 
1960
        self.activities = {}
2041
1961
        def report_activity(t, bytes, direction):
2042
 
            count = _activities.get(direction, 0)
 
1962
            count = self.activities.get(direction, 0)
2043
1963
            count += bytes
2044
 
            _activities[direction] = count
2045
 
        self.activities = _activities
 
1964
            self.activities[direction] = count
2046
1965
 
2047
1966
        # We override at class level because constructors may propagate the
2048
1967
        # bound method and render instance overriding ineffective (an
2049
1968
        # alternative would be to define a specific ui factory instead...)
2050
 
        self.overrideAttr(self._transport, '_report_activity', report_activity)
2051
 
        self.addCleanup(self.server.stop_server)
 
1969
        self.orig_report_activity = self._transport._report_activity
 
1970
        self._transport._report_activity = report_activity
 
1971
 
 
1972
    def tearDown(self):
 
1973
        self._transport._report_activity = self.orig_report_activity
 
1974
        self.server.stop_server()
 
1975
        tests.TestCase.tearDown(self)
2052
1976
 
2053
1977
    def get_transport(self):
2054
 
        t = self._transport(self.server.get_url())
2055
 
        # FIXME: Needs cleanup -- vila 20100611
2056
 
        return t
 
1978
        return self._transport(self.server.get_url())
2057
1979
 
2058
1980
    def assertActivitiesMatch(self):
2059
1981
        self.assertEqual(self.server.bytes_read,
2164
2086
'''
2165
2087
        t = self.get_transport()
2166
2088
        # We must send a single line of body bytes, see
2167
 
        # PredefinedRequestHandler._handle_one_request
 
2089
        # PredefinedRequestHandler.handle_one_request
2168
2090
        code, f = t._post('abc def end-of-body\n')
2169
2091
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2170
2092
        self.assertActivitiesMatch()
2172
2094
 
2173
2095
class TestActivity(tests.TestCase, TestActivityMixin):
2174
2096
 
2175
 
    scenarios = multiply_scenarios(
2176
 
        vary_by_http_activity(),
2177
 
        vary_by_http_protocol_version(),
2178
 
        )
2179
 
 
2180
2097
    def setUp(self):
2181
 
        TestActivityMixin.setUp(self)
 
2098
        tests.TestCase.setUp(self)
 
2099
        self.server = self._activity_server(self._protocol_version)
 
2100
        self.server.start_server()
 
2101
        self.activities = {}
 
2102
        def report_activity(t, bytes, direction):
 
2103
            count = self.activities.get(direction, 0)
 
2104
            count += bytes
 
2105
            self.activities[direction] = count
 
2106
 
 
2107
        # We override at class level because constructors may propagate the
 
2108
        # bound method and render instance overriding ineffective (an
 
2109
        # alternative would be to define a specific ui factory instead...)
 
2110
        self.orig_report_activity = self._transport._report_activity
 
2111
        self._transport._report_activity = report_activity
 
2112
 
 
2113
    def tearDown(self):
 
2114
        self._transport._report_activity = self.orig_report_activity
 
2115
        self.server.stop_server()
 
2116
        tests.TestCase.tearDown(self)
2182
2117
 
2183
2118
 
2184
2119
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2185
2120
 
2186
 
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2187
 
    # ReportingSocket, so we don't need all the parametrization. Since
2188
 
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2189
 
    # test them through their use by the transport than directly (that's a
2190
 
    # bit less clean but far more simpler and effective).
2191
 
    _activity_server = ActivityHTTPServer
2192
 
    _protocol_version = 'HTTP/1.1'
2193
 
 
2194
2121
    def setUp(self):
2195
 
        self._transport =_urllib.HttpTransport_urllib
2196
 
        TestActivityMixin.setUp(self)
 
2122
        tests.TestCase.setUp(self)
 
2123
        # Unlike TestActivity, we are really testing ReportingFileSocket and
 
2124
        # ReportingSocket, so we don't need all the parametrization. Since
 
2125
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
 
2126
        # test them through their use by the transport than directly (that's a
 
2127
        # bit less clean but far more simpler and effective).
 
2128
        self.server = ActivityHTTPServer('HTTP/1.1')
 
2129
        self._transport=_urllib.HttpTransport_urllib
 
2130
 
 
2131
        self.server.start_server()
 
2132
 
 
2133
        # We override at class level because constructors may propagate the
 
2134
        # bound method and render instance overriding ineffective (an
 
2135
        # alternative would be to define a specific ui factory instead...)
 
2136
        self.orig_report_activity = self._transport._report_activity
 
2137
        self._transport._report_activity = None
 
2138
 
 
2139
    def tearDown(self):
 
2140
        self._transport._report_activity = self.orig_report_activity
 
2141
        self.server.stop_server()
 
2142
        tests.TestCase.tearDown(self)
2197
2143
 
2198
2144
    def assertActivitiesMatch(self):
2199
2145
        # Nothing to check here
2203
2149
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2204
2150
    """Test authentication on the redirected http server."""
2205
2151
 
2206
 
    scenarios = vary_by_http_protocol_version()
2207
 
 
2208
2152
    _auth_header = 'Authorization'
2209
2153
    _password_prompt_prefix = ''
2210
2154
    _username_prompt_prefix = ''
2211
2155
    _auth_server = http_utils.HTTPBasicAuthServer
2212
2156
    _transport = _urllib.HttpTransport_urllib
2213
2157
 
 
2158
    def create_transport_readonly_server(self):
 
2159
        return self._auth_server()
 
2160
 
 
2161
    def create_transport_secondary_server(self):
 
2162
        """Create the secondary server redirecting to the primary server"""
 
2163
        new = self.get_readonly_server()
 
2164
 
 
2165
        redirecting = http_utils.HTTPServerRedirecting()
 
2166
        redirecting.redirect_to(new.host, new.port)
 
2167
        return redirecting
 
2168
 
2214
2169
    def setUp(self):
2215
2170
        super(TestAuthOnRedirected, self).setUp()
2216
2171
        self.build_tree_contents([('a','a'),
2221
2176
                                       self.new_server.port)
2222
2177
        self.old_server.redirections = [
2223
2178
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2224
 
        self.old_transport = self.get_old_transport()
 
2179
        self.old_transport = self._transport(self.old_server.get_url())
2225
2180
        self.new_server.add_user('joe', 'foo')
2226
 
        cleanup_http_redirection_connections(self)
2227
 
 
2228
 
    def create_transport_readonly_server(self):
2229
 
        server = self._auth_server(protocol_version=self._protocol_version)
2230
 
        server._url_protocol = self._url_protocol
2231
 
        return server
2232
 
 
2233
 
    def get_a(self, t):
2234
 
        return t.get('a')
 
2181
 
 
2182
    def get_a(self, transport):
 
2183
        return transport.get('a')
2235
2184
 
2236
2185
    def test_auth_on_redirected_via_do_catching_redirections(self):
2237
2186
        self.redirections = 0
2238
2187
 
2239
 
        def redirected(t, exception, redirection_notice):
 
2188
        def redirected(transport, exception, redirection_notice):
2240
2189
            self.redirections += 1
2241
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2242
 
            self.addCleanup(redirected_t.disconnect)
2243
 
            return redirected_t
 
2190
            dir, file = urlutils.split(exception.target)
 
2191
            return self._transport(dir)
2244
2192
 
2245
2193
        stdout = tests.StringIOWrapper()
2246
2194
        stderr = tests.StringIOWrapper()
2267
2215
                                       self.new_server.port)
2268
2216
        self.old_server.redirections = [
2269
2217
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2270
 
        self.assertEqual('redirected once', t._perform(req).read())
 
2218
        self.assertEqual('redirected once',t._perform(req).read())
2271
2219
        # stdin should be empty
2272
2220
        self.assertEqual('', ui.ui_factory.stdin.readline())
2273
2221
        # stdout should be empty, stderr will contains the prompts
2274
2222
        self.assertEqual('', stdout.getvalue())
2275
2223
 
 
2224