~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http.py

  • Committer: Patch Queue Manager
  • Date: 2011-10-14 16:54:26 UTC
  • mfrom: (6216.1.1 remove-this-file)
  • Revision ID: pqm@pqm.ubuntu.com-20111014165426-tjix4e6idryf1r2z
(jelmer) Remove an accidentally committed .THIS file. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
27
26
import httplib
28
 
import os
29
 
import select
30
27
import SimpleHTTPServer
31
28
import socket
32
29
import sys
35
32
import bzrlib
36
33
from bzrlib import (
37
34
    bzrdir,
 
35
    cethread,
38
36
    config,
 
37
    debug,
39
38
    errors,
40
39
    osutils,
41
40
    remote as _mod_remote,
42
41
    tests,
 
42
    trace,
43
43
    transport,
44
44
    ui,
45
 
    urlutils,
46
 
    )
47
 
from bzrlib.symbol_versioning import (
48
 
    deprecated_in,
49
45
    )
50
46
from bzrlib.tests import (
 
47
    features,
51
48
    http_server,
52
49
    http_utils,
 
50
    test_server,
 
51
    )
 
52
from bzrlib.tests.scenarios import (
 
53
    load_tests_apply_scenarios,
 
54
    multiply_scenarios,
53
55
    )
54
56
from bzrlib.transport import (
55
57
    http,
61
63
    )
62
64
 
63
65
 
64
 
try:
 
66
if features.pycurl.available():
65
67
    from bzrlib.transport.http._pycurl import PyCurlTransport
66
 
    pycurl_present = True
67
 
except errors.DependencyNotPresent:
68
 
    pycurl_present = False
69
 
 
70
 
 
71
 
def load_tests(standard_tests, module, loader):
72
 
    """Multiply tests for http clients and protocol versions."""
73
 
    result = loader.suiteClass()
74
 
 
75
 
    # one for each transport implementation
76
 
    t_tests, remaining_tests = tests.split_suite_by_condition(
77
 
        standard_tests, tests.condition_isinstance((
78
 
                TestHttpTransportRegistration,
79
 
                TestHttpTransportUrls,
80
 
                Test_redirected_to,
81
 
                )))
 
68
 
 
69
 
 
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."""
82
75
    transport_scenarios = [
83
76
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
84
77
                        _server=http_server.HttpServer_urllib,
85
 
                        _qualified_prefix='http+urllib',)),
 
78
                        _url_protocol='http+urllib',)),
86
79
        ]
87
 
    if pycurl_present:
 
80
    if features.pycurl.available():
88
81
        transport_scenarios.append(
89
82
            ('pycurl', dict(_transport=PyCurlTransport,
90
83
                            _server=http_server.HttpServer_PyCurl,
91
 
                            _qualified_prefix='http+pycurl',)))
92
 
    tests.multiply_tests(t_tests, transport_scenarios, result)
93
 
 
94
 
    # each implementation tested with each HTTP version
95
 
    tp_tests, remaining_tests = tests.split_suite_by_condition(
96
 
        remaining_tests, tests.condition_isinstance((
97
 
                SmartHTTPTunnellingTest,
98
 
                TestDoCatchRedirections,
99
 
                TestHTTPConnections,
100
 
                TestHTTPRedirections,
101
 
                TestHTTPSilentRedirections,
102
 
                TestLimitedRangeRequestServer,
103
 
                TestPost,
104
 
                TestProxyHttpServer,
105
 
                TestRanges,
106
 
                TestSpecificRequestHandler,
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
 
            ]
112
 
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
113
 
                                            protocol_scenarios)
114
 
    tests.multiply_tests(tp_tests, tp_scenarios, result)
115
 
 
116
 
    # proxy auth: each auth scheme on all http versions on all implementations.
117
 
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
118
 
        remaining_tests, tests.condition_isinstance((
119
 
                TestProxyAuth,
120
 
                )))
121
 
    proxy_auth_scheme_scenarios = [
122
 
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
123
 
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
124
 
        ('basicdigest',
125
 
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
 
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')),
126
93
        ]
127
 
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
128
 
                                              proxy_auth_scheme_scenarios)
129
 
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
130
 
 
131
 
    # auth: each auth scheme on all http versions on all implementations.
132
 
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
133
 
        remaining_tests, tests.condition_isinstance((
134
 
                TestAuth,
135
 
                )))
136
 
    auth_scheme_scenarios = [
 
94
 
 
95
 
 
96
def vary_by_http_auth_scheme():
 
97
    scenarios = [
137
98
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
138
99
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
139
100
        ('basicdigest',
140
 
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
141
 
        ]
142
 
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
143
 
                                             auth_scheme_scenarios)
144
 
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
145
 
 
146
 
    # activity: on all http[s] versions on all implementations
147
 
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
148
 
        remaining_tests, tests.condition_isinstance((
149
 
                TestActivity,
150
 
                )))
 
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():
151
127
    activity_scenarios = [
152
128
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
153
 
                             _transport=_urllib.HttpTransport_urllib,)),
 
129
                            _transport=_urllib.HttpTransport_urllib,)),
154
130
        ]
155
 
    if tests.HTTPSServerFeature.available():
 
131
    if features.HTTPSServerFeature.available():
156
132
        activity_scenarios.append(
157
133
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
158
 
                                  _transport=_urllib.HttpTransport_urllib,)),)
159
 
    if pycurl_present:
 
134
                                _transport=_urllib.HttpTransport_urllib,)),)
 
135
    if features.pycurl.available():
160
136
        activity_scenarios.append(
161
137
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
162
 
                                 _transport=PyCurlTransport,)),)
163
 
        if tests.HTTPSServerFeature.available():
 
138
                                _transport=PyCurlTransport,)),)
 
139
        if features.HTTPSServerFeature.available():
164
140
            from bzrlib.tests import (
165
141
                ssl_certs,
166
142
                )
177
153
 
178
154
            activity_scenarios.append(
179
155
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
180
 
                                      _transport=HTTPS_pycurl_transport,)),)
181
 
 
182
 
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
183
 
                                               protocol_scenarios)
184
 
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
185
 
 
186
 
    # No parametrization for the remaining tests
187
 
    result.addTests(remaining_tests)
188
 
 
189
 
    return result
 
156
                                    _transport=HTTPS_pycurl_transport,)),)
 
157
    return activity_scenarios
190
158
 
191
159
 
192
160
class FakeManager(object):
204
172
    It records the bytes sent to it, and replies with a 200.
205
173
    """
206
174
 
207
 
    def __init__(self, expect_body_tail=None):
 
175
    def __init__(self, expect_body_tail=None, scheme=''):
208
176
        """Constructor.
209
177
 
210
178
        :type expect_body_tail: str
215
183
        self.host = None
216
184
        self.port = None
217
185
        self.received_bytes = ''
218
 
 
219
 
    def setUp(self):
 
186
        self.scheme = scheme
 
187
 
 
188
    def get_url(self):
 
189
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
 
190
 
 
191
    def start_server(self):
220
192
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
221
193
        self._sock.bind(('127.0.0.1', 0))
222
194
        self.host, self.port = self._sock.getsockname()
223
195
        self._ready = threading.Event()
224
 
        self._thread = threading.Thread(target=self._accept_read_and_reply)
225
 
        self._thread.setDaemon(True)
 
196
        self._thread = test_server.TestThread(
 
197
            sync_event=self._ready, target=self._accept_read_and_reply)
226
198
        self._thread.start()
227
 
        self._ready.wait(5)
 
199
        if 'threads' in tests.selftest_debug_flags:
 
200
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
 
201
        self._ready.wait()
228
202
 
229
203
    def _accept_read_and_reply(self):
230
204
        self._sock.listen(1)
231
205
        self._ready.set()
232
 
        self._sock.settimeout(5)
233
 
        try:
234
 
            conn, address = self._sock.accept()
235
 
            # On win32, the accepted connection will be non-blocking to start
236
 
            # with because we're using settimeout.
237
 
            conn.setblocking(True)
 
206
        conn, address = self._sock.accept()
 
207
        if self._expect_body_tail is not None:
238
208
            while not self.received_bytes.endswith(self._expect_body_tail):
239
209
                self.received_bytes += conn.recv(4096)
240
210
            conn.sendall('HTTP/1.1 200 OK\r\n')
241
 
        except socket.timeout:
242
 
            # Make sure the client isn't stuck waiting for us to e.g. accept.
 
211
        try:
243
212
            self._sock.close()
244
213
        except socket.error:
245
214
            # The client may have already closed the socket.
246
215
            pass
247
216
 
248
 
    def tearDown(self):
 
217
    def stop_server(self):
249
218
        try:
250
 
            self._sock.close()
 
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()
251
223
        except socket.error:
252
224
            # We might have already closed it.  We don't care.
253
225
            pass
254
226
        self.host = None
255
227
        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,))
256
231
 
257
232
 
258
233
class TestAuthHeader(tests.TestCase):
265
240
 
266
241
    def test_empty_header(self):
267
242
        scheme, remainder = self.parse_header('')
268
 
        self.assertEquals('', scheme)
 
243
        self.assertEqual('', scheme)
269
244
        self.assertIs(None, remainder)
270
245
 
271
246
    def test_negotiate_header(self):
272
247
        scheme, remainder = self.parse_header('Negotiate')
273
 
        self.assertEquals('negotiate', scheme)
 
248
        self.assertEqual('negotiate', scheme)
274
249
        self.assertIs(None, remainder)
275
250
 
276
251
    def test_basic_header(self):
277
252
        scheme, remainder = self.parse_header(
278
253
            'Basic realm="Thou should not pass"')
279
 
        self.assertEquals('basic', scheme)
280
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
254
        self.assertEqual('basic', scheme)
 
255
        self.assertEqual('realm="Thou should not pass"', remainder)
281
256
 
282
257
    def test_basic_extract_realm(self):
283
258
        scheme, remainder = self.parse_header(
285
260
            _urllib2_wrappers.BasicAuthHandler)
286
261
        match, realm = self.auth_handler.extract_realm(remainder)
287
262
        self.assertTrue(match is not None)
288
 
        self.assertEquals('Thou should not pass', realm)
 
263
        self.assertEqual('Thou should not pass', realm)
289
264
 
290
265
    def test_digest_header(self):
291
266
        scheme, remainder = self.parse_header(
292
267
            'Digest realm="Thou should not pass"')
293
 
        self.assertEquals('digest', scheme)
294
 
        self.assertEquals('realm="Thou should not pass"', remainder)
 
268
        self.assertEqual('digest', scheme)
 
269
        self.assertEqual('realm="Thou should not pass"', remainder)
 
270
 
 
271
 
 
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)
295
304
 
296
305
 
297
306
class TestHTTPServer(tests.TestCase):
302
311
 
303
312
            protocol_version = 'HTTP/0.1'
304
313
 
305
 
        server = http_server.HttpServer(BogusRequestHandler)
306
 
        try:
307
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
308
 
        except:
309
 
            server.tearDown()
310
 
            self.fail('HTTP Server creation did not raise UnknownProtocol')
 
314
        self.assertRaises(httplib.UnknownProtocol,
 
315
                          http_server.HttpServer, BogusRequestHandler)
311
316
 
312
317
    def test_force_invalid_protocol(self):
313
 
        server = http_server.HttpServer(protocol_version='HTTP/0.1')
314
 
        try:
315
 
            self.assertRaises(httplib.UnknownProtocol,server.setUp)
316
 
        except:
317
 
            server.tearDown()
318
 
            self.fail('HTTP Server creation did not raise UnknownProtocol')
 
318
        self.assertRaises(httplib.UnknownProtocol,
 
319
                          http_server.HttpServer, protocol_version='HTTP/0.1')
319
320
 
320
321
    def test_server_start_and_stop(self):
321
322
        server = http_server.HttpServer()
322
 
        server.setUp()
323
 
        self.assertTrue(server._http_running)
324
 
        server.tearDown()
325
 
        self.assertFalse(server._http_running)
 
323
        self.addCleanup(server.stop_server)
 
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)
326
328
 
327
329
    def test_create_http_server_one_zero(self):
328
330
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
330
332
            protocol_version = 'HTTP/1.0'
331
333
 
332
334
        server = http_server.HttpServer(RequestHandlerOneZero)
333
 
        server.setUp()
334
 
        self.addCleanup(server.tearDown)
335
 
        self.assertIsInstance(server._httpd, http_server.TestingHTTPServer)
 
335
        self.start_server(server)
 
336
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
336
337
 
337
338
    def test_create_http_server_one_one(self):
338
339
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
340
341
            protocol_version = 'HTTP/1.1'
341
342
 
342
343
        server = http_server.HttpServer(RequestHandlerOneOne)
343
 
        server.setUp()
344
 
        self.addCleanup(server.tearDown)
345
 
        self.assertIsInstance(server._httpd,
 
344
        self.start_server(server)
 
345
        self.assertIsInstance(server.server,
346
346
                              http_server.TestingThreadingHTTPServer)
347
347
 
348
348
    def test_create_http_server_force_one_one(self):
352
352
 
353
353
        server = http_server.HttpServer(RequestHandlerOneZero,
354
354
                                        protocol_version='HTTP/1.1')
355
 
        server.setUp()
356
 
        self.addCleanup(server.tearDown)
357
 
        self.assertIsInstance(server._httpd,
 
355
        self.start_server(server)
 
356
        self.assertIsInstance(server.server,
358
357
                              http_server.TestingThreadingHTTPServer)
359
358
 
360
359
    def test_create_http_server_force_one_zero(self):
364
363
 
365
364
        server = http_server.HttpServer(RequestHandlerOneOne,
366
365
                                        protocol_version='HTTP/1.0')
367
 
        server.setUp()
368
 
        self.addCleanup(server.tearDown)
369
 
        self.assertIsInstance(server._httpd,
 
366
        self.start_server(server)
 
367
        self.assertIsInstance(server.server,
370
368
                              http_server.TestingHTTPServer)
371
369
 
372
370
 
374
372
    """Test case to inherit from if pycurl is present"""
375
373
 
376
374
    def _get_pycurl_maybe(self):
377
 
        try:
378
 
            from bzrlib.transport.http._pycurl import PyCurlTransport
379
 
            return PyCurlTransport
380
 
        except errors.DependencyNotPresent:
381
 
            raise tests.TestSkipped('pycurl not present')
 
375
        self.requireFeature(features.pycurl)
 
376
        return PyCurlTransport
382
377
 
383
378
    _transport = property(_get_pycurl_maybe)
384
379
 
391
386
    def test_url_parsing(self):
392
387
        f = FakeManager()
393
388
        url = http.extract_auth('http://example.com', f)
394
 
        self.assertEquals('http://example.com', url)
395
 
        self.assertEquals(0, len(f.credentials))
 
389
        self.assertEqual('http://example.com', url)
 
390
        self.assertEqual(0, len(f.credentials))
396
391
        url = http.extract_auth(
397
 
            'http://user:pass@www.bazaar-vcs.org/bzr/bzr.dev', f)
398
 
        self.assertEquals('http://www.bazaar-vcs.org/bzr/bzr.dev', url)
399
 
        self.assertEquals(1, len(f.credentials))
400
 
        self.assertEquals([None, 'www.bazaar-vcs.org', 'user', 'pass'],
401
 
                          f.credentials[0])
 
392
            'http://user:pass@example.com/bzr/bzr.dev', f)
 
393
        self.assertEqual('http://example.com/bzr/bzr.dev', url)
 
394
        self.assertEqual(1, len(f.credentials))
 
395
        self.assertEqual([None, 'example.com', 'user', 'pass'],
 
396
                         f.credentials[0])
402
397
 
403
398
 
404
399
class TestHttpTransportUrls(tests.TestCase):
405
400
    """Test the http urls."""
406
401
 
 
402
    scenarios = vary_by_http_client_implementation()
 
403
 
407
404
    def test_abs_url(self):
408
405
        """Construction of absolute http URLs"""
409
 
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
 
406
        t = self._transport('http://example.com/bzr/bzr.dev/')
410
407
        eq = self.assertEqualDiff
411
 
        eq(t.abspath('.'), 'http://bazaar-vcs.org/bzr/bzr.dev')
412
 
        eq(t.abspath('foo/bar'), 'http://bazaar-vcs.org/bzr/bzr.dev/foo/bar')
413
 
        eq(t.abspath('.bzr'), 'http://bazaar-vcs.org/bzr/bzr.dev/.bzr')
 
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')
414
411
        eq(t.abspath('.bzr/1//2/./3'),
415
 
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
 
412
           'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
416
413
 
417
414
    def test_invalid_http_urls(self):
418
415
        """Trap invalid construction of urls"""
419
 
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
 
416
        self._transport('http://example.com/bzr/bzr.dev/')
420
417
        self.assertRaises(errors.InvalidURL,
421
418
                          self._transport,
422
 
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
 
419
                          'http://http://example.com/bzr/bzr.dev/')
423
420
 
424
421
    def test_http_root_urls(self):
425
422
        """Construction of URLs from server root"""
426
 
        t = self._transport('http://bzr.ozlabs.org/')
 
423
        t = self._transport('http://example.com/')
427
424
        eq = self.assertEqualDiff
428
425
        eq(t.abspath('.bzr/tree-version'),
429
 
           'http://bzr.ozlabs.org/.bzr/tree-version')
 
426
           'http://example.com/.bzr/tree-version')
430
427
 
431
428
    def test_http_impl_urls(self):
432
429
        """There are servers which ask for particular clients to connect"""
433
430
        server = self._server()
 
431
        server.start_server()
434
432
        try:
435
 
            server.setUp()
436
433
            url = server.get_url()
437
 
            self.assertTrue(url.startswith('%s://' % self._qualified_prefix))
 
434
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
438
435
        finally:
439
 
            server.tearDown()
 
436
            server.stop_server()
440
437
 
441
438
 
442
439
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
451
448
        https by supplying a fake version_info that do not
452
449
        support it.
453
450
        """
454
 
        try:
455
 
            import pycurl
456
 
        except ImportError:
457
 
            raise tests.TestSkipped('pycurl not present')
 
451
        self.requireFeature(features.pycurl)
 
452
        # Import the module locally now that we now it's available.
 
453
        pycurl = features.pycurl.module
458
454
 
459
 
        version_info_orig = pycurl.version_info
460
 
        try:
461
 
            # Now that we have pycurl imported, we can fake its version_info
462
 
            # This was taken from a windows pycurl without SSL
463
 
            # (thanks to bialix)
464
 
            pycurl.version_info = lambda : (2,
465
 
                                            '7.13.2',
466
 
                                            462082,
467
 
                                            'i386-pc-win32',
468
 
                                            2576,
469
 
                                            None,
470
 
                                            0,
471
 
                                            None,
472
 
                                            ('ftp', 'gopher', 'telnet',
473
 
                                             'dict', 'ldap', 'http', 'file'),
474
 
                                            None,
475
 
                                            0,
476
 
                                            None)
477
 
            self.assertRaises(errors.DependencyNotPresent, self._transport,
478
 
                              'https://launchpad.net')
479
 
        finally:
480
 
            # Restore the right function
481
 
            pycurl.version_info = version_info_orig
 
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')
482
473
 
483
474
 
484
475
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
485
476
    """Test the http connections."""
486
477
 
 
478
    scenarios = multiply_scenarios(
 
479
        vary_by_http_client_implementation(),
 
480
        vary_by_http_protocol_version(),
 
481
        )
 
482
 
487
483
    def setUp(self):
488
484
        http_utils.TestCaseWithWebserver.setUp(self)
489
485
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
491
487
 
492
488
    def test_http_has(self):
493
489
        server = self.get_readonly_server()
494
 
        t = self._transport(server.get_url())
 
490
        t = self.get_readonly_transport()
495
491
        self.assertEqual(t.has('foo/bar'), True)
496
492
        self.assertEqual(len(server.logs), 1)
497
493
        self.assertContainsRe(server.logs[0],
499
495
 
500
496
    def test_http_has_not_found(self):
501
497
        server = self.get_readonly_server()
502
 
        t = self._transport(server.get_url())
 
498
        t = self.get_readonly_transport()
503
499
        self.assertEqual(t.has('not-found'), False)
504
500
        self.assertContainsRe(server.logs[1],
505
501
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
506
502
 
507
503
    def test_http_get(self):
508
504
        server = self.get_readonly_server()
509
 
        t = self._transport(server.get_url())
 
505
        t = self.get_readonly_transport()
510
506
        fp = t.get('foo/bar')
511
507
        self.assertEqualDiff(
512
508
            fp.read(),
534
530
class TestHttpTransportRegistration(tests.TestCase):
535
531
    """Test registrations of various http implementations"""
536
532
 
 
533
    scenarios = vary_by_http_client_implementation()
 
534
 
537
535
    def test_http_registered(self):
538
 
        t = transport.get_transport('%s://foo.com/' % self._qualified_prefix)
 
536
        t = transport.get_transport_from_url(
 
537
            '%s://foo.com/' % self._url_protocol)
539
538
        self.assertIsInstance(t, transport.Transport)
540
539
        self.assertIsInstance(t, self._transport)
541
540
 
542
541
 
543
542
class TestPost(tests.TestCase):
544
543
 
 
544
    scenarios = multiply_scenarios(
 
545
        vary_by_http_client_implementation(),
 
546
        vary_by_http_protocol_version(),
 
547
        )
 
548
 
545
549
    def test_post_body_is_received(self):
546
 
        server = RecordingServer(expect_body_tail='end-of-body')
547
 
        server.setUp()
548
 
        self.addCleanup(server.tearDown)
549
 
        scheme = self._qualified_prefix
550
 
        url = '%s://%s:%s/' % (scheme, server.host, server.port)
551
 
        http_transport = self._transport(url)
 
550
        server = RecordingServer(expect_body_tail='end-of-body',
 
551
                                 scheme=self._url_protocol)
 
552
        self.start_server(server)
 
553
        url = server.get_url()
 
554
        # FIXME: needs a cleanup -- vila 20100611
 
555
        http_transport = transport.get_transport_from_url(url)
552
556
        code, response = http_transport._post('abc def end-of-body')
553
557
        self.assertTrue(
554
558
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
555
559
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
 
560
        self.assertTrue('content-type: application/octet-stream\r'
 
561
                        in server.received_bytes.lower())
556
562
        # The transport should not be assuming that the server can accept
557
563
        # chunked encoding the first time it connects, because HTTP/1.1, so we
558
564
        # check for the literal string.
594
600
    Daughter classes are expected to override _req_handler_class
595
601
    """
596
602
 
 
603
    scenarios = multiply_scenarios(
 
604
        vary_by_http_client_implementation(),
 
605
        vary_by_http_protocol_version(),
 
606
        )
 
607
 
597
608
    # Provide a useful default
598
609
    _req_handler_class = http_server.TestingHTTPRequestHandler
599
610
 
600
611
    def create_transport_readonly_server(self):
601
 
        return http_server.HttpServer(self._req_handler_class,
602
 
                                      protocol_version=self._protocol_version)
 
612
        server = http_server.HttpServer(self._req_handler_class,
 
613
                                        protocol_version=self._protocol_version)
 
614
        server._url_protocol = self._url_protocol
 
615
        return server
603
616
 
604
617
    def _testing_pycurl(self):
605
 
        return pycurl_present and self._transport == PyCurlTransport
 
618
        # TODO: This is duplicated for lots of the classes in this file
 
619
        return (features.pycurl.available()
 
620
                and self._transport == PyCurlTransport)
606
621
 
607
622
 
608
623
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
609
624
    """Whatever request comes in, close the connection"""
610
625
 
611
 
    def handle_one_request(self):
 
626
    def _handle_one_request(self):
612
627
        """Handle a single HTTP request, by abruptly closing the connection"""
613
628
        self.close_connection = 1
614
629
 
619
634
    _req_handler_class = WallRequestHandler
620
635
 
621
636
    def test_http_has(self):
622
 
        server = self.get_readonly_server()
623
 
        t = self._transport(server.get_url())
 
637
        t = self.get_readonly_transport()
624
638
        # Unfortunately httplib (see HTTPResponse._read_status
625
639
        # for details) make no distinction between a closed
626
640
        # socket and badly formatted status line, so we can't
627
641
        # just test for ConnectionError, we have to test
628
 
        # InvalidHttpResponse too.
629
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
642
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
 
643
        # instead of ConnectionError too.
 
644
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
 
645
                            errors.InvalidHttpResponse),
630
646
                          t.has, 'foo/bar')
631
647
 
632
648
    def test_http_get(self):
633
 
        server = self.get_readonly_server()
634
 
        t = self._transport(server.get_url())
635
 
        self.assertRaises((errors.ConnectionError, errors.InvalidHttpResponse),
 
649
        t = self.get_readonly_transport()
 
650
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
 
651
                           errors.InvalidHttpResponse),
636
652
                          t.get, 'foo/bar')
637
653
 
638
654
 
653
669
    _req_handler_class = BadStatusRequestHandler
654
670
 
655
671
    def test_http_has(self):
656
 
        server = self.get_readonly_server()
657
 
        t = self._transport(server.get_url())
 
672
        t = self.get_readonly_transport()
658
673
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
659
674
 
660
675
    def test_http_get(self):
661
 
        server = self.get_readonly_server()
662
 
        t = self._transport(server.get_url())
 
676
        t = self.get_readonly_transport()
663
677
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
664
678
 
665
679
 
670
684
        """Fakes handling a single HTTP request, returns a bad status"""
671
685
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
672
686
        self.wfile.write("Invalid status line\r\n")
 
687
        # If we don't close the connection pycurl will hang. Since this is a
 
688
        # stress test we don't *have* to respect the protocol, but we don't
 
689
        # have to sabotage it too much either.
 
690
        self.close_connection = True
673
691
        return False
674
692
 
675
693
 
681
699
 
682
700
    _req_handler_class = InvalidStatusRequestHandler
683
701
 
684
 
    def test_http_has(self):
685
 
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
686
 
            raise tests.KnownFailure(
687
 
                'pycurl hangs if the server send back garbage')
688
 
        super(TestInvalidStatusServer, self).test_http_has()
689
 
 
690
 
    def test_http_get(self):
691
 
        if self._testing_pycurl() and self._protocol_version == 'HTTP/1.1':
692
 
            raise tests.KnownFailure(
693
 
                'pycurl hangs if the server send back garbage')
694
 
        super(TestInvalidStatusServer, self).test_http_get()
695
 
 
696
702
 
697
703
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
698
704
    """Whatever request comes in, returns a bad protocol version"""
714
720
    _req_handler_class = BadProtocolRequestHandler
715
721
 
716
722
    def setUp(self):
717
 
        if pycurl_present and self._transport == PyCurlTransport:
 
723
        if self._testing_pycurl():
718
724
            raise tests.TestNotApplicable(
719
725
                "pycurl doesn't check the protocol version")
720
726
        super(TestBadProtocolServer, self).setUp()
721
727
 
722
728
    def test_http_has(self):
723
 
        server = self.get_readonly_server()
724
 
        t = self._transport(server.get_url())
 
729
        t = self.get_readonly_transport()
725
730
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
726
731
 
727
732
    def test_http_get(self):
728
 
        server = self.get_readonly_server()
729
 
        t = self._transport(server.get_url())
 
733
        t = self.get_readonly_transport()
730
734
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
731
735
 
732
736
 
746
750
    _req_handler_class = ForbiddenRequestHandler
747
751
 
748
752
    def test_http_has(self):
749
 
        server = self.get_readonly_server()
750
 
        t = self._transport(server.get_url())
 
753
        t = self.get_readonly_transport()
751
754
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
752
755
 
753
756
    def test_http_get(self):
754
 
        server = self.get_readonly_server()
755
 
        t = self._transport(server.get_url())
 
757
        t = self.get_readonly_transport()
756
758
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
757
759
 
758
760
 
764
766
        self.assertEqual(None, server.host)
765
767
        self.assertEqual(None, server.port)
766
768
 
767
 
    def test_setUp_and_tearDown(self):
 
769
    def test_setUp_and_stop(self):
768
770
        server = RecordingServer(expect_body_tail=None)
769
 
        server.setUp()
 
771
        server.start_server()
770
772
        try:
771
773
            self.assertNotEqual(None, server.host)
772
774
            self.assertNotEqual(None, server.port)
773
775
        finally:
774
 
            server.tearDown()
 
776
            server.stop_server()
775
777
        self.assertEqual(None, server.host)
776
778
        self.assertEqual(None, server.port)
777
779
 
778
780
    def test_send_receive_bytes(self):
779
 
        server = RecordingServer(expect_body_tail='c')
780
 
        server.setUp()
781
 
        self.addCleanup(server.tearDown)
 
781
        server = RecordingServer(expect_body_tail='c', scheme='http')
 
782
        self.start_server(server)
782
783
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
783
784
        sock.connect((server.host, server.port))
784
785
        sock.sendall('abc')
798
799
        self.build_tree_contents([('a', '0123456789')],)
799
800
 
800
801
    def test_readv(self):
801
 
        server = self.get_readonly_server()
802
 
        t = self._transport(server.get_url())
 
802
        t = self.get_readonly_transport()
803
803
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
804
804
        self.assertEqual(l[0], (0, '0'))
805
805
        self.assertEqual(l[1], (1, '1'))
807
807
        self.assertEqual(l[3], (9, '9'))
808
808
 
809
809
    def test_readv_out_of_order(self):
810
 
        server = self.get_readonly_server()
811
 
        t = self._transport(server.get_url())
 
810
        t = self.get_readonly_transport()
812
811
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
813
812
        self.assertEqual(l[0], (1, '1'))
814
813
        self.assertEqual(l[1], (9, '9'))
816
815
        self.assertEqual(l[3], (3, '34'))
817
816
 
818
817
    def test_readv_invalid_ranges(self):
819
 
        server = self.get_readonly_server()
820
 
        t = self._transport(server.get_url())
 
818
        t = self.get_readonly_transport()
821
819
 
822
820
        # This is intentionally reading off the end of the file
823
821
        # since we are sure that it cannot get there
831
829
 
832
830
    def test_readv_multiple_get_requests(self):
833
831
        server = self.get_readonly_server()
834
 
        t = self._transport(server.get_url())
 
832
        t = self.get_readonly_transport()
835
833
        # force transport to issue multiple requests
836
834
        t._max_readv_combine = 1
837
835
        t._max_get_ranges = 1
845
843
 
846
844
    def test_readv_get_max_size(self):
847
845
        server = self.get_readonly_server()
848
 
        t = self._transport(server.get_url())
 
846
        t = self.get_readonly_transport()
849
847
        # force transport to issue multiple requests by limiting the number of
850
848
        # bytes by request. Note that this apply to coalesced offsets only, a
851
849
        # single range will keep its size even if bigger than the limit.
860
858
 
861
859
    def test_complete_readv_leave_pipe_clean(self):
862
860
        server = self.get_readonly_server()
863
 
        t = self._transport(server.get_url())
 
861
        t = self.get_readonly_transport()
864
862
        # force transport to issue multiple requests
865
863
        t._get_max_size = 2
866
 
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
 
864
        list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
867
865
        # The server should have issued 3 requests
868
866
        self.assertEqual(3, server.GET_request_nb)
869
867
        self.assertEqual('0123456789', t.get_bytes('a'))
871
869
 
872
870
    def test_incomplete_readv_leave_pipe_clean(self):
873
871
        server = self.get_readonly_server()
874
 
        t = self._transport(server.get_url())
 
872
        t = self.get_readonly_transport()
875
873
        # force transport to issue multiple requests
876
874
        t._get_max_size = 2
877
875
        # Don't collapse readv results into a list so that we leave unread
946
944
    def get_multiple_ranges(self, file, file_size, ranges):
947
945
        self.send_response(206)
948
946
        self.send_header('Accept-Ranges', 'bytes')
 
947
        # XXX: this is strange; the 'random' name below seems undefined and
 
948
        # yet the tests pass -- mbp 2010-10-11 bug 658773
949
949
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
950
950
        self.send_header("Content-Type",
951
951
                         "multipart/byteranges; boundary=%s" % boundary)
1013
1013
                return
1014
1014
            self.send_range_content(file, start, end - start + 1)
1015
1015
            cur += 1
1016
 
        # No final boundary
 
1016
        # Final boundary
1017
1017
        self.wfile.write(boundary_line)
1018
1018
 
1019
1019
 
1027
1027
 
1028
1028
    def test_readv_with_short_reads(self):
1029
1029
        server = self.get_readonly_server()
1030
 
        t = self._transport(server.get_url())
 
1030
        t = self.get_readonly_transport()
1031
1031
        # Force separate ranges for each offset
1032
1032
        t._bytes_to_read_before_seek = 0
1033
1033
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1048
1048
        # that mode
1049
1049
        self.assertEqual('single', t._range_hint)
1050
1050
 
 
1051
 
 
1052
class TruncatedBeforeBoundaryRequestHandler(
 
1053
    http_server.TestingHTTPRequestHandler):
 
1054
    """Truncation before a boundary, like in bug 198646"""
 
1055
 
 
1056
    _truncated_ranges = 1
 
1057
 
 
1058
    def get_multiple_ranges(self, file, file_size, ranges):
 
1059
        self.send_response(206)
 
1060
        self.send_header('Accept-Ranges', 'bytes')
 
1061
        boundary = 'tagada'
 
1062
        self.send_header('Content-Type',
 
1063
                         'multipart/byteranges; boundary=%s' % boundary)
 
1064
        boundary_line = '--%s\r\n' % boundary
 
1065
        # Calculate the Content-Length
 
1066
        content_length = 0
 
1067
        for (start, end) in ranges:
 
1068
            content_length += len(boundary_line)
 
1069
            content_length += self._header_line_length(
 
1070
                'Content-type', 'application/octet-stream')
 
1071
            content_length += self._header_line_length(
 
1072
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
 
1073
            content_length += len('\r\n') # end headers
 
1074
            content_length += end - start # + 1
 
1075
        content_length += len(boundary_line)
 
1076
        self.send_header('Content-length', content_length)
 
1077
        self.end_headers()
 
1078
 
 
1079
        # Send the multipart body
 
1080
        cur = 0
 
1081
        for (start, end) in ranges:
 
1082
            if cur + self._truncated_ranges >= len(ranges):
 
1083
                # Abruptly ends the response and close the connection
 
1084
                self.close_connection = 1
 
1085
                return
 
1086
            self.wfile.write(boundary_line)
 
1087
            self.send_header('Content-type', 'application/octet-stream')
 
1088
            self.send_header('Content-Range', 'bytes %d-%d/%d'
 
1089
                             % (start, end, file_size))
 
1090
            self.end_headers()
 
1091
            self.send_range_content(file, start, end - start + 1)
 
1092
            cur += 1
 
1093
        # Final boundary
 
1094
        self.wfile.write(boundary_line)
 
1095
 
 
1096
 
 
1097
class TestTruncatedBeforeBoundary(TestSpecificRequestHandler):
 
1098
    """Tests the case of bug 198646, disconnecting before a boundary."""
 
1099
 
 
1100
    _req_handler_class = TruncatedBeforeBoundaryRequestHandler
 
1101
 
 
1102
    def setUp(self):
 
1103
        super(TestTruncatedBeforeBoundary, self).setUp()
 
1104
        self.build_tree_contents([('a', '0123456789')],)
 
1105
 
 
1106
    def test_readv_with_short_reads(self):
 
1107
        server = self.get_readonly_server()
 
1108
        t = self.get_readonly_transport()
 
1109
        # Force separate ranges for each offset
 
1110
        t._bytes_to_read_before_seek = 0
 
1111
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
 
1112
        self.assertEqual((0, '0'), ireadv.next())
 
1113
        self.assertEqual((2, '2'), ireadv.next())
 
1114
        self.assertEqual((4, '45'), ireadv.next())
 
1115
        self.assertEqual((9, '9'), ireadv.next())
 
1116
 
 
1117
 
1051
1118
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1052
1119
    """Errors out when range specifiers exceed the limit"""
1053
1120
 
1077
1144
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1078
1145
    """Tests readv requests against a server erroring out on too much ranges."""
1079
1146
 
 
1147
    scenarios = multiply_scenarios(
 
1148
        vary_by_http_client_implementation(),
 
1149
        vary_by_http_protocol_version(),
 
1150
        )
 
1151
 
1080
1152
    # Requests with more range specifiers will error out
1081
1153
    range_limit = 3
1082
1154
 
1084
1156
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1085
1157
                                      protocol_version=self._protocol_version)
1086
1158
 
1087
 
    def get_transport(self):
1088
 
        return self._transport(self.get_readonly_server().get_url())
1089
 
 
1090
1159
    def setUp(self):
1091
1160
        http_utils.TestCaseWithWebserver.setUp(self)
1092
1161
        # We need to manipulate ranges that correspond to real chunks in the
1096
1165
        self.build_tree_contents([('a', content)],)
1097
1166
 
1098
1167
    def test_few_ranges(self):
1099
 
        t = self.get_transport()
 
1168
        t = self.get_readonly_transport()
1100
1169
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1101
1170
        self.assertEqual(l[0], (0, '0000'))
1102
1171
        self.assertEqual(l[1], (1024, '0001'))
1103
1172
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1104
1173
 
1105
1174
    def test_more_ranges(self):
1106
 
        t = self.get_transport()
 
1175
        t = self.get_readonly_transport()
1107
1176
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1108
1177
        self.assertEqual(l[0], (0, '0000'))
1109
1178
        self.assertEqual(l[1], (1024, '0001'))
1120
1189
    Only the urllib implementation is tested here.
1121
1190
    """
1122
1191
 
1123
 
    def setUp(self):
1124
 
        tests.TestCase.setUp(self)
1125
 
        self._old_env = {}
1126
 
 
1127
 
    def tearDown(self):
1128
 
        self._restore_env()
1129
 
        tests.TestCase.tearDown(self)
1130
 
 
1131
 
    def _install_env(self, env):
1132
 
        for name, value in env.iteritems():
1133
 
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1134
 
 
1135
 
    def _restore_env(self):
1136
 
        for name, value in self._old_env.iteritems():
1137
 
            osutils.set_or_unset_env(name, value)
1138
 
 
1139
1192
    def _proxied_request(self):
1140
1193
        handler = _urllib2_wrappers.ProxyHandler()
1141
 
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
 
1194
        request = _urllib2_wrappers.Request('GET', 'http://baz/buzzle')
1142
1195
        handler.set_proxy(request, 'http')
1143
1196
        return request
1144
1197
 
 
1198
    def assertEvaluateProxyBypass(self, expected, host, no_proxy):
 
1199
        handler = _urllib2_wrappers.ProxyHandler()
 
1200
        self.assertEquals(expected,
 
1201
                          handler.evaluate_proxy_bypass(host, no_proxy))
 
1202
 
1145
1203
    def test_empty_user(self):
1146
 
        self._install_env({'http_proxy': 'http://bar.com'})
 
1204
        self.overrideEnv('http_proxy', 'http://bar.com')
 
1205
        request = self._proxied_request()
 
1206
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
 
1207
 
 
1208
    def test_user_with_at(self):
 
1209
        self.overrideEnv('http_proxy',
 
1210
                         'http://username@domain:password@proxy_host:1234')
1147
1211
        request = self._proxied_request()
1148
1212
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1149
1213
 
1150
1214
    def test_invalid_proxy(self):
1151
1215
        """A proxy env variable without scheme"""
1152
 
        self._install_env({'http_proxy': 'host:1234'})
 
1216
        self.overrideEnv('http_proxy', 'host:1234')
1153
1217
        self.assertRaises(errors.InvalidURL, self._proxied_request)
1154
1218
 
 
1219
    def test_evaluate_proxy_bypass_true(self):
 
1220
        """The host is not proxied"""
 
1221
        self.assertEvaluateProxyBypass(True, 'example.com', 'example.com')
 
1222
        self.assertEvaluateProxyBypass(True, 'bzr.example.com', '*example.com')
 
1223
 
 
1224
    def test_evaluate_proxy_bypass_false(self):
 
1225
        """The host is proxied"""
 
1226
        self.assertEvaluateProxyBypass(False, 'bzr.example.com', None)
 
1227
 
 
1228
    def test_evaluate_proxy_bypass_unknown(self):
 
1229
        """The host is not explicitly proxied"""
 
1230
        self.assertEvaluateProxyBypass(None, 'example.com', 'not.example.com')
 
1231
        self.assertEvaluateProxyBypass(None, 'bzr.example.com', 'example.com')
 
1232
 
 
1233
    def test_evaluate_proxy_bypass_empty_entries(self):
 
1234
        """Ignore empty entries"""
 
1235
        self.assertEvaluateProxyBypass(None, 'example.com', '')
 
1236
        self.assertEvaluateProxyBypass(None, 'example.com', ',')
 
1237
        self.assertEvaluateProxyBypass(None, 'example.com', 'foo,,bar')
 
1238
 
1155
1239
 
1156
1240
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1157
1241
    """Tests proxy server.
1162
1246
    to the file names).
1163
1247
    """
1164
1248
 
 
1249
    scenarios = multiply_scenarios(
 
1250
        vary_by_http_client_implementation(),
 
1251
        vary_by_http_protocol_version(),
 
1252
        )
 
1253
 
1165
1254
    # FIXME: We don't have an https server available, so we don't
1166
 
    # test https connections.
 
1255
    # test https connections. --vila toolongago
1167
1256
 
1168
1257
    def setUp(self):
1169
1258
        super(TestProxyHttpServer, self).setUp()
 
1259
        self.transport_secondary_server = http_utils.ProxyServer
1170
1260
        self.build_tree_contents([('foo', 'contents of foo\n'),
1171
1261
                                  ('foo-proxied', 'proxied contents of foo\n')])
1172
1262
        # Let's setup some attributes for tests
1173
 
        self.server = self.get_readonly_server()
1174
 
        self.proxy_address = '%s:%d' % (self.server.host, self.server.port)
 
1263
        server = self.get_readonly_server()
 
1264
        self.server_host_port = '%s:%d' % (server.host, server.port)
1175
1265
        if self._testing_pycurl():
1176
1266
            # Oh my ! pycurl does not check for the port as part of
1177
1267
            # no_proxy :-( So we just test the host part
1178
 
            self.no_proxy_host = 'localhost'
 
1268
            self.no_proxy_host = server.host
1179
1269
        else:
1180
 
            self.no_proxy_host = self.proxy_address
 
1270
            self.no_proxy_host = self.server_host_port
1181
1271
        # The secondary server is the proxy
1182
 
        self.proxy = self.get_secondary_server()
1183
 
        self.proxy_url = self.proxy.get_url()
1184
 
        self._old_env = {}
 
1272
        self.proxy_url = self.get_secondary_url()
1185
1273
 
1186
1274
    def _testing_pycurl(self):
1187
 
        return pycurl_present and self._transport == PyCurlTransport
1188
 
 
1189
 
    def create_transport_secondary_server(self):
1190
 
        """Creates an http server that will serve files with
1191
 
        '-proxied' appended to their names.
1192
 
        """
1193
 
        return http_utils.ProxyServer(protocol_version=self._protocol_version)
1194
 
 
1195
 
    def _install_env(self, env):
1196
 
        for name, value in env.iteritems():
1197
 
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1198
 
 
1199
 
    def _restore_env(self):
1200
 
        for name, value in self._old_env.iteritems():
1201
 
            osutils.set_or_unset_env(name, value)
1202
 
 
1203
 
    def proxied_in_env(self, env):
1204
 
        self._install_env(env)
1205
 
        url = self.server.get_url()
1206
 
        t = self._transport(url)
1207
 
        try:
1208
 
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1209
 
        finally:
1210
 
            self._restore_env()
1211
 
 
1212
 
    def not_proxied_in_env(self, env):
1213
 
        self._install_env(env)
1214
 
        url = self.server.get_url()
1215
 
        t = self._transport(url)
1216
 
        try:
1217
 
            self.assertEqual('contents of foo\n', t.get('foo').read())
1218
 
        finally:
1219
 
            self._restore_env()
 
1275
        # TODO: This is duplicated for lots of the classes in this file
 
1276
        return (features.pycurl.available()
 
1277
                and self._transport == PyCurlTransport)
 
1278
 
 
1279
    def assertProxied(self):
 
1280
        t = self.get_readonly_transport()
 
1281
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
 
1282
 
 
1283
    def assertNotProxied(self):
 
1284
        t = self.get_readonly_transport()
 
1285
        self.assertEqual('contents of foo\n', t.get('foo').read())
1220
1286
 
1221
1287
    def test_http_proxy(self):
1222
 
        self.proxied_in_env({'http_proxy': self.proxy_url})
 
1288
        self.overrideEnv('http_proxy', self.proxy_url)
 
1289
        self.assertProxied()
1223
1290
 
1224
1291
    def test_HTTP_PROXY(self):
1225
1292
        if self._testing_pycurl():
1228
1295
            # about. Should we ?)
1229
1296
            raise tests.TestNotApplicable(
1230
1297
                'pycurl does not check HTTP_PROXY for security reasons')
1231
 
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
 
1298
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
 
1299
        self.assertProxied()
1232
1300
 
1233
1301
    def test_all_proxy(self):
1234
 
        self.proxied_in_env({'all_proxy': self.proxy_url})
 
1302
        self.overrideEnv('all_proxy', self.proxy_url)
 
1303
        self.assertProxied()
1235
1304
 
1236
1305
    def test_ALL_PROXY(self):
1237
 
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
 
1306
        self.overrideEnv('ALL_PROXY', self.proxy_url)
 
1307
        self.assertProxied()
1238
1308
 
1239
1309
    def test_http_proxy_with_no_proxy(self):
1240
 
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
1241
 
                                 'no_proxy': self.no_proxy_host})
 
1310
        self.overrideEnv('no_proxy', self.no_proxy_host)
 
1311
        self.overrideEnv('http_proxy', self.proxy_url)
 
1312
        self.assertNotProxied()
1242
1313
 
1243
1314
    def test_HTTP_PROXY_with_NO_PROXY(self):
1244
1315
        if self._testing_pycurl():
1245
1316
            raise tests.TestNotApplicable(
1246
1317
                'pycurl does not check HTTP_PROXY for security reasons')
1247
 
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1248
 
                                 'NO_PROXY': self.no_proxy_host})
 
1318
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
 
1319
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
 
1320
        self.assertNotProxied()
1249
1321
 
1250
1322
    def test_all_proxy_with_no_proxy(self):
1251
 
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
1252
 
                                 'no_proxy': self.no_proxy_host})
 
1323
        self.overrideEnv('no_proxy', self.no_proxy_host)
 
1324
        self.overrideEnv('all_proxy', self.proxy_url)
 
1325
        self.assertNotProxied()
1253
1326
 
1254
1327
    def test_ALL_PROXY_with_NO_PROXY(self):
1255
 
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1256
 
                                 'NO_PROXY': self.no_proxy_host})
 
1328
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
 
1329
        self.overrideEnv('ALL_PROXY', self.proxy_url)
 
1330
        self.assertNotProxied()
1257
1331
 
1258
1332
    def test_http_proxy_without_scheme(self):
 
1333
        self.overrideEnv('http_proxy', self.server_host_port)
1259
1334
        if self._testing_pycurl():
1260
1335
            # pycurl *ignores* invalid proxy env variables. If that ever change
1261
1336
            # in the future, this test will fail indicating that pycurl do not
1262
1337
            # ignore anymore such variables.
1263
 
            self.not_proxied_in_env({'http_proxy': self.proxy_address})
 
1338
            self.assertNotProxied()
1264
1339
        else:
1265
 
            self.assertRaises(errors.InvalidURL,
1266
 
                              self.proxied_in_env,
1267
 
                              {'http_proxy': self.proxy_address})
 
1340
            self.assertRaises(errors.InvalidURL, self.assertProxied)
1268
1341
 
1269
1342
 
1270
1343
class TestRanges(http_utils.TestCaseWithWebserver):
1271
1344
    """Test the Range header in GET methods."""
1272
1345
 
 
1346
    scenarios = multiply_scenarios(
 
1347
        vary_by_http_client_implementation(),
 
1348
        vary_by_http_protocol_version(),
 
1349
        )
 
1350
 
1273
1351
    def setUp(self):
1274
1352
        http_utils.TestCaseWithWebserver.setUp(self)
1275
1353
        self.build_tree_contents([('a', '0123456789')],)
1276
 
        server = self.get_readonly_server()
1277
 
        self.transport = self._transport(server.get_url())
1278
1354
 
1279
1355
    def create_transport_readonly_server(self):
1280
1356
        return http_server.HttpServer(protocol_version=self._protocol_version)
1281
1357
 
1282
1358
    def _file_contents(self, relpath, ranges):
 
1359
        t = self.get_readonly_transport()
1283
1360
        offsets = [ (start, end - start + 1) for start, end in ranges]
1284
 
        coalesce = self.transport._coalesce_offsets
 
1361
        coalesce = t._coalesce_offsets
1285
1362
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
1286
 
        code, data = self.transport._get(relpath, coalesced)
 
1363
        code, data = t._get(relpath, coalesced)
1287
1364
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1288
1365
        for start, end in ranges:
1289
1366
            data.seek(start)
1290
1367
            yield data.read(end - start + 1)
1291
1368
 
1292
1369
    def _file_tail(self, relpath, tail_amount):
1293
 
        code, data = self.transport._get(relpath, [], tail_amount)
 
1370
        t = self.get_readonly_transport()
 
1371
        code, data = t._get(relpath, [], tail_amount)
1294
1372
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1295
1373
        data.seek(-tail_amount, 2)
1296
1374
        return data.read(tail_amount)
1315
1393
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1316
1394
    """Test redirection between http servers."""
1317
1395
 
1318
 
    def create_transport_secondary_server(self):
1319
 
        """Create the secondary server redirecting to the primary server"""
1320
 
        new = self.get_readonly_server()
1321
 
 
1322
 
        redirecting = http_utils.HTTPServerRedirecting(
1323
 
            protocol_version=self._protocol_version)
1324
 
        redirecting.redirect_to(new.host, new.port)
1325
 
        return redirecting
 
1396
    scenarios = multiply_scenarios(
 
1397
        vary_by_http_client_implementation(),
 
1398
        vary_by_http_protocol_version(),
 
1399
        )
1326
1400
 
1327
1401
    def setUp(self):
1328
1402
        super(TestHTTPRedirections, self).setUp()
1330
1404
                                  ('bundle',
1331
1405
                                  '# Bazaar revision bundle v0.9\n#\n')
1332
1406
                                  ],)
1333
 
        # The requests to the old server will be redirected to the new server
1334
 
        self.old_transport = self._transport(self.old_server.get_url())
1335
1407
 
1336
1408
    def test_redirected(self):
1337
 
        self.assertRaises(errors.RedirectRequested, self.old_transport.get, 'a')
1338
 
        t = self._transport(self.new_server.get_url())
1339
 
        self.assertEqual('0123456789', t.get('a').read())
1340
 
 
1341
 
    def test_read_redirected_bundle_from_url(self):
1342
 
        from bzrlib.bundle import read_bundle_from_url
1343
 
        url = self.old_transport.abspath('bundle')
1344
 
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1345
 
                read_bundle_from_url, url)
1346
 
        # If read_bundle_from_url was successful we get an empty bundle
1347
 
        self.assertEqual([], bundle.revisions)
 
1409
        self.assertRaises(errors.RedirectRequested,
 
1410
                          self.get_old_transport().get, 'a')
 
1411
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
1348
1412
 
1349
1413
 
1350
1414
class RedirectedRequest(_urllib2_wrappers.Request):
1363
1427
        self.follow_redirections = True
1364
1428
 
1365
1429
 
 
1430
def install_redirected_request(test):
 
1431
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
 
1432
 
 
1433
 
 
1434
def cleanup_http_redirection_connections(test):
 
1435
    # Some sockets are opened but never seen by _urllib, so we trap them at
 
1436
    # the _urllib2_wrappers level to be able to clean them up.
 
1437
    def socket_disconnect(sock):
 
1438
        try:
 
1439
            sock.shutdown(socket.SHUT_RDWR)
 
1440
            sock.close()
 
1441
        except socket.error:
 
1442
            pass
 
1443
    def connect(connection):
 
1444
        test.http_connect_orig(connection)
 
1445
        test.addCleanup(socket_disconnect, connection.sock)
 
1446
    test.http_connect_orig = test.overrideAttr(
 
1447
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
 
1448
    def connect(connection):
 
1449
        test.https_connect_orig(connection)
 
1450
        test.addCleanup(socket_disconnect, connection.sock)
 
1451
    test.https_connect_orig = test.overrideAttr(
 
1452
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
 
1453
 
 
1454
 
1366
1455
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1367
1456
    """Test redirections.
1368
1457
 
1377
1466
    -- vila 20070212
1378
1467
    """
1379
1468
 
 
1469
    scenarios = multiply_scenarios(
 
1470
        vary_by_http_client_implementation(),
 
1471
        vary_by_http_protocol_version(),
 
1472
        )
 
1473
 
1380
1474
    def setUp(self):
1381
 
        if pycurl_present and self._transport == PyCurlTransport:
 
1475
        if (features.pycurl.available()
 
1476
            and self._transport == PyCurlTransport):
1382
1477
            raise tests.TestNotApplicable(
1383
 
                "pycurl doesn't redirect silently annymore")
 
1478
                "pycurl doesn't redirect silently anymore")
1384
1479
        super(TestHTTPSilentRedirections, self).setUp()
1385
 
        self.setup_redirected_request()
1386
 
        self.addCleanup(self.cleanup_redirected_request)
 
1480
        install_redirected_request(self)
 
1481
        cleanup_http_redirection_connections(self)
1387
1482
        self.build_tree_contents([('a','a'),
1388
1483
                                  ('1/',),
1389
1484
                                  ('1/a', 'redirected once'),
1397
1492
                                  ('5/a', 'redirected 5 times'),
1398
1493
                                  ],)
1399
1494
 
1400
 
        self.old_transport = self._transport(self.old_server.get_url())
1401
 
 
1402
 
    def setup_redirected_request(self):
1403
 
        self.original_class = _urllib2_wrappers.Request
1404
 
        _urllib2_wrappers.Request = RedirectedRequest
1405
 
 
1406
 
    def cleanup_redirected_request(self):
1407
 
        _urllib2_wrappers.Request = self.original_class
1408
 
 
1409
 
    def create_transport_secondary_server(self):
1410
 
        """Create the secondary server, redirections are defined in the tests"""
1411
 
        return http_utils.HTTPServerRedirecting(
1412
 
            protocol_version=self._protocol_version)
1413
 
 
1414
1495
    def test_one_redirection(self):
1415
 
        t = self.old_transport
1416
 
 
1417
 
        req = RedirectedRequest('GET', t.abspath('a'))
1418
 
        req.follow_redirections = True
 
1496
        t = self.get_old_transport()
 
1497
        req = RedirectedRequest('GET', t._remote_path('a'))
1419
1498
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1420
1499
                                       self.new_server.port)
1421
1500
        self.old_server.redirections = \
1422
1501
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
1423
 
        self.assertEquals('redirected once',t._perform(req).read())
 
1502
        self.assertEqual('redirected once', t._perform(req).read())
1424
1503
 
1425
1504
    def test_five_redirections(self):
1426
 
        t = self.old_transport
1427
 
 
1428
 
        req = RedirectedRequest('GET', t.abspath('a'))
1429
 
        req.follow_redirections = True
 
1505
        t = self.get_old_transport()
 
1506
        req = RedirectedRequest('GET', t._remote_path('a'))
1430
1507
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1431
1508
                                       self.old_server.port)
1432
1509
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1438
1515
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1439
1516
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1440
1517
            ]
1441
 
        self.assertEquals('redirected 5 times',t._perform(req).read())
 
1518
        self.assertEqual('redirected 5 times', t._perform(req).read())
1442
1519
 
1443
1520
 
1444
1521
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1445
1522
    """Test transport.do_catching_redirections."""
1446
1523
 
 
1524
    scenarios = multiply_scenarios(
 
1525
        vary_by_http_client_implementation(),
 
1526
        vary_by_http_protocol_version(),
 
1527
        )
 
1528
 
1447
1529
    def setUp(self):
1448
1530
        super(TestDoCatchRedirections, self).setUp()
1449
1531
        self.build_tree_contents([('a', '0123456789'),],)
1450
 
 
1451
 
        self.old_transport = self._transport(self.old_server.get_url())
1452
 
 
1453
 
    def get_a(self, transport):
1454
 
        return transport.get('a')
 
1532
        cleanup_http_redirection_connections(self)
 
1533
 
 
1534
        self.old_transport = self.get_old_transport()
 
1535
 
 
1536
    def get_a(self, t):
 
1537
        return t.get('a')
1455
1538
 
1456
1539
    def test_no_redirection(self):
1457
 
        t = self._transport(self.new_server.get_url())
 
1540
        t = self.get_new_transport()
1458
1541
 
1459
1542
        # We use None for redirected so that we fail if redirected
1460
 
        self.assertEquals('0123456789',
1461
 
                          transport.do_catching_redirections(
 
1543
        self.assertEqual('0123456789',
 
1544
                         transport.do_catching_redirections(
1462
1545
                self.get_a, t, None).read())
1463
1546
 
1464
1547
    def test_one_redirection(self):
1465
1548
        self.redirections = 0
1466
1549
 
1467
 
        def redirected(transport, exception, redirection_notice):
 
1550
        def redirected(t, exception, redirection_notice):
1468
1551
            self.redirections += 1
1469
 
            dir, file = urlutils.split(exception.target)
1470
 
            return self._transport(dir)
 
1552
            redirected_t = t._redirected_to(exception.source, exception.target)
 
1553
            return redirected_t
1471
1554
 
1472
 
        self.assertEquals('0123456789',
1473
 
                          transport.do_catching_redirections(
 
1555
        self.assertEqual('0123456789',
 
1556
                         transport.do_catching_redirections(
1474
1557
                self.get_a, self.old_transport, redirected).read())
1475
 
        self.assertEquals(1, self.redirections)
 
1558
        self.assertEqual(1, self.redirections)
1476
1559
 
1477
1560
    def test_redirection_loop(self):
1478
1561
 
1487
1570
                          self.get_a, self.old_transport, redirected)
1488
1571
 
1489
1572
 
 
1573
def _setup_authentication_config(**kwargs):
 
1574
    conf = config.AuthenticationConfig()
 
1575
    conf._get_config().update({'httptest': kwargs})
 
1576
    conf._save()
 
1577
 
 
1578
 
 
1579
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
 
1580
    """Unit tests for glue by which urllib2 asks us for authentication"""
 
1581
 
 
1582
    def test_get_user_password_without_port(self):
 
1583
        """We cope if urllib2 doesn't tell us the port.
 
1584
 
 
1585
        See https://bugs.launchpad.net/bzr/+bug/654684
 
1586
        """
 
1587
        user = 'joe'
 
1588
        password = 'foo'
 
1589
        _setup_authentication_config(scheme='http', host='localhost',
 
1590
                                     user=user, password=password)
 
1591
        handler = _urllib2_wrappers.HTTPAuthHandler()
 
1592
        got_pass = handler.get_user_password(dict(
 
1593
            user='joe',
 
1594
            protocol='http',
 
1595
            host='localhost',
 
1596
            path='/',
 
1597
            realm='Realm',
 
1598
            ))
 
1599
        self.assertEquals((user, password), got_pass)
 
1600
 
 
1601
 
1490
1602
class TestAuth(http_utils.TestCaseWithWebserver):
1491
1603
    """Test authentication scheme"""
1492
1604
 
1493
 
    _auth_header = 'Authorization'
1494
 
    _password_prompt_prefix = ''
1495
 
    _username_prompt_prefix = ''
1496
 
    # Set by load_tests
1497
 
    _auth_server = None
 
1605
    scenarios = multiply_scenarios(
 
1606
        vary_by_http_client_implementation(),
 
1607
        vary_by_http_protocol_version(),
 
1608
        vary_by_http_auth_scheme(),
 
1609
        )
1498
1610
 
1499
1611
    def setUp(self):
1500
1612
        super(TestAuth, self).setUp()
1503
1615
                                  ('b', 'contents of b\n'),])
1504
1616
 
1505
1617
    def create_transport_readonly_server(self):
1506
 
        return self._auth_server(protocol_version=self._protocol_version)
 
1618
        server = self._auth_server(protocol_version=self._protocol_version)
 
1619
        server._url_protocol = self._url_protocol
 
1620
        return server
1507
1621
 
1508
1622
    def _testing_pycurl(self):
1509
 
        return pycurl_present and self._transport == PyCurlTransport
 
1623
        # TODO: This is duplicated for lots of the classes in this file
 
1624
        return (features.pycurl.available()
 
1625
                and self._transport == PyCurlTransport)
1510
1626
 
1511
1627
    def get_user_url(self, user, password):
1512
1628
        """Build an url embedding user and password"""
1520
1636
        return url
1521
1637
 
1522
1638
    def get_user_transport(self, user, password):
1523
 
        return self._transport(self.get_user_url(user, password))
 
1639
        t = transport.get_transport_from_url(
 
1640
            self.get_user_url(user, password))
 
1641
        return t
1524
1642
 
1525
1643
    def test_no_user(self):
1526
1644
        self.server.add_user('joe', 'foo')
1577
1695
        self.assertEqual('', ui.ui_factory.stdin.readline())
1578
1696
        stderr.seek(0)
1579
1697
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
1580
 
        self.assertEquals(expected_prompt, stderr.read(len(expected_prompt)))
1581
 
        self.assertEquals('', stdout.getvalue())
 
1698
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
 
1699
        self.assertEqual('', stdout.getvalue())
1582
1700
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1583
1701
                                    stderr.readline())
1584
1702
 
1599
1717
        self.assertEqual('', ui.ui_factory.stdin.readline())
1600
1718
        self._check_password_prompt(t._unqualified_scheme, 'joe',
1601
1719
                                    stderr.getvalue())
1602
 
        self.assertEquals('', stdout.getvalue())
 
1720
        self.assertEqual('', stdout.getvalue())
1603
1721
        # And we shouldn't prompt again for a different request
1604
1722
        # against the same transport.
1605
1723
        self.assertEqual('contents of b\n',t.get('b').read())
1615
1733
                              % (scheme.upper(),
1616
1734
                                 user, self.server.host, self.server.port,
1617
1735
                                 self.server.auth_realm)))
1618
 
        self.assertEquals(expected_prompt, actual_prompt)
 
1736
        self.assertEqual(expected_prompt, actual_prompt)
1619
1737
 
1620
1738
    def _expected_username_prompt(self, scheme):
1621
1739
        return (self._username_prompt_prefix
1635
1753
        self.server.add_user(user, password)
1636
1754
        t = self.get_user_transport(user, None)
1637
1755
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
1638
 
                                            stdout=tests.StringIOWrapper())
 
1756
                                            stderr=tests.StringIOWrapper())
1639
1757
        # Create a minimal config file with the right password
1640
 
        conf = config.AuthenticationConfig()
1641
 
        conf._get_config().update(
1642
 
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1643
 
                          'user': user, 'password': password}})
1644
 
        conf._save()
 
1758
        _setup_authentication_config(scheme='http', port=self.server.port,
 
1759
                                     user=user, password=password)
1645
1760
        # Issue a request to the server to connect
1646
1761
        self.assertEqual('contents of a\n',t.get('a').read())
1647
1762
        # stdin should have  been left untouched
1649
1764
        # Only one 'Authentication Required' error should occur
1650
1765
        self.assertEqual(1, self.server.auth_required_errors)
1651
1766
 
1652
 
    def test_user_from_auth_conf(self):
1653
 
        if self._testing_pycurl():
1654
 
            raise tests.TestNotApplicable(
1655
 
                'pycurl does not support authentication.conf')
1656
 
        user = 'joe'
1657
 
        password = 'foo'
1658
 
        self.server.add_user(user, password)
1659
 
        # Create a minimal config file with the right password
1660
 
        conf = config.AuthenticationConfig()
1661
 
        conf._get_config().update(
1662
 
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1663
 
                          'user': user, 'password': password}})
1664
 
        conf._save()
1665
 
        t = self.get_user_transport(None, None)
1666
 
        # Issue a request to the server to connect
1667
 
        self.assertEqual('contents of a\n', t.get('a').read())
1668
 
        # Only one 'Authentication Required' error should occur
1669
 
        self.assertEqual(1, self.server.auth_required_errors)
1670
 
 
1671
1767
    def test_changing_nonce(self):
1672
1768
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1673
1769
                                     http_utils.ProxyDigestAuthServer):
1674
1770
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
1675
1771
        if self._testing_pycurl():
1676
 
            raise tests.KnownFailure(
 
1772
            self.knownFailure(
1677
1773
                'pycurl does not handle a nonce change')
1678
1774
        self.server.add_user('joe', 'foo')
1679
1775
        t = self.get_user_transport('joe', 'foo')
1689
1785
        # initial 'who are you' and a second 'who are you' with the new nonce)
1690
1786
        self.assertEqual(2, self.server.auth_required_errors)
1691
1787
 
 
1788
    def test_user_from_auth_conf(self):
 
1789
        if self._testing_pycurl():
 
1790
            raise tests.TestNotApplicable(
 
1791
                'pycurl does not support authentication.conf')
 
1792
        user = 'joe'
 
1793
        password = 'foo'
 
1794
        self.server.add_user(user, password)
 
1795
        _setup_authentication_config(scheme='http', port=self.server.port,
 
1796
                                     user=user, password=password)
 
1797
        t = self.get_user_transport(None, None)
 
1798
        # Issue a request to the server to connect
 
1799
        self.assertEqual('contents of a\n', t.get('a').read())
 
1800
        # Only one 'Authentication Required' error should occur
 
1801
        self.assertEqual(1, self.server.auth_required_errors)
 
1802
 
 
1803
    def test_no_credential_leaks_in_log(self):
 
1804
        self.overrideAttr(debug, 'debug_flags', set(['http']))
 
1805
        user = 'joe'
 
1806
        password = 'very-sensitive-password'
 
1807
        self.server.add_user(user, password)
 
1808
        t = self.get_user_transport(user, password)
 
1809
        # Capture the debug calls to mutter
 
1810
        self.mutters = []
 
1811
        def mutter(*args):
 
1812
            lines = args[0] % args[1:]
 
1813
            # Some calls output multiple lines, just split them now since we
 
1814
            # care about a single one later.
 
1815
            self.mutters.extend(lines.splitlines())
 
1816
        self.overrideAttr(trace, 'mutter', mutter)
 
1817
        # Issue a request to the server to connect
 
1818
        self.assertEqual(True, t.has('a'))
 
1819
        # Only one 'Authentication Required' error should occur
 
1820
        self.assertEqual(1, self.server.auth_required_errors)
 
1821
        # Since the authentification succeeded, there should be a corresponding
 
1822
        # debug line
 
1823
        sent_auth_headers = [line for line in self.mutters
 
1824
                             if line.startswith('> %s' % (self._auth_header,))]
 
1825
        self.assertLength(1, sent_auth_headers)
 
1826
        self.assertStartsWith(sent_auth_headers[0],
 
1827
                              '> %s: <masked>' % (self._auth_header,))
1692
1828
 
1693
1829
 
1694
1830
class TestProxyAuth(TestAuth):
1695
 
    """Test proxy authentication schemes."""
1696
 
 
1697
 
    _auth_header = 'Proxy-authorization'
1698
 
    _password_prompt_prefix = 'Proxy '
1699
 
    _username_prompt_prefix = 'Proxy '
 
1831
    """Test proxy authentication schemes.
 
1832
 
 
1833
    This inherits from TestAuth to tweak the setUp and filter some failing
 
1834
    tests.
 
1835
    """
 
1836
 
 
1837
    scenarios = multiply_scenarios(
 
1838
        vary_by_http_client_implementation(),
 
1839
        vary_by_http_protocol_version(),
 
1840
        vary_by_http_proxy_auth_scheme(),
 
1841
        )
1700
1842
 
1701
1843
    def setUp(self):
1702
1844
        super(TestProxyAuth, self).setUp()
1703
 
        self._old_env = {}
1704
 
        self.addCleanup(self._restore_env)
1705
1845
        # Override the contents to avoid false positives
1706
1846
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1707
1847
                                  ('b', 'not proxied contents of b\n'),
1710
1850
                                  ])
1711
1851
 
1712
1852
    def get_user_transport(self, user, password):
1713
 
        self._install_env({'all_proxy': self.get_user_url(user, password)})
1714
 
        return self._transport(self.server.get_url())
1715
 
 
1716
 
    def _install_env(self, env):
1717
 
        for name, value in env.iteritems():
1718
 
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1719
 
 
1720
 
    def _restore_env(self):
1721
 
        for name, value in self._old_env.iteritems():
1722
 
            osutils.set_or_unset_env(name, value)
 
1853
        self.overrideEnv('all_proxy', self.get_user_url(user, password))
 
1854
        return TestAuth.get_user_transport(self, user, password)
1723
1855
 
1724
1856
    def test_empty_pass(self):
1725
1857
        if self._testing_pycurl():
1726
1858
            import pycurl
1727
1859
            if pycurl.version_info()[1] < '7.16.0':
1728
 
                raise tests.KnownFailure(
 
1860
                self.knownFailure(
1729
1861
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1730
1862
        super(TestProxyAuth, self).test_empty_pass()
1731
1863
 
1744
1876
        self.readfile = StringIO(socket_read_content)
1745
1877
        self.writefile = StringIO()
1746
1878
        self.writefile.close = lambda: None
 
1879
        self.close = lambda: None
1747
1880
 
1748
1881
    def makefile(self, mode='r', bufsize=None):
1749
1882
        if 'r' in mode:
1754
1887
 
1755
1888
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1756
1889
 
 
1890
    scenarios = multiply_scenarios(
 
1891
        vary_by_http_client_implementation(),
 
1892
        vary_by_http_protocol_version(),
 
1893
        )
 
1894
 
1757
1895
    def setUp(self):
1758
1896
        super(SmartHTTPTunnellingTest, self).setUp()
1759
1897
        # We use the VFS layer as part of HTTP tunnelling tests.
1760
 
        self._captureVar('BZR_NO_SMART_VFS', None)
 
1898
        self.overrideEnv('BZR_NO_SMART_VFS', None)
1761
1899
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
 
1900
        self.http_server = self.get_readonly_server()
1762
1901
 
1763
1902
    def create_transport_readonly_server(self):
1764
 
        return http_utils.HTTPServerWithSmarts(
 
1903
        server = http_utils.HTTPServerWithSmarts(
1765
1904
            protocol_version=self._protocol_version)
 
1905
        server._url_protocol = self._url_protocol
 
1906
        return server
1766
1907
 
1767
1908
    def test_open_bzrdir(self):
1768
1909
        branch = self.make_branch('relpath')
1769
 
        http_server = self.get_readonly_server()
1770
 
        url = http_server.get_url() + 'relpath'
 
1910
        url = self.http_server.get_url() + 'relpath'
1771
1911
        bd = bzrdir.BzrDir.open(url)
 
1912
        self.addCleanup(bd.transport.disconnect)
1772
1913
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1773
1914
 
1774
1915
    def test_bulk_data(self):
1776
1917
        # The 'readv' command in the smart protocol both sends and receives
1777
1918
        # bulk data, so we use that.
1778
1919
        self.build_tree(['data-file'])
1779
 
        http_server = self.get_readonly_server()
1780
 
        http_transport = self._transport(http_server.get_url())
 
1920
        http_transport = transport.get_transport_from_url(
 
1921
            self.http_server.get_url())
1781
1922
        medium = http_transport.get_smart_medium()
1782
1923
        # Since we provide the medium, the url below will be mostly ignored
1783
1924
        # during the test, as long as the path is '/'.
1791
1932
        post_body = 'hello\n'
1792
1933
        expected_reply_body = 'ok\x012\n'
1793
1934
 
1794
 
        http_server = self.get_readonly_server()
1795
 
        http_transport = self._transport(http_server.get_url())
 
1935
        http_transport = transport.get_transport_from_url(
 
1936
            self.http_server.get_url())
1796
1937
        medium = http_transport.get_smart_medium()
1797
1938
        response = medium.send_http_smart_request(post_body)
1798
1939
        reply_body = response.read()
1799
1940
        self.assertEqual(expected_reply_body, reply_body)
1800
1941
 
1801
1942
    def test_smart_http_server_post_request_handler(self):
1802
 
        httpd = self.get_readonly_server()._get_httpd()
 
1943
        httpd = self.http_server.server
1803
1944
 
1804
1945
        socket = SampleSocket(
1805
1946
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1837
1978
 
1838
1979
    def test_probe_smart_server(self):
1839
1980
        """Test error handling against server refusing smart requests."""
1840
 
        server = self.get_readonly_server()
1841
 
        t = self._transport(server.get_url())
 
1981
        t = self.get_readonly_transport()
1842
1982
        # No need to build a valid smart request here, the server will not even
1843
1983
        # try to interpret it.
1844
1984
        self.assertRaises(errors.SmartProtocolError,
1845
1985
                          t.get_smart_medium().send_http_smart_request,
1846
1986
                          'whatever')
1847
1987
 
 
1988
 
1848
1989
class Test_redirected_to(tests.TestCase):
1849
1990
 
 
1991
    scenarios = vary_by_http_client_implementation()
 
1992
 
1850
1993
    def test_redirected_to_subdir(self):
1851
1994
        t = self._transport('http://www.example.com/foo')
1852
1995
        r = t._redirected_to('http://www.example.com/foo',
1853
1996
                             'http://www.example.com/foo/subdir')
1854
1997
        self.assertIsInstance(r, type(t))
1855
1998
        # Both transports share the some connection
1856
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
1999
        self.assertEqual(t._get_connection(), r._get_connection())
 
2000
        self.assertEquals('http://www.example.com/foo/subdir/', r.base)
1857
2001
 
1858
2002
    def test_redirected_to_self_with_slash(self):
1859
2003
        t = self._transport('http://www.example.com/foo')
1863
2007
        # Both transports share the some connection (one can argue that we
1864
2008
        # should return the exact same transport here, but that seems
1865
2009
        # overkill).
1866
 
        self.assertEquals(t._get_connection(), r._get_connection())
 
2010
        self.assertEqual(t._get_connection(), r._get_connection())
1867
2011
 
1868
2012
    def test_redirected_to_host(self):
1869
2013
        t = self._transport('http://www.example.com/foo')
1870
2014
        r = t._redirected_to('http://www.example.com/foo',
1871
2015
                             'http://foo.example.com/foo/subdir')
1872
2016
        self.assertIsInstance(r, type(t))
 
2017
        self.assertEquals('http://foo.example.com/foo/subdir/',
 
2018
            r.external_url())
1873
2019
 
1874
2020
    def test_redirected_to_same_host_sibling_protocol(self):
1875
2021
        t = self._transport('http://www.example.com/foo')
1876
2022
        r = t._redirected_to('http://www.example.com/foo',
1877
2023
                             'https://www.example.com/foo')
1878
2024
        self.assertIsInstance(r, type(t))
 
2025
        self.assertEquals('https://www.example.com/foo/',
 
2026
            r.external_url())
1879
2027
 
1880
2028
    def test_redirected_to_same_host_different_protocol(self):
1881
2029
        t = self._transport('http://www.example.com/foo')
1882
2030
        r = t._redirected_to('http://www.example.com/foo',
1883
2031
                             'ftp://www.example.com/foo')
1884
2032
        self.assertNotEquals(type(r), type(t))
 
2033
        self.assertEquals('ftp://www.example.com/foo/', r.external_url())
 
2034
 
 
2035
    def test_redirected_to_same_host_specific_implementation(self):
 
2036
        t = self._transport('http://www.example.com/foo')
 
2037
        r = t._redirected_to('http://www.example.com/foo',
 
2038
                             'https+urllib://www.example.com/foo')
 
2039
        self.assertEquals('https://www.example.com/foo/', r.external_url())
1885
2040
 
1886
2041
    def test_redirected_to_different_host_same_user(self):
1887
2042
        t = self._transport('http://joe@www.example.com/foo')
1888
2043
        r = t._redirected_to('http://www.example.com/foo',
1889
2044
                             'https://foo.example.com/foo')
1890
2045
        self.assertIsInstance(r, type(t))
1891
 
        self.assertEquals(t._user, r._user)
 
2046
        self.assertEqual(t._parsed_url.user, r._parsed_url.user)
 
2047
        self.assertEquals('https://joe@foo.example.com/foo/', r.external_url())
1892
2048
 
1893
2049
 
1894
2050
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1903
2059
    line.
1904
2060
    """
1905
2061
 
1906
 
    def handle_one_request(self):
 
2062
    def _handle_one_request(self):
1907
2063
        tcs = self.server.test_case_server
1908
2064
        requestline = self.rfile.readline()
1909
2065
        headers = self.MessageClass(self.rfile, 0)
1947
2103
    pass
1948
2104
 
1949
2105
 
1950
 
if tests.HTTPSServerFeature.available():
 
2106
if features.HTTPSServerFeature.available():
1951
2107
    from bzrlib.tests import https_server
1952
2108
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1953
2109
        pass
1954
2110
 
1955
2111
 
1956
 
class TestActivity(tests.TestCase):
 
2112
class TestActivityMixin(object):
1957
2113
    """Test socket activity reporting.
1958
2114
 
1959
2115
    We use a special purpose server to control the bytes sent and received and
1963
2119
    def setUp(self):
1964
2120
        tests.TestCase.setUp(self)
1965
2121
        self.server = self._activity_server(self._protocol_version)
1966
 
        self.server.setUp()
1967
 
        self.activities = {}
 
2122
        self.server.start_server()
 
2123
        _activities = {} # Don't close over self and create a cycle
1968
2124
        def report_activity(t, bytes, direction):
1969
 
            count = self.activities.get(direction, 0)
 
2125
            count = _activities.get(direction, 0)
1970
2126
            count += bytes
1971
 
            self.activities[direction] = count
 
2127
            _activities[direction] = count
 
2128
        self.activities = _activities
1972
2129
 
1973
2130
        # We override at class level because constructors may propagate the
1974
2131
        # bound method and render instance overriding ineffective (an
1975
2132
        # alternative would be to define a specific ui factory instead...)
1976
 
        self.orig_report_activity = self._transport._report_activity
1977
 
        self._transport._report_activity = report_activity
1978
 
 
1979
 
    def tearDown(self):
1980
 
        self._transport._report_activity = self.orig_report_activity
1981
 
        self.server.tearDown()
1982
 
        tests.TestCase.tearDown(self)
 
2133
        self.overrideAttr(self._transport, '_report_activity', report_activity)
 
2134
        self.addCleanup(self.server.stop_server)
1983
2135
 
1984
2136
    def get_transport(self):
1985
 
        return self._transport(self.server.get_url())
 
2137
        t = self._transport(self.server.get_url())
 
2138
        # FIXME: Needs cleanup -- vila 20100611
 
2139
        return t
1986
2140
 
1987
2141
    def assertActivitiesMatch(self):
1988
2142
        self.assertEqual(self.server.bytes_read,
2093
2247
'''
2094
2248
        t = self.get_transport()
2095
2249
        # We must send a single line of body bytes, see
2096
 
        # PredefinedRequestHandler.handle_one_request
 
2250
        # PredefinedRequestHandler._handle_one_request
2097
2251
        code, f = t._post('abc def end-of-body\n')
2098
2252
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2099
2253
        self.assertActivitiesMatch()
 
2254
 
 
2255
 
 
2256
class TestActivity(tests.TestCase, TestActivityMixin):
 
2257
 
 
2258
    scenarios = multiply_scenarios(
 
2259
        vary_by_http_activity(),
 
2260
        vary_by_http_protocol_version(),
 
2261
        )
 
2262
 
 
2263
    def setUp(self):
 
2264
        TestActivityMixin.setUp(self)
 
2265
 
 
2266
 
 
2267
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
 
2268
 
 
2269
    # Unlike TestActivity, we are really testing ReportingFileSocket and
 
2270
    # ReportingSocket, so we don't need all the parametrization. Since
 
2271
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
 
2272
    # test them through their use by the transport than directly (that's a
 
2273
    # bit less clean but far more simpler and effective).
 
2274
    _activity_server = ActivityHTTPServer
 
2275
    _protocol_version = 'HTTP/1.1'
 
2276
 
 
2277
    def setUp(self):
 
2278
        self._transport =_urllib.HttpTransport_urllib
 
2279
        TestActivityMixin.setUp(self)
 
2280
 
 
2281
    def assertActivitiesMatch(self):
 
2282
        # Nothing to check here
 
2283
        pass
 
2284
 
 
2285
 
 
2286
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
 
2287
    """Test authentication on the redirected http server."""
 
2288
 
 
2289
    scenarios = vary_by_http_protocol_version()
 
2290
 
 
2291
    _auth_header = 'Authorization'
 
2292
    _password_prompt_prefix = ''
 
2293
    _username_prompt_prefix = ''
 
2294
    _auth_server = http_utils.HTTPBasicAuthServer
 
2295
    _transport = _urllib.HttpTransport_urllib
 
2296
 
 
2297
    def setUp(self):
 
2298
        super(TestAuthOnRedirected, self).setUp()
 
2299
        self.build_tree_contents([('a','a'),
 
2300
                                  ('1/',),
 
2301
                                  ('1/a', 'redirected once'),
 
2302
                                  ],)
 
2303
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2304
                                       self.new_server.port)
 
2305
        self.old_server.redirections = [
 
2306
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2307
        self.old_transport = self.get_old_transport()
 
2308
        self.new_server.add_user('joe', 'foo')
 
2309
        cleanup_http_redirection_connections(self)
 
2310
 
 
2311
    def create_transport_readonly_server(self):
 
2312
        server = self._auth_server(protocol_version=self._protocol_version)
 
2313
        server._url_protocol = self._url_protocol
 
2314
        return server
 
2315
 
 
2316
    def get_a(self, t):
 
2317
        return t.get('a')
 
2318
 
 
2319
    def test_auth_on_redirected_via_do_catching_redirections(self):
 
2320
        self.redirections = 0
 
2321
 
 
2322
        def redirected(t, exception, redirection_notice):
 
2323
            self.redirections += 1
 
2324
            redirected_t = t._redirected_to(exception.source, exception.target)
 
2325
            self.addCleanup(redirected_t.disconnect)
 
2326
            return redirected_t
 
2327
 
 
2328
        stdout = tests.StringIOWrapper()
 
2329
        stderr = tests.StringIOWrapper()
 
2330
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2331
                                            stdout=stdout, stderr=stderr)
 
2332
        self.assertEqual('redirected once',
 
2333
                         transport.do_catching_redirections(
 
2334
                self.get_a, self.old_transport, redirected).read())
 
2335
        self.assertEqual(1, self.redirections)
 
2336
        # stdin should be empty
 
2337
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2338
        # stdout should be empty, stderr will contains the prompts
 
2339
        self.assertEqual('', stdout.getvalue())
 
2340
 
 
2341
    def test_auth_on_redirected_via_following_redirections(self):
 
2342
        self.new_server.add_user('joe', 'foo')
 
2343
        stdout = tests.StringIOWrapper()
 
2344
        stderr = tests.StringIOWrapper()
 
2345
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
 
2346
                                            stdout=stdout, stderr=stderr)
 
2347
        t = self.old_transport
 
2348
        req = RedirectedRequest('GET', t.abspath('a'))
 
2349
        new_prefix = 'http://%s:%s' % (self.new_server.host,
 
2350
                                       self.new_server.port)
 
2351
        self.old_server.redirections = [
 
2352
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
 
2353
        self.assertEqual('redirected once', t._perform(req).read())
 
2354
        # stdin should be empty
 
2355
        self.assertEqual('', ui.ui_factory.stdin.readline())
 
2356
        # stdout should be empty, stderr will contains the prompts
 
2357
        self.assertEqual('', stdout.getvalue())
 
2358