~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Vincent Ladeuil
  • Date: 2009-04-27 16:10:10 UTC
  • mto: (4310.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4311.
  • Revision ID: v.ladeuil+lp@free.fr-20090427161010-7swfzeagf63cpixd
Fix bug #367726 by reverting some default user handling introduced
while fixing bug #256612.

* bzrlib/transport/ssh.py:
(_paramiko_auth): Explicitly use getpass.getuser() as default
user.

* bzrlib/transport/ftp/_gssapi.py:
(GSSAPIFtpTransport._create_connection): Explicitly use
getpass.getuser() as default user.

* bzrlib/transport/ftp/__init__.py:
(FtpTransport._create_connection): Explicitly use
getpass.getuser() as default user.

* bzrlib/tests/test_sftp_transport.py:
(TestUsesAuthConfig.test_sftp_is_none_if_no_config)
(TestUsesAuthConfig.test_sftp_doesnt_prompt_username): Revert to
None as the default user.

* bzrlib/tests/test_remote.py:
(TestRemoteSSHTransportAuthentication): The really offending one:
revert to None as the default user.

* bzrlib/tests/test_config.py:
(TestAuthenticationConfig.test_username_default_no_prompt): Update
test (and some PEP8).

* bzrlib/smtp_connection.py:
(SMTPConnection._authenticate): Revert to None as the default
user.

* bzrlib/plugins/launchpad/account.py:
(_get_auth_user): Revert default value handling.

* bzrlib/config.py:
(AuthenticationConfig.get_user): Fix doc-string. Leave default
value handling to callers.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
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
 
    features,
49
51
    http_server,
50
52
    http_utils,
51
 
    test_server,
52
53
    )
53
54
from bzrlib.transport import (
54
55
    http,
60
61
    )
61
62
 
62
63
 
63
 
if features.pycurl.available():
 
64
try:
64
65
    from bzrlib.transport.http._pycurl import PyCurlTransport
 
66
    pycurl_present = True
 
67
except errors.DependencyNotPresent:
 
68
    pycurl_present = False
65
69
 
66
70
 
67
71
def load_tests(standard_tests, module, loader):
78
82
    transport_scenarios = [
79
83
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
80
84
                        _server=http_server.HttpServer_urllib,
81
 
                        _url_protocol='http+urllib',)),
 
85
                        _qualified_prefix='http+urllib',)),
82
86
        ]
83
 
    if features.pycurl.available():
 
87
    if pycurl_present:
84
88
        transport_scenarios.append(
85
89
            ('pycurl', dict(_transport=PyCurlTransport,
86
90
                            _server=http_server.HttpServer_PyCurl,
87
 
                            _url_protocol='http+pycurl',)))
 
91
                            _qualified_prefix='http+pycurl',)))
88
92
    tests.multiply_tests(t_tests, transport_scenarios, result)
89
93
 
90
 
    protocol_scenarios = [
91
 
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
92
 
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
93
 
            ]
94
 
 
95
 
    # some tests are parametrized by the protocol version only
96
 
    p_tests, remaining_tests = tests.split_suite_by_condition(
97
 
        remaining_tests, tests.condition_isinstance((
98
 
                TestAuthOnRedirected,
99
 
                )))
100
 
    tests.multiply_tests(p_tests, protocol_scenarios, result)
101
 
 
102
94
    # each implementation tested with each HTTP version
103
95
    tp_tests, remaining_tests = tests.split_suite_by_condition(
104
96
        remaining_tests, tests.condition_isinstance((
113
105
                TestRanges,
114
106
                TestSpecificRequestHandler,
115
107
                )))
 
108
    protocol_scenarios = [
 
109
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
 
110
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
 
111
            ]
116
112
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
117
113
                                            protocol_scenarios)
118
114
    tests.multiply_tests(tp_tests, tp_scenarios, result)
119
115
 
120
 
    # proxy auth: each auth scheme on all http versions on all implementations.
121
 
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
122
 
        remaining_tests, tests.condition_isinstance((
123
 
                TestProxyAuth,
124
 
                )))
125
 
    proxy_auth_scheme_scenarios = [
126
 
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
127
 
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
128
 
        ('basicdigest',
129
 
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
130
 
        ]
131
 
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
132
 
                                              proxy_auth_scheme_scenarios)
133
 
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
134
 
 
135
116
    # auth: each auth scheme on all http versions on all implementations.
136
117
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
137
118
        remaining_tests, tests.condition_isinstance((
138
119
                TestAuth,
139
120
                )))
140
121
    auth_scheme_scenarios = [
141
 
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
142
 
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
143
 
        ('basicdigest',
144
 
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
 
122
        ('basic', dict(_auth_scheme='basic')),
 
123
        ('digest', dict(_auth_scheme='digest')),
145
124
        ]
146
125
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
147
 
                                             auth_scheme_scenarios)
 
126
        auth_scheme_scenarios)
148
127
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
149
128
 
150
 
    # activity: on all http[s] versions on all implementations
 
129
    # activity: activity on all http versions on all implementations
151
130
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
152
131
        remaining_tests, tests.condition_isinstance((
153
132
                TestActivity,
154
133
                )))
155
134
    activity_scenarios = [
156
 
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
157
 
                             _transport=_urllib.HttpTransport_urllib,)),
 
135
        ('http', dict(_activity_server=ActivityHTTPServer)),
158
136
        ]
159
137
    if tests.HTTPSServerFeature.available():
160
138
        activity_scenarios.append(
161
 
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
162
 
                                  _transport=_urllib.HttpTransport_urllib,)),)
163
 
    if features.pycurl.available():
164
 
        activity_scenarios.append(
165
 
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
166
 
                                 _transport=PyCurlTransport,)),)
167
 
        if tests.HTTPSServerFeature.available():
168
 
            from bzrlib.tests import (
169
 
                ssl_certs,
170
 
                )
171
 
            # FIXME: Until we have a better way to handle self-signed
172
 
            # certificates (like allowing them in a test specific
173
 
            # authentication.conf for example), we need some specialized pycurl
174
 
            # transport for tests.
175
 
            class HTTPS_pycurl_transport(PyCurlTransport):
176
 
 
177
 
                def __init__(self, base, _from_transport=None):
178
 
                    super(HTTPS_pycurl_transport, self).__init__(
179
 
                        base, _from_transport)
180
 
                    self.cabundle = str(ssl_certs.build_path('ca.crt'))
181
 
 
182
 
            activity_scenarios.append(
183
 
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
184
 
                                      _transport=HTTPS_pycurl_transport,)),)
185
 
 
186
 
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
187
 
                                               protocol_scenarios)
 
139
            ('https', dict(_activity_server=ActivityHTTPSServer)))
 
140
    tpact_scenarios = tests.multiply_scenarios(tp_scenarios,
 
141
        activity_scenarios)
188
142
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
189
143
 
190
144
    # No parametrization for the remaining tests
208
162
    It records the bytes sent to it, and replies with a 200.
209
163
    """
210
164
 
211
 
    def __init__(self, expect_body_tail=None, scheme=''):
 
165
    def __init__(self, expect_body_tail=None):
212
166
        """Constructor.
213
167
 
214
168
        :type expect_body_tail: str
219
173
        self.host = None
220
174
        self.port = None
221
175
        self.received_bytes = ''
222
 
        self.scheme = scheme
223
 
 
224
 
    def get_url(self):
225
 
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
226
 
 
227
 
    def start_server(self):
 
176
 
 
177
    def setUp(self):
228
178
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
229
179
        self._sock.bind(('127.0.0.1', 0))
230
180
        self.host, self.port = self._sock.getsockname()
231
181
        self._ready = threading.Event()
232
 
        self._thread = test_server.ThreadWithException(
233
 
            event=self._ready, target=self._accept_read_and_reply)
 
182
        self._thread = threading.Thread(target=self._accept_read_and_reply)
 
183
        self._thread.setDaemon(True)
234
184
        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()
 
185
        self._ready.wait(5)
238
186
 
239
187
    def _accept_read_and_reply(self):
240
188
        self._sock.listen(1)
241
189
        self._ready.set()
242
 
        conn, address = self._sock.accept()
243
 
        if self._expect_body_tail is not None:
 
190
        self._sock.settimeout(5)
 
191
        try:
 
192
            conn, address = self._sock.accept()
 
193
            # On win32, the accepted connection will be non-blocking to start
 
194
            # with because we're using settimeout.
 
195
            conn.setblocking(True)
244
196
            while not self.received_bytes.endswith(self._expect_body_tail):
245
197
                self.received_bytes += conn.recv(4096)
246
198
            conn.sendall('HTTP/1.1 200 OK\r\n')
247
 
        try:
 
199
        except socket.timeout:
 
200
            # Make sure the client isn't stuck waiting for us to e.g. accept.
248
201
            self._sock.close()
249
202
        except socket.error:
250
203
            # The client may have already closed the socket.
251
204
            pass
252
205
 
253
 
    def stop_server(self):
 
206
    def tearDown(self):
254
207
        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()
 
208
            self._sock.close()
259
209
        except socket.error:
260
210
            # We might have already closed it.  We don't care.
261
211
            pass
262
212
        self.host = None
263
213
        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
214
 
268
215
 
269
216
class TestAuthHeader(tests.TestCase):
276
223
 
277
224
    def test_empty_header(self):
278
225
        scheme, remainder = self.parse_header('')
279
 
        self.assertEqual('', scheme)
 
226
        self.assertEquals('', scheme)
280
227
        self.assertIs(None, remainder)
281
228
 
282
229
    def test_negotiate_header(self):
283
230
        scheme, remainder = self.parse_header('Negotiate')
284
 
        self.assertEqual('negotiate', scheme)
 
231
        self.assertEquals('negotiate', scheme)
285
232
        self.assertIs(None, remainder)
286
233
 
287
234
    def test_basic_header(self):
288
235
        scheme, remainder = self.parse_header(
289
236
            'Basic realm="Thou should not pass"')
290
 
        self.assertEqual('basic', scheme)
291
 
        self.assertEqual('realm="Thou should not pass"', remainder)
 
237
        self.assertEquals('basic', scheme)
 
238
        self.assertEquals('realm="Thou should not pass"', remainder)
292
239
 
293
240
    def test_basic_extract_realm(self):
294
241
        scheme, remainder = self.parse_header(
296
243
            _urllib2_wrappers.BasicAuthHandler)
297
244
        match, realm = self.auth_handler.extract_realm(remainder)
298
245
        self.assertTrue(match is not None)
299
 
        self.assertEqual('Thou should not pass', realm)
 
246
        self.assertEquals('Thou should not pass', realm)
300
247
 
301
248
    def test_digest_header(self):
302
249
        scheme, remainder = self.parse_header(
303
250
            'Digest realm="Thou should not pass"')
304
 
        self.assertEqual('digest', scheme)
305
 
        self.assertEqual('realm="Thou should not pass"', remainder)
 
251
        self.assertEquals('digest', scheme)
 
252
        self.assertEquals('realm="Thou should not pass"', remainder)
306
253
 
307
254
 
308
255
class TestHTTPServer(tests.TestCase):
313
260
 
314
261
            protocol_version = 'HTTP/0.1'
315
262
 
316
 
        self.assertRaises(httplib.UnknownProtocol,
317
 
                          http_server.HttpServer, BogusRequestHandler)
 
263
        server = http_server.HttpServer(BogusRequestHandler)
 
264
        try:
 
265
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
266
        except:
 
267
            server.tearDown()
 
268
            self.fail('HTTP Server creation did not raise UnknownProtocol')
318
269
 
319
270
    def test_force_invalid_protocol(self):
320
 
        self.assertRaises(httplib.UnknownProtocol,
321
 
                          http_server.HttpServer, protocol_version='HTTP/0.1')
 
271
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
 
272
        try:
 
273
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
 
274
        except:
 
275
            server.tearDown()
 
276
            self.fail('HTTP Server creation did not raise UnknownProtocol')
322
277
 
323
278
    def test_server_start_and_stop(self):
324
279
        server = http_server.HttpServer()
325
 
        self.addCleanup(server.stop_server)
326
 
        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)
 
280
        server.setUp()
 
281
        self.assertTrue(server._http_running)
 
282
        server.tearDown()
 
283
        self.assertFalse(server._http_running)
330
284
 
331
285
    def test_create_http_server_one_zero(self):
332
286
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
334
288
            protocol_version = 'HTTP/1.0'
335
289
 
336
290
        server = http_server.HttpServer(RequestHandlerOneZero)
337
 
        self.start_server(server)
338
 
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
 
291
        server.setUp()
 
292
        self.addCleanup(server.tearDown)
 
293
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
339
294
 
340
295
    def test_create_http_server_one_one(self):
341
296
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
343
298
            protocol_version = 'HTTP/1.1'
344
299
 
345
300
        server = http_server.HttpServer(RequestHandlerOneOne)
346
 
        self.start_server(server)
347
 
        self.assertIsInstance(server.server,
 
301
        server.setUp()
 
302
        self.addCleanup(server.tearDown)
 
303
        self.assertIsInstance(server._httpd,
348
304
                              http_server.TestingThreadingHTTPServer)
349
305
 
350
306
    def test_create_http_server_force_one_one(self):
354
310
 
355
311
        server = http_server.HttpServer(RequestHandlerOneZero,
356
312
                                        protocol_version='HTTP/1.1')
357
 
        self.start_server(server)
358
 
        self.assertIsInstance(server.server,
 
313
        server.setUp()
 
314
        self.addCleanup(server.tearDown)
 
315
        self.assertIsInstance(server._httpd,
359
316
                              http_server.TestingThreadingHTTPServer)
360
317
 
361
318
    def test_create_http_server_force_one_zero(self):
365
322
 
366
323
        server = http_server.HttpServer(RequestHandlerOneOne,
367
324
                                        protocol_version='HTTP/1.0')
368
 
        self.start_server(server)
369
 
        self.assertIsInstance(server.server,
 
325
        server.setUp()
 
326
        self.addCleanup(server.tearDown)
 
327
        self.assertIsInstance(server._httpd,
370
328
                              http_server.TestingHTTPServer)
371
329
 
372
330
 
374
332
    """Test case to inherit from if pycurl is present"""
375
333
 
376
334
    def _get_pycurl_maybe(self):
377
 
        self.requireFeature(features.pycurl)
378
 
        return PyCurlTransport
 
335
        try:
 
336
            from bzrlib.transport.http._pycurl import PyCurlTransport
 
337
            return PyCurlTransport
 
338
        except errors.DependencyNotPresent:
 
339
            raise tests.TestSkipped('pycurl not present')
379
340
 
380
341
    _transport = property(_get_pycurl_maybe)
381
342
 
388
349
    def test_url_parsing(self):
389
350
        f = FakeManager()
390
351
        url = http.extract_auth('http://example.com', f)
391
 
        self.assertEqual('http://example.com', url)
392
 
        self.assertEqual(0, len(f.credentials))
 
352
        self.assertEquals('http://example.com', url)
 
353
        self.assertEquals(0, len(f.credentials))
393
354
        url = http.extract_auth(
394
 
            'http://user:pass@example.com/bzr/bzr.dev', f)
395
 
        self.assertEqual('http://example.com/bzr/bzr.dev', url)
396
 
        self.assertEqual(1, len(f.credentials))
397
 
        self.assertEqual([None, 'example.com', 'user', 'pass'],
398
 
                         f.credentials[0])
 
355
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
 
356
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
 
357
        self.assertEquals(1, len(f.credentials))
 
358
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
 
359
                          f.credentials[0])
399
360
 
400
361
 
401
362
class TestHttpTransportUrls(tests.TestCase):
428
389
    def test_http_impl_urls(self):
429
390
        """There are servers which ask for particular clients to connect"""
430
391
        server = self._server()
431
 
        server.start_server()
432
392
        try:
 
393
            server.setUp()
433
394
            url = server.get_url()
434
 
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
 
395
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
435
396
        finally:
436
 
            server.stop_server()
 
397
            server.tearDown()
437
398
 
438
399
 
439
400
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
448
409
        https by supplying a fake version_info that do not
449
410
        support it.
450
411
        """
451
 
        self.requireFeature(features.pycurl)
452
 
        # Import the module locally now that we now it's available.
453
 
        pycurl = features.pycurl.module
 
412
        try:
 
413
            import pycurl
 
414
        except ImportError:
 
415
            raise tests.TestSkipped('pycurl not present')
454
416
 
455
 
        self.overrideAttr(pycurl, 'version_info',
456
 
                          # Fake the pycurl version_info This was taken from
457
 
                          # a windows pycurl without SSL (thanks to bialix)
458
 
                          lambda : (2,
459
 
                                    '7.13.2',
460
 
                                    462082,
461
 
                                    'i386-pc-win32',
462
 
                                    2576,
463
 
                                    None,
464
 
                                    0,
465
 
                                    None,
466
 
                                    ('ftp', 'gopher', 'telnet',
467
 
                                     'dict', 'ldap', 'http', 'file'),
468
 
                                    None,
469
 
                                    0,
470
 
                                    None))
471
 
        self.assertRaises(errors.DependencyNotPresent, self._transport,
472
 
                          'https://launchpad.net')
 
417
        version_info_orig = pycurl.version_info
 
418
        try:
 
419
            # Now that we have pycurl imported, we can fake its version_info
 
420
            # This was taken from a windows pycurl without SSL
 
421
            # (thanks to bialix)
 
422
            pycurl.version_info = lambda : (2,
 
423
                                            '7.13.2',
 
424
                                            462082,
 
425
                                            'i386-pc-win32',
 
426
                                            2576,
 
427
                                            None,
 
428
                                            0,
 
429
                                            None,
 
430
                                            ('ftp', 'gopher', 'telnet',
 
431
                                             'dict', 'ldap', 'http', 'file'),
 
432
                                            None,
 
433
                                            0,
 
434
                                            None)
 
435
            self.assertRaises(errors.DependencyNotPresent, self._transport,
 
436
                              'https://launchpad.net')
 
437
        finally:
 
438
            # Restore the right function
 
439
            pycurl.version_info = version_info_orig
473
440
 
474
441
 
475
442
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
482
449
 
483
450
    def test_http_has(self):
484
451
        server = self.get_readonly_server()
485
 
        t = self.get_readonly_transport()
 
452
        t = self._transport(server.get_url())
486
453
        self.assertEqual(t.has('foo/bar'), True)
487
454
        self.assertEqual(len(server.logs), 1)
488
455
        self.assertContainsRe(server.logs[0],
490
457
 
491
458
    def test_http_has_not_found(self):
492
459
        server = self.get_readonly_server()
493
 
        t = self.get_readonly_transport()
 
460
        t = self._transport(server.get_url())
494
461
        self.assertEqual(t.has('not-found'), False)
495
462
        self.assertContainsRe(server.logs[1],
496
463
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
497
464
 
498
465
    def test_http_get(self):
499
466
        server = self.get_readonly_server()
500
 
        t = self.get_readonly_transport()
 
467
        t = self._transport(server.get_url())
501
468
        fp = t.get('foo/bar')
502
469
        self.assertEqualDiff(
503
470
            fp.read(),
526
493
    """Test registrations of various http implementations"""
527
494
 
528
495
    def test_http_registered(self):
529
 
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
 
496
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
530
497
        self.assertIsInstance(t, transport.Transport)
531
498
        self.assertIsInstance(t, self._transport)
532
499
 
534
501
class TestPost(tests.TestCase):
535
502
 
536
503
    def test_post_body_is_received(self):
537
 
        server = RecordingServer(expect_body_tail='end-of-body',
538
 
                                 scheme=self._url_protocol)
539
 
        self.start_server(server)
540
 
        url = server.get_url()
541
 
        # FIXME: needs a cleanup -- vila 20100611
542
 
        http_transport = transport.get_transport(url)
 
504
        server = RecordingServer(expect_body_tail='end-of-body')
 
505
        server.setUp()
 
506
        self.addCleanup(server.tearDown)
 
507
        scheme = self._qualified_prefix
 
508
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
 
509
        http_transport = self._transport(url)
543
510
        code, response = http_transport._post('abc def end-of-body')
544
511
        self.assertTrue(
545
512
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
589
556
    _req_handler_class = http_server.TestingHTTPRequestHandler
590
557
 
591
558
    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
 
559
        return http_server.HttpServer(self._req_handler_class,
 
560
                                      protocol_version=self._protocol_version)
596
561
 
597
562
    def _testing_pycurl(self):
598
 
        # TODO: This is duplicated for lots of the classes in this file
599
 
        return (features.pycurl.available()
600
 
                and self._transport == PyCurlTransport)
 
563
        return pycurl_present and self._transport == PyCurlTransport
601
564
 
602
565
 
603
566
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
604
567
    """Whatever request comes in, close the connection"""
605
568
 
606
 
    def _handle_one_request(self):
 
569
    def handle_one_request(self):
607
570
        """Handle a single HTTP request, by abruptly closing the connection"""
608
571
        self.close_connection = 1
609
572
 
614
577
    _req_handler_class = WallRequestHandler
615
578
 
616
579
    def test_http_has(self):
617
 
        t = self.get_readonly_transport()
 
580
        server = self.get_readonly_server()
 
581
        t = self._transport(server.get_url())
618
582
        # Unfortunately httplib (see HTTPResponse._read_status
619
583
        # for details) make no distinction between a closed
620
584
        # socket and badly formatted status line, so we can't
621
585
        # just test for ConnectionError, we have to test
622
 
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
623
 
        # instead of ConnectionError too.
624
 
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
625
 
                            errors.InvalidHttpResponse),
 
586
        # InvalidHttpResponse too.
 
587
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
626
588
                          t.has, 'foo/bar')
627
589
 
628
590
    def test_http_get(self):
629
 
        t = self.get_readonly_transport()
630
 
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
631
 
                           errors.InvalidHttpResponse),
 
591
        server = self.get_readonly_server()
 
592
        t = self._transport(server.get_url())
 
593
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
632
594
                          t.get, 'foo/bar')
633
595
 
634
596
 
649
611
    _req_handler_class = BadStatusRequestHandler
650
612
 
651
613
    def test_http_has(self):
652
 
        t = self.get_readonly_transport()
 
614
        server = self.get_readonly_server()
 
615
        t = self._transport(server.get_url())
653
616
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
654
617
 
655
618
    def test_http_get(self):
656
 
        t = self.get_readonly_transport()
 
619
        server = self.get_readonly_server()
 
620
        t = self._transport(server.get_url())
657
621
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
658
622
 
659
623
 
664
628
        """Fakes handling a single HTTP request, returns a bad status"""
665
629
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
666
630
        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
631
        return False
672
632
 
673
633
 
679
639
 
680
640
    _req_handler_class = InvalidStatusRequestHandler
681
641
 
 
642
    def test_http_has(self):
 
643
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
644
            raise tests.KnownFailure(
 
645
                'pycurl hangs if the server send back garbage')
 
646
        super(TestInvalidStatusServer, self).test_http_has()
 
647
 
 
648
    def test_http_get(self):
 
649
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
 
650
            raise tests.KnownFailure(
 
651
                'pycurl hangs if the server send back garbage')
 
652
        super(TestInvalidStatusServer, self).test_http_get()
 
653
 
682
654
 
683
655
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
684
656
    """Whatever request comes in, returns a bad protocol version"""
700
672
    _req_handler_class = BadProtocolRequestHandler
701
673
 
702
674
    def setUp(self):
703
 
        if self._testing_pycurl():
 
675
        if pycurl_present and self._transport == PyCurlTransport:
704
676
            raise tests.TestNotApplicable(
705
677
                "pycurl doesn't check the protocol version")
706
678
        super(TestBadProtocolServer, self).setUp()
707
679
 
708
680
    def test_http_has(self):
709
 
        t = self.get_readonly_transport()
 
681
        server = self.get_readonly_server()
 
682
        t = self._transport(server.get_url())
710
683
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
711
684
 
712
685
    def test_http_get(self):
713
 
        t = self.get_readonly_transport()
 
686
        server = self.get_readonly_server()
 
687
        t = self._transport(server.get_url())
714
688
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
715
689
 
716
690
 
730
704
    _req_handler_class = ForbiddenRequestHandler
731
705
 
732
706
    def test_http_has(self):
733
 
        t = self.get_readonly_transport()
 
707
        server = self.get_readonly_server()
 
708
        t = self._transport(server.get_url())
734
709
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
735
710
 
736
711
    def test_http_get(self):
737
 
        t = self.get_readonly_transport()
 
712
        server = self.get_readonly_server()
 
713
        t = self._transport(server.get_url())
738
714
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
739
715
 
740
716
 
746
722
        self.assertEqual(None, server.host)
747
723
        self.assertEqual(None, server.port)
748
724
 
749
 
    def test_setUp_and_stop(self):
 
725
    def test_setUp_and_tearDown(self):
750
726
        server = RecordingServer(expect_body_tail=None)
751
 
        server.start_server()
 
727
        server.setUp()
752
728
        try:
753
729
            self.assertNotEqual(None, server.host)
754
730
            self.assertNotEqual(None, server.port)
755
731
        finally:
756
 
            server.stop_server()
 
732
            server.tearDown()
757
733
        self.assertEqual(None, server.host)
758
734
        self.assertEqual(None, server.port)
759
735
 
760
736
    def test_send_receive_bytes(self):
761
 
        server = RecordingServer(expect_body_tail='c', scheme='http')
762
 
        self.start_server(server)
 
737
        server = RecordingServer(expect_body_tail='c')
 
738
        server.setUp()
 
739
        self.addCleanup(server.tearDown)
763
740
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
764
741
        sock.connect((server.host, server.port))
765
742
        sock.sendall('abc')
779
756
        self.build_tree_contents([('a', '0123456789')],)
780
757
 
781
758
    def test_readv(self):
782
 
        t = self.get_readonly_transport()
 
759
        server = self.get_readonly_server()
 
760
        t = self._transport(server.get_url())
783
761
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
784
762
        self.assertEqual(l[0], (0, '0'))
785
763
        self.assertEqual(l[1], (1, '1'))
787
765
        self.assertEqual(l[3], (9, '9'))
788
766
 
789
767
    def test_readv_out_of_order(self):
790
 
        t = self.get_readonly_transport()
 
768
        server = self.get_readonly_server()
 
769
        t = self._transport(server.get_url())
791
770
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
792
771
        self.assertEqual(l[0], (1, '1'))
793
772
        self.assertEqual(l[1], (9, '9'))
795
774
        self.assertEqual(l[3], (3, '34'))
796
775
 
797
776
    def test_readv_invalid_ranges(self):
798
 
        t = self.get_readonly_transport()
 
777
        server = self.get_readonly_server()
 
778
        t = self._transport(server.get_url())
799
779
 
800
780
        # This is intentionally reading off the end of the file
801
781
        # since we are sure that it cannot get there
809
789
 
810
790
    def test_readv_multiple_get_requests(self):
811
791
        server = self.get_readonly_server()
812
 
        t = self.get_readonly_transport()
 
792
        t = self._transport(server.get_url())
813
793
        # force transport to issue multiple requests
814
794
        t._max_readv_combine = 1
815
795
        t._max_get_ranges = 1
823
803
 
824
804
    def test_readv_get_max_size(self):
825
805
        server = self.get_readonly_server()
826
 
        t = self.get_readonly_transport()
 
806
        t = self._transport(server.get_url())
827
807
        # force transport to issue multiple requests by limiting the number of
828
808
        # bytes by request. Note that this apply to coalesced offsets only, a
829
809
        # single range will keep its size even if bigger than the limit.
838
818
 
839
819
    def test_complete_readv_leave_pipe_clean(self):
840
820
        server = self.get_readonly_server()
841
 
        t = self.get_readonly_transport()
 
821
        t = self._transport(server.get_url())
842
822
        # force transport to issue multiple requests
843
823
        t._get_max_size = 2
844
824
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
849
829
 
850
830
    def test_incomplete_readv_leave_pipe_clean(self):
851
831
        server = self.get_readonly_server()
852
 
        t = self.get_readonly_transport()
 
832
        t = self._transport(server.get_url())
853
833
        # force transport to issue multiple requests
854
834
        t._get_max_size = 2
855
835
        # Don't collapse readv results into a list so that we leave unread
1005
985
 
1006
986
    def test_readv_with_short_reads(self):
1007
987
        server = self.get_readonly_server()
1008
 
        t = self.get_readonly_transport()
 
988
        t = self._transport(server.get_url())
1009
989
        # Force separate ranges for each offset
1010
990
        t._bytes_to_read_before_seek = 0
1011
991
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1062
1042
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1063
1043
                                      protocol_version=self._protocol_version)
1064
1044
 
 
1045
    def get_transport(self):
 
1046
        return self._transport(self.get_readonly_server().get_url())
 
1047
 
1065
1048
    def setUp(self):
1066
1049
        http_utils.TestCaseWithWebserver.setUp(self)
1067
1050
        # We need to manipulate ranges that correspond to real chunks in the
1071
1054
        self.build_tree_contents([('a', content)],)
1072
1055
 
1073
1056
    def test_few_ranges(self):
1074
 
        t = self.get_readonly_transport()
 
1057
        t = self.get_transport()
1075
1058
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1076
1059
        self.assertEqual(l[0], (0, '0000'))
1077
1060
        self.assertEqual(l[1], (1024, '0001'))
1078
1061
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1079
1062
 
1080
1063
    def test_more_ranges(self):
1081
 
        t = self.get_readonly_transport()
 
1064
        t = self.get_transport()
1082
1065
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1083
1066
        self.assertEqual(l[0], (0, '0000'))
1084
1067
        self.assertEqual(l[1], (1024, '0001'))
1098
1081
    def setUp(self):
1099
1082
        tests.TestCase.setUp(self)
1100
1083
        self._old_env = {}
1101
 
        self.addCleanup(self._restore_env)
 
1084
 
 
1085
    def tearDown(self):
 
1086
        self._restore_env()
 
1087
        tests.TestCase.tearDown(self)
1102
1088
 
1103
1089
    def _install_env(self, env):
1104
1090
        for name, value in env.iteritems():
1135
1121
    """
1136
1122
 
1137
1123
    # FIXME: We don't have an https server available, so we don't
1138
 
    # test https connections. --vila toolongago
 
1124
    # test https connections.
1139
1125
 
1140
1126
    def setUp(self):
1141
1127
        super(TestProxyHttpServer, self).setUp()
1142
 
        self.transport_secondary_server = http_utils.ProxyServer
1143
1128
        self.build_tree_contents([('foo', 'contents of foo\n'),
1144
1129
                                  ('foo-proxied', 'proxied contents of foo\n')])
1145
1130
        # Let's setup some attributes for tests
1146
 
        server = self.get_readonly_server()
1147
 
        self.server_host_port = '%s:%d' % (server.host, server.port)
 
1131
        self.server = self.get_readonly_server()
 
1132
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
1148
1133
        if self._testing_pycurl():
1149
1134
            # Oh my ! pycurl does not check for the port as part of
1150
1135
            # no_proxy :-( So we just test the host part
1151
 
            self.no_proxy_host = server.host
 
1136
            self.no_proxy_host = 'localhost'
1152
1137
        else:
1153
 
            self.no_proxy_host = self.server_host_port
 
1138
            self.no_proxy_host = self.proxy_address
1154
1139
        # The secondary server is the proxy
1155
 
        self.proxy_url = self.get_secondary_url()
 
1140
        self.proxy = self.get_secondary_server()
 
1141
        self.proxy_url = self.proxy.get_url()
1156
1142
        self._old_env = {}
1157
1143
 
1158
1144
    def _testing_pycurl(self):
1159
 
        # TODO: This is duplicated for lots of the classes in this file
1160
 
        return (features.pycurl.available()
1161
 
                and self._transport == PyCurlTransport)
 
1145
        return pycurl_present and self._transport == PyCurlTransport
 
1146
 
 
1147
    def create_transport_secondary_server(self):
 
1148
        """Creates an http server that will serve files with
 
1149
        '-proxied' appended to their names.
 
1150
        """
 
1151
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
1162
1152
 
1163
1153
    def _install_env(self, env):
1164
1154
        for name, value in env.iteritems():
1170
1160
 
1171
1161
    def proxied_in_env(self, env):
1172
1162
        self._install_env(env)
1173
 
        t = self.get_readonly_transport()
 
1163
        url = self.server.get_url()
 
1164
        t = self._transport(url)
1174
1165
        try:
1175
1166
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1176
1167
        finally:
1178
1169
 
1179
1170
    def not_proxied_in_env(self, env):
1180
1171
        self._install_env(env)
1181
 
        t = self.get_readonly_transport()
 
1172
        url = self.server.get_url()
 
1173
        t = self._transport(url)
1182
1174
        try:
1183
1175
            self.assertEqual('contents of foo\n', t.get('foo').read())
1184
1176
        finally:
1226
1218
            # pycurl *ignores* invalid proxy env variables. If that ever change
1227
1219
            # in the future, this test will fail indicating that pycurl do not
1228
1220
            # ignore anymore such variables.
1229
 
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
 
1221
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
1230
1222
        else:
1231
1223
            self.assertRaises(errors.InvalidURL,
1232
1224
                              self.proxied_in_env,
1233
 
                              {'http_proxy': self.server_host_port})
 
1225
                              {'http_proxy': self.proxy_address})
1234
1226
 
1235
1227
 
1236
1228
class TestRanges(http_utils.TestCaseWithWebserver):
1239
1231
    def setUp(self):
1240
1232
        http_utils.TestCaseWithWebserver.setUp(self)
1241
1233
        self.build_tree_contents([('a', '0123456789')],)
 
1234
        server = self.get_readonly_server()
 
1235
        self.transport = self._transport(server.get_url())
1242
1236
 
1243
1237
    def create_transport_readonly_server(self):
1244
1238
        return http_server.HttpServer(protocol_version=self._protocol_version)
1245
1239
 
1246
1240
    def _file_contents(self, relpath, ranges):
1247
 
        t = self.get_readonly_transport()
1248
1241
        offsets = [ (start, end - start + 1) for start, end in ranges]
1249
 
        coalesce = t._coalesce_offsets
 
1242
        coalesce = self.transport._coalesce_offsets
1250
1243
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1251
 
        code, data = t._get(relpath, coalesced)
 
1244
        code, data = self.transport._get(relpath, coalesced)
1252
1245
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1253
1246
        for start, end in ranges:
1254
1247
            data.seek(start)
1255
1248
            yield data.read(end - start + 1)
1256
1249
 
1257
1250
    def _file_tail(self, relpath, tail_amount):
1258
 
        t = self.get_readonly_transport()
1259
 
        code, data = t._get(relpath, [], tail_amount)
 
1251
        code, data = self.transport._get(relpath, [], tail_amount)
1260
1252
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1261
1253
        data.seek(-tail_amount, 2)
1262
1254
        return data.read(tail_amount)
1281
1273
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1282
1274
    """Test redirection between http servers."""
1283
1275
 
 
1276
    def create_transport_secondary_server(self):
 
1277
        """Create the secondary server redirecting to the primary server"""
 
1278
        new = self.get_readonly_server()
 
1279
 
 
1280
        redirecting = http_utils.HTTPServerRedirecting(
 
1281
            protocol_version=self._protocol_version)
 
1282
        redirecting.redirect_to(new.host, new.port)
 
1283
        return redirecting
 
1284
 
1284
1285
    def setUp(self):
1285
1286
        super(TestHTTPRedirections, self).setUp()
1286
1287
        self.build_tree_contents([('a', '0123456789'),
1287
1288
                                  ('bundle',
1288
1289
                                  '# Bazaar revision bundle v0.9\n#\n')
1289
1290
                                  ],)
 
1291
        # The requests to the old server will be redirected to the new server
 
1292
        self.old_transport = self._transport(self.old_server.get_url())
1290
1293
 
1291
1294
    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())
 
1295
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
 
1296
        t = self._transport(self.new_server.get_url())
 
1297
        self.assertEqual('0123456789', t.get('a').read())
 
1298
 
 
1299
    def test_read_redirected_bundle_from_url(self):
 
1300
        from bzrlib.bundle import read_bundle_from_url
 
1301
        url = self.old_transport.abspath('bundle')
 
1302
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
 
1303
                read_bundle_from_url, url)
 
1304
        # If read_bundle_from_url was successful we get an empty bundle
 
1305
        self.assertEqual([], bundle.revisions)
1295
1306
 
1296
1307
 
1297
1308
class RedirectedRequest(_urllib2_wrappers.Request):
1310
1321
        self.follow_redirections = True
1311
1322
 
1312
1323
 
1313
 
def install_redirected_request(test):
1314
 
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
1315
 
 
1316
 
 
1317
 
def cleanup_http_redirection_connections(test):
1318
 
    # Some sockets are opened but never seen by _urllib, so we trap them at
1319
 
    # the _urllib2_wrappers level to be able to clean them up.
1320
 
    def socket_disconnect(sock):
1321
 
        try:
1322
 
            sock.shutdown(socket.SHUT_RDWR)
1323
 
            sock.close()
1324
 
        except socket.error:
1325
 
            pass
1326
 
    def connect(connection):
1327
 
        test.http_connect_orig(connection)
1328
 
        test.addCleanup(socket_disconnect, connection.sock)
1329
 
    test.http_connect_orig = test.overrideAttr(
1330
 
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1331
 
    def connect(connection):
1332
 
        test.https_connect_orig(connection)
1333
 
        test.addCleanup(socket_disconnect, connection.sock)
1334
 
    test.https_connect_orig = test.overrideAttr(
1335
 
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1336
 
 
1337
 
 
1338
1324
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1339
1325
    """Test redirections.
1340
1326
 
1350
1336
    """
1351
1337
 
1352
1338
    def setUp(self):
1353
 
        if (features.pycurl.available()
1354
 
            and self._transport == PyCurlTransport):
 
1339
        if pycurl_present and self._transport == PyCurlTransport:
1355
1340
            raise tests.TestNotApplicable(
1356
 
                "pycurl doesn't redirect silently anymore")
 
1341
                "pycurl doesn't redirect silently annymore")
1357
1342
        super(TestHTTPSilentRedirections, self).setUp()
1358
 
        install_redirected_request(self)
1359
 
        cleanup_http_redirection_connections(self)
 
1343
        self.setup_redirected_request()
 
1344
        self.addCleanup(self.cleanup_redirected_request)
1360
1345
        self.build_tree_contents([('a','a'),
1361
1346
                                  ('1/',),
1362
1347
                                  ('1/a', 'redirected once'),
1370
1355
                                  ('5/a', 'redirected 5 times'),
1371
1356
                                  ],)
1372
1357
 
 
1358
        self.old_transport = self._transport(self.old_server.get_url())
 
1359
 
 
1360
    def setup_redirected_request(self):
 
1361
        self.original_class = _urllib2_wrappers.Request
 
1362
        _urllib2_wrappers.Request = RedirectedRequest
 
1363
 
 
1364
    def cleanup_redirected_request(self):
 
1365
        _urllib2_wrappers.Request = self.original_class
 
1366
 
 
1367
    def create_transport_secondary_server(self):
 
1368
        """Create the secondary server, redirections are defined in the tests"""
 
1369
        return http_utils.HTTPServerRedirecting(
 
1370
            protocol_version=self._protocol_version)
 
1371
 
1373
1372
    def test_one_redirection(self):
1374
 
        t = self.get_old_transport()
1375
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1373
        t = self.old_transport
 
1374
 
 
1375
        req = RedirectedRequest('GET', t.abspath('a'))
 
1376
        req.follow_redirections = True
1376
1377
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1377
1378
                                       self.new_server.port)
1378
1379
        self.old_server.redirections = \
1379
1380
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1380
 
        self.assertEqual('redirected once', t._perform(req).read())
 
1381
        self.assertEquals('redirected once',t._perform(req).read())
1381
1382
 
1382
1383
    def test_five_redirections(self):
1383
 
        t = self.get_old_transport()
1384
 
        req = RedirectedRequest('GET', t._remote_path('a'))
 
1384
        t = self.old_transport
 
1385
 
 
1386
        req = RedirectedRequest('GET', t.abspath('a'))
 
1387
        req.follow_redirections = True
1385
1388
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1386
1389
                                       self.old_server.port)
1387
1390
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1393
1396
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1394
1397
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1395
1398
            ]
1396
 
        self.assertEqual('redirected 5 times', t._perform(req).read())
 
1399
        self.assertEquals('redirected 5 times',t._perform(req).read())
1397
1400
 
1398
1401
 
1399
1402
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1402
1405
    def setUp(self):
1403
1406
        super(TestDoCatchRedirections, self).setUp()
1404
1407
        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')
 
1408
 
 
1409
        self.old_transport = self._transport(self.old_server.get_url())
 
1410
 
 
1411
    def get_a(self, transport):
 
1412
        return transport.get('a')
1411
1413
 
1412
1414
    def test_no_redirection(self):
1413
 
        t = self.get_new_transport()
 
1415
        t = self._transport(self.new_server.get_url())
1414
1416
 
1415
1417
        # We use None for redirected so that we fail if redirected
1416
 
        self.assertEqual('0123456789',
1417
 
                         transport.do_catching_redirections(
 
1418
        self.assertEquals('0123456789',
 
1419
                          transport.do_catching_redirections(
1418
1420
                self.get_a, t, None).read())
1419
1421
 
1420
1422
    def test_one_redirection(self):
1421
1423
        self.redirections = 0
1422
1424
 
1423
 
        def redirected(t, exception, redirection_notice):
 
1425
        def redirected(transport, exception, redirection_notice):
1424
1426
            self.redirections += 1
1425
 
            redirected_t = t._redirected_to(exception.source, exception.target)
1426
 
            return redirected_t
 
1427
            dir, file = urlutils.split(exception.target)
 
1428
            return self._transport(dir)
1427
1429
 
1428
 
        self.assertEqual('0123456789',
1429
 
                         transport.do_catching_redirections(
 
1430
        self.assertEquals('0123456789',
 
1431
                          transport.do_catching_redirections(
1430
1432
                self.get_a, self.old_transport, redirected).read())
1431
 
        self.assertEqual(1, self.redirections)
 
1433
        self.assertEquals(1, self.redirections)
1432
1434
 
1433
1435
    def test_redirection_loop(self):
1434
1436
 
1449
1451
    _auth_header = 'Authorization'
1450
1452
    _password_prompt_prefix = ''
1451
1453
    _username_prompt_prefix = ''
1452
 
    # Set by load_tests
1453
 
    _auth_server = None
1454
1454
 
1455
1455
    def setUp(self):
1456
1456
        super(TestAuth, self).setUp()
1459
1459
                                  ('b', 'contents of b\n'),])
1460
1460
 
1461
1461
    def create_transport_readonly_server(self):
1462
 
        server = self._auth_server(protocol_version=self._protocol_version)
1463
 
        server._url_protocol = self._url_protocol
 
1462
        if self._auth_scheme == 'basic':
 
1463
            server = http_utils.HTTPBasicAuthServer(
 
1464
                protocol_version=self._protocol_version)
 
1465
        else:
 
1466
            if self._auth_scheme != 'digest':
 
1467
                raise AssertionError('Unknown auth scheme: %r'
 
1468
                                     % self._auth_scheme)
 
1469
            server = http_utils.HTTPDigestAuthServer(
 
1470
                protocol_version=self._protocol_version)
1464
1471
        return server
1465
1472
 
1466
1473
    def _testing_pycurl(self):
1467
 
        # TODO: This is duplicated for lots of the classes in this file
1468
 
        return (features.pycurl.available()
1469
 
                and self._transport == PyCurlTransport)
 
1474
        return pycurl_present and self._transport == PyCurlTransport
1470
1475
 
1471
1476
    def get_user_url(self, user, password):
1472
1477
        """Build an url embedding user and password"""
1480
1485
        return url
1481
1486
 
1482
1487
    def get_user_transport(self, user, password):
1483
 
        t = transport.get_transport(self.get_user_url(user, password))
1484
 
        return t
 
1488
        return self._transport(self.get_user_url(user, password))
1485
1489
 
1486
1490
    def test_no_user(self):
1487
1491
        self.server.add_user('joe', 'foo')
1530
1534
        self.server.add_user('joe', 'foo')
1531
1535
        t = self.get_user_transport(None, None)
1532
1536
        stdout = tests.StringIOWrapper()
1533
 
        stderr = tests.StringIOWrapper()
1534
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1535
 
                                            stdout=stdout, stderr=stderr)
 
1537
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n', stdout=stdout)
1536
1538
        self.assertEqual('contents of a\n',t.get('a').read())
1537
1539
        # stdin should be empty
1538
1540
        self.assertEqual('', ui.ui_factory.stdin.readline())
1539
 
        stderr.seek(0)
 
1541
        stdout.seek(0)
1540
1542
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1541
 
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1542
 
        self.assertEqual('', stdout.getvalue())
 
1543
        self.assertEquals(expected_prompt, stdout.read(len(expected_prompt)))
1543
1544
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1544
 
                                    stderr.readline())
 
1545
                                    stdout.readline())
1545
1546
 
1546
1547
    def test_prompt_for_password(self):
1547
1548
        if self._testing_pycurl():
1552
1553
        self.server.add_user('joe', 'foo')
1553
1554
        t = self.get_user_transport('joe', None)
1554
1555
        stdout = tests.StringIOWrapper()
1555
 
        stderr = tests.StringIOWrapper()
1556
 
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1557
 
                                            stdout=stdout, stderr=stderr)
1558
 
        self.assertEqual('contents of a\n', t.get('a').read())
 
1556
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n', stdout=stdout)
 
1557
        self.assertEqual('contents of a\n',t.get('a').read())
1559
1558
        # stdin should be empty
1560
1559
        self.assertEqual('', ui.ui_factory.stdin.readline())
1561
1560
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1562
 
                                    stderr.getvalue())
1563
 
        self.assertEqual('', stdout.getvalue())
 
1561
                                    stdout.getvalue())
1564
1562
        # And we shouldn't prompt again for a different request
1565
1563
        # against the same transport.
1566
1564
        self.assertEqual('contents of b\n',t.get('b').read())
1576
1574
                              % (scheme.upper(),
1577
1575
                                 user, self.server.host, self.server.port,
1578
1576
                                 self.server.auth_realm)))
1579
 
        self.assertEqual(expected_prompt, actual_prompt)
 
1577
        self.assertEquals(expected_prompt, actual_prompt)
1580
1578
 
1581
1579
    def _expected_username_prompt(self, scheme):
1582
1580
        return (self._username_prompt_prefix
1596
1594
        self.server.add_user(user, password)
1597
1595
        t = self.get_user_transport(user, None)
1598
1596
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1599
 
                                            stderr=tests.StringIOWrapper())
 
1597
                                            stdout=tests.StringIOWrapper())
1600
1598
        # Create a minimal config file with the right password
1601
1599
        conf = config.AuthenticationConfig()
1602
1600
        conf._get_config().update(
1630
1628
        self.assertEqual(1, self.server.auth_required_errors)
1631
1629
 
1632
1630
    def test_changing_nonce(self):
1633
 
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1634
 
                                     http_utils.ProxyDigestAuthServer):
1635
 
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
 
1631
        if self._auth_scheme != 'digest':
 
1632
            raise tests.TestNotApplicable('HTTP auth digest only test')
1636
1633
        if self._testing_pycurl():
1637
1634
            raise tests.KnownFailure(
1638
1635
                'pycurl does not handle a nonce change')
1670
1667
                                  ('b-proxied', 'contents of b\n'),
1671
1668
                                  ])
1672
1669
 
 
1670
    def create_transport_readonly_server(self):
 
1671
        if self._auth_scheme == 'basic':
 
1672
            server = http_utils.ProxyBasicAuthServer(
 
1673
                protocol_version=self._protocol_version)
 
1674
        else:
 
1675
            if self._auth_scheme != 'digest':
 
1676
                raise AssertionError('Unknown auth scheme: %r'
 
1677
                                     % self._auth_scheme)
 
1678
            server = http_utils.ProxyDigestAuthServer(
 
1679
                protocol_version=self._protocol_version)
 
1680
        return server
 
1681
 
1673
1682
    def get_user_transport(self, user, password):
1674
1683
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1675
 
        return TestAuth.get_user_transport(self, user, password)
 
1684
        return self._transport(self.server.get_url())
1676
1685
 
1677
1686
    def _install_env(self, env):
1678
1687
        for name, value in env.iteritems():
1705
1714
        self.readfile = StringIO(socket_read_content)
1706
1715
        self.writefile = StringIO()
1707
1716
        self.writefile.close = lambda: None
1708
 
        self.close = lambda: None
1709
1717
 
1710
1718
    def makefile(self, mode='r', bufsize=None):
1711
1719
        if 'r' in mode:
1721
1729
        # We use the VFS layer as part of HTTP tunnelling tests.
1722
1730
        self._captureVar('BZR_NO_SMART_VFS', None)
1723
1731
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
1724
 
        self.http_server = self.get_readonly_server()
1725
1732
 
1726
1733
    def create_transport_readonly_server(self):
1727
 
        server = http_utils.HTTPServerWithSmarts(
 
1734
        return http_utils.HTTPServerWithSmarts(
1728
1735
            protocol_version=self._protocol_version)
1729
 
        server._url_protocol = self._url_protocol
1730
 
        return server
1731
1736
 
1732
1737
    def test_open_bzrdir(self):
1733
1738
        branch = self.make_branch('relpath')
1734
 
        url = self.http_server.get_url() + 'relpath'
 
1739
        http_server = self.get_readonly_server()
 
1740
        url = http_server.get_url() + 'relpath'
1735
1741
        bd = bzrdir.BzrDir.open(url)
1736
 
        self.addCleanup(bd.transport.disconnect)
1737
1742
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1738
1743
 
1739
1744
    def test_bulk_data(self):
1741
1746
        # The 'readv' command in the smart protocol both sends and receives
1742
1747
        # bulk data, so we use that.
1743
1748
        self.build_tree(['data-file'])
1744
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1749
        http_server = self.get_readonly_server()
 
1750
        http_transport = self._transport(http_server.get_url())
1745
1751
        medium = http_transport.get_smart_medium()
1746
1752
        # Since we provide the medium, the url below will be mostly ignored
1747
1753
        # during the test, as long as the path is '/'.
1755
1761
        post_body = 'hello\n'
1756
1762
        expected_reply_body = 'ok\x012\n'
1757
1763
 
1758
 
        http_transport = transport.get_transport(self.http_server.get_url())
 
1764
        http_server = self.get_readonly_server()
 
1765
        http_transport = self._transport(http_server.get_url())
1759
1766
        medium = http_transport.get_smart_medium()
1760
1767
        response = medium.send_http_smart_request(post_body)
1761
1768
        reply_body = response.read()
1762
1769
        self.assertEqual(expected_reply_body, reply_body)
1763
1770
 
1764
1771
    def test_smart_http_server_post_request_handler(self):
1765
 
        httpd = self.http_server.server
 
1772
        httpd = self.get_readonly_server()._get_httpd()
1766
1773
 
1767
1774
        socket = SampleSocket(
1768
1775
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1800
1807
 
1801
1808
    def test_probe_smart_server(self):
1802
1809
        """Test error handling against server refusing smart requests."""
1803
 
        t = self.get_readonly_transport()
 
1810
        server = self.get_readonly_server()
 
1811
        t = self._transport(server.get_url())
1804
1812
        # No need to build a valid smart request here, the server will not even
1805
1813
        # try to interpret it.
1806
1814
        self.assertRaises(errors.SmartProtocolError,
1807
1815
                          t.get_smart_medium().send_http_smart_request,
1808
1816
                          'whatever')
1809
1817
 
1810
 
 
1811
1818
class Test_redirected_to(tests.TestCase):
1812
1819
 
1813
1820
    def test_redirected_to_subdir(self):
1816
1823
                             'http://www.example.com/foo/subdir')
1817
1824
        self.assertIsInstance(r, type(t))
1818
1825
        # Both transports share the some connection
1819
 
        self.assertEqual(t._get_connection(), r._get_connection())
 
1826
        self.assertEquals(t._get_connection(), r._get_connection())
1820
1827
 
1821
1828
    def test_redirected_to_self_with_slash(self):
1822
1829
        t = self._transport('http://www.example.com/foo')
1826
1833
        # Both transports share the some connection (one can argue that we
1827
1834
        # should return the exact same transport here, but that seems
1828
1835
        # overkill).
1829
 
        self.assertEqual(t._get_connection(), r._get_connection())
 
1836
        self.assertEquals(t._get_connection(), r._get_connection())
1830
1837
 
1831
1838
    def test_redirected_to_host(self):
1832
1839
        t = self._transport('http://www.example.com/foo')
1851
1858
        r = t._redirected_to('http://www.example.com/foo',
1852
1859
                             'https://foo.example.com/foo')
1853
1860
        self.assertIsInstance(r, type(t))
1854
 
        self.assertEqual(t._user, r._user)
 
1861
        self.assertEquals(t._user, r._user)
1855
1862
 
1856
1863
 
1857
1864
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1866
1873
    line.
1867
1874
    """
1868
1875
 
1869
 
    def _handle_one_request(self):
 
1876
    def handle_one_request(self):
1870
1877
        tcs = self.server.test_case_server
1871
1878
        requestline = self.rfile.readline()
1872
1879
        headers = self.MessageClass(self.rfile, 0)
1916
1923
        pass
1917
1924
 
1918
1925
 
1919
 
class TestActivityMixin(object):
 
1926
class TestActivity(tests.TestCase):
1920
1927
    """Test socket activity reporting.
1921
1928
 
1922
1929
    We use a special purpose server to control the bytes sent and received and
1926
1933
    def setUp(self):
1927
1934
        tests.TestCase.setUp(self)
1928
1935
        self.server = self._activity_server(self._protocol_version)
1929
 
        self.server.start_server()
 
1936
        self.server.setUp()
1930
1937
        self.activities = {}
1931
1938
        def report_activity(t, bytes, direction):
1932
1939
            count = self.activities.get(direction, 0)
1936
1943
        # We override at class level because constructors may propagate the
1937
1944
        # bound method and render instance overriding ineffective (an
1938
1945
        # 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)
 
1946
        self.orig_report_activity = self._transport._report_activity
 
1947
        self._transport._report_activity = report_activity
 
1948
 
 
1949
    def tearDown(self):
 
1950
        self._transport._report_activity = self.orig_report_activity
 
1951
        self.server.tearDown()
 
1952
        tests.TestCase.tearDown(self)
1941
1953
 
1942
1954
    def get_transport(self):
1943
 
        t = self._transport(self.server.get_url())
1944
 
        # FIXME: Needs cleanup -- vila 20100611
1945
 
        return t
 
1955
        return self._transport(self.server.get_url())
1946
1956
 
1947
1957
    def assertActivitiesMatch(self):
1948
1958
        self.assertEqual(self.server.bytes_read,
2053
2063
'''
2054
2064
        t = self.get_transport()
2055
2065
        # We must send a single line of body bytes, see
2056
 
        # PredefinedRequestHandler._handle_one_request
 
2066
        # PredefinedRequestHandler.handle_one_request
2057
2067
        code, f = t._post('abc def end-of-body\n')
2058
2068
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2059
2069
        self.assertActivitiesMatch()
2060
 
 
2061
 
 
2062
 
class TestActivity(tests.TestCase, TestActivityMixin):
2063
 
 
2064
 
    def setUp(self):
2065
 
        TestActivityMixin.setUp(self)
2066
 
 
2067
 
 
2068
 
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2069
 
 
2070
 
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2071
 
    # ReportingSocket, so we don't need all the parametrization. Since
2072
 
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2073
 
    # test them through their use by the transport than directly (that's a
2074
 
    # bit less clean but far more simpler and effective).
2075
 
    _activity_server = ActivityHTTPServer
2076
 
    _protocol_version = 'HTTP/1.1'
2077
 
 
2078
 
    def setUp(self):
2079
 
        self._transport =_urllib.HttpTransport_urllib
2080
 
        TestActivityMixin.setUp(self)
2081
 
 
2082
 
    def assertActivitiesMatch(self):
2083
 
        # Nothing to check here
2084
 
        pass
2085
 
 
2086
 
 
2087
 
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2088
 
    """Test authentication on the redirected http server."""
2089
 
 
2090
 
    _auth_header = 'Authorization'
2091
 
    _password_prompt_prefix = ''
2092
 
    _username_prompt_prefix = ''
2093
 
    _auth_server = http_utils.HTTPBasicAuthServer
2094
 
    _transport = _urllib.HttpTransport_urllib
2095
 
 
2096
 
    def setUp(self):
2097
 
        super(TestAuthOnRedirected, self).setUp()
2098
 
        self.build_tree_contents([('a','a'),
2099
 
                                  ('1/',),
2100
 
                                  ('1/a', 'redirected once'),
2101
 
                                  ],)
2102
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2103
 
                                       self.new_server.port)
2104
 
        self.old_server.redirections = [
2105
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2106
 
        self.old_transport = self.get_old_transport()
2107
 
        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')
2117
 
 
2118
 
    def test_auth_on_redirected_via_do_catching_redirections(self):
2119
 
        self.redirections = 0
2120
 
 
2121
 
        def redirected(t, exception, redirection_notice):
2122
 
            self.redirections += 1
2123
 
            redirected_t = t._redirected_to(exception.source, exception.target)
2124
 
            self.addCleanup(redirected_t.disconnect)
2125
 
            return redirected_t
2126
 
 
2127
 
        stdout = tests.StringIOWrapper()
2128
 
        stderr = tests.StringIOWrapper()
2129
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2130
 
                                            stdout=stdout, stderr=stderr)
2131
 
        self.assertEqual('redirected once',
2132
 
                         transport.do_catching_redirections(
2133
 
                self.get_a, self.old_transport, redirected).read())
2134
 
        self.assertEqual(1, self.redirections)
2135
 
        # stdin should be empty
2136
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2137
 
        # stdout should be empty, stderr will contains the prompts
2138
 
        self.assertEqual('', stdout.getvalue())
2139
 
 
2140
 
    def test_auth_on_redirected_via_following_redirections(self):
2141
 
        self.new_server.add_user('joe', 'foo')
2142
 
        stdout = tests.StringIOWrapper()
2143
 
        stderr = tests.StringIOWrapper()
2144
 
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2145
 
                                            stdout=stdout, stderr=stderr)
2146
 
        t = self.old_transport
2147
 
        req = RedirectedRequest('GET', t.abspath('a'))
2148
 
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2149
 
                                       self.new_server.port)
2150
 
        self.old_server.redirections = [
2151
 
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
2152
 
        self.assertEqual('redirected once', t._perform(req).read())
2153
 
        # stdin should be empty
2154
 
        self.assertEqual('', ui.ui_factory.stdin.readline())
2155
 
        # stdout should be empty, stderr will contains the prompts
2156
 
        self.assertEqual('', stdout.getvalue())
2157
 
 
2158