/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4988.10.3 by John Arbash Meinel
Merge bzr.dev 5007, resolve conflict, update NEWS
1
# Copyright (C) 2005-2010 Canonical Ltd
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
2
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
7
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
12
#
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.16.68 by Martin Pool
- http url fixes suggested by Robey Pointer, and tests
16
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
17
"""Tests for HTTP implementations.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
18
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
19
This module defines a load_tests() method that parametrize tests classes for
20
transport implementation, http protocol versions and authentication schemes.
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
21
"""
1540.3.3 by Martin Pool
Review updates of pycurl transport
22
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
23
# TODO: Should be renamed to bzrlib.transport.http.tests?
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
24
# TODO: What about renaming to bzrlib.tests.transport.http ?
1540.3.22 by Martin Pool
[patch] Add TestCase.assertIsInstance
25
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
26
from cStringIO import StringIO
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
27
import httplib
2167.3.5 by v.ladeuil+lp at free
Tests for proxies, covering #74759.
28
import os
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
29
import select
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
30
import SimpleHTTPServer
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
31
import socket
2420.1.20 by Vincent Ladeuil
Fix test failure on pqm.
32
import sys
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
33
import threading
2000.2.2 by John Arbash Meinel
Update the urllib.has test.
34
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
35
import bzrlib
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
36
from bzrlib import (
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
37
    bzrdir,
2900.2.6 by Vincent Ladeuil
Make http aware of authentication config.
38
    config,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
39
    errors,
40
    osutils,
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
41
    remote as _mod_remote,
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
42
    tests,
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
43
    transport,
2363.4.12 by Vincent Ladeuil
Take jam's review comments into account. Fix typos, give better
44
    ui,
2164.2.22 by Vincent Ladeuil
Take Aaron's review comments into account.
45
    urlutils,
46
    )
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
47
from bzrlib.symbol_versioning import (
48
    deprecated_in,
49
    )
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
50
from bzrlib.tests import (
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
51
    features,
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
52
    http_server,
3111.1.7 by Vincent Ladeuil
Further refactoring.
53
    http_utils,
5247.2.5 by Vincent Ladeuil
Some cleanups.
54
    test_server,
3102.1.1 by Vincent Ladeuil
Rename bzrlib/test/HTTPTestUtils.py to bzrlib/tests/http_utils.py and fix
55
    )
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
56
from bzrlib.transport import (
57
    http,
58
    remote,
59
    )
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
60
from bzrlib.transport.http import (
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
61
    _urllib,
2164.2.29 by Vincent Ladeuil
Test the http redirection at the request level even if it's not
62
    _urllib2_wrappers,
2004.3.3 by vila
Better (but still incomplete) design for bogus servers.
63
    )
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
64
65
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
66
if features.pycurl.available():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
67
    from bzrlib.transport.http._pycurl import PyCurlTransport
68
69
70
def load_tests(standard_tests, module, loader):
71
    """Multiply tests for http clients and protocol versions."""
3945.1.7 by Vincent Ladeuil
Test against https.
72
    result = loader.suiteClass()
73
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
74
    # one for each transport implementation
3945.1.7 by Vincent Ladeuil
Test against https.
75
    t_tests, remaining_tests = tests.split_suite_by_condition(
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
76
        standard_tests, tests.condition_isinstance((
3945.1.7 by Vincent Ladeuil
Test against https.
77
                TestHttpTransportRegistration,
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
78
                TestHttpTransportUrls,
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
79
                Test_redirected_to,
3945.1.7 by Vincent Ladeuil
Test against https.
80
                )))
81
    transport_scenarios = [
82
        ('urllib', dict(_transport=_urllib.HttpTransport_urllib,
83
                        _server=http_server.HttpServer_urllib,
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
84
                        _url_protocol='http+urllib',)),
3945.1.7 by Vincent Ladeuil
Test against https.
85
        ]
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
86
    if features.pycurl.available():
3945.1.7 by Vincent Ladeuil
Test against https.
87
        transport_scenarios.append(
88
            ('pycurl', dict(_transport=PyCurlTransport,
89
                            _server=http_server.HttpServer_PyCurl,
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
90
                            _url_protocol='http+pycurl',)))
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
91
    tests.multiply_tests(t_tests, transport_scenarios, result)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
92
5273.1.4 by Vincent Ladeuil
The default http protocol version wasn't properly defined and as such not respected by some parametrized tests.
93
    protocol_scenarios = [
94
            ('HTTP/1.0',  dict(_protocol_version='HTTP/1.0')),
95
            ('HTTP/1.1',  dict(_protocol_version='HTTP/1.1')),
96
            ]
97
98
    # some tests are parametrized by the protocol version only
99
    p_tests, remaining_tests = tests.split_suite_by_condition(
100
        remaining_tests, tests.condition_isinstance((
101
                TestAuthOnRedirected,
102
                )))
103
    tests.multiply_tests(p_tests, protocol_scenarios, result)
104
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
105
    # each implementation tested with each HTTP version
3945.1.7 by Vincent Ladeuil
Test against https.
106
    tp_tests, remaining_tests = tests.split_suite_by_condition(
107
        remaining_tests, tests.condition_isinstance((
108
                SmartHTTPTunnellingTest,
109
                TestDoCatchRedirections,
110
                TestHTTPConnections,
111
                TestHTTPRedirections,
112
                TestHTTPSilentRedirections,
113
                TestLimitedRangeRequestServer,
114
                TestPost,
115
                TestProxyHttpServer,
116
                TestRanges,
117
                TestSpecificRequestHandler,
118
                )))
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
119
    tp_scenarios = tests.multiply_scenarios(transport_scenarios,
3945.1.7 by Vincent Ladeuil
Test against https.
120
                                            protocol_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
121
    tests.multiply_tests(tp_tests, tp_scenarios, result)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
122
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
123
    # proxy auth: each auth scheme on all http versions on all implementations.
124
    tppa_tests, remaining_tests = tests.split_suite_by_condition(
125
        remaining_tests, tests.condition_isinstance((
126
                TestProxyAuth,
127
                )))
128
    proxy_auth_scheme_scenarios = [
129
        ('basic', dict(_auth_server=http_utils.ProxyBasicAuthServer)),
130
        ('digest', dict(_auth_server=http_utils.ProxyDigestAuthServer)),
131
        ('basicdigest',
132
         dict(_auth_server=http_utils.ProxyBasicAndDigestAuthServer)),
133
        ]
134
    tppa_scenarios = tests.multiply_scenarios(tp_scenarios,
135
                                              proxy_auth_scheme_scenarios)
136
    tests.multiply_tests(tppa_tests, tppa_scenarios, result)
137
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
138
    # auth: each auth scheme on all http versions on all implementations.
3945.1.7 by Vincent Ladeuil
Test against https.
139
    tpa_tests, remaining_tests = tests.split_suite_by_condition(
140
        remaining_tests, tests.condition_isinstance((
141
                TestAuth,
142
                )))
143
    auth_scheme_scenarios = [
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
144
        ('basic', dict(_auth_server=http_utils.HTTPBasicAuthServer)),
145
        ('digest', dict(_auth_server=http_utils.HTTPDigestAuthServer)),
146
        ('basicdigest',
147
         dict(_auth_server=http_utils.HTTPBasicAndDigestAuthServer)),
3945.1.7 by Vincent Ladeuil
Test against https.
148
        ]
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
149
    tpa_scenarios = tests.multiply_scenarios(tp_scenarios,
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
150
                                             auth_scheme_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
151
    tests.multiply_tests(tpa_tests, tpa_scenarios, result)
3945.1.7 by Vincent Ladeuil
Test against https.
152
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
153
    # activity: on all http[s] versions on all implementations
3945.1.7 by Vincent Ladeuil
Test against https.
154
    tpact_tests, remaining_tests = tests.split_suite_by_condition(
155
        remaining_tests, tests.condition_isinstance((
156
                TestActivity,
157
                )))
158
    activity_scenarios = [
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
159
        ('urllib,http', dict(_activity_server=ActivityHTTPServer,
160
                             _transport=_urllib.HttpTransport_urllib,)),
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
161
        ]
3945.1.7 by Vincent Ladeuil
Test against https.
162
    if tests.HTTPSServerFeature.available():
163
        activity_scenarios.append(
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
164
            ('urllib,https', dict(_activity_server=ActivityHTTPSServer,
165
                                  _transport=_urllib.HttpTransport_urllib,)),)
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
166
    if features.pycurl.available():
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
167
        activity_scenarios.append(
168
            ('pycurl,http', dict(_activity_server=ActivityHTTPServer,
169
                                 _transport=PyCurlTransport,)),)
170
        if tests.HTTPSServerFeature.available():
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
171
            from bzrlib.tests import (
172
                ssl_certs,
173
                )
174
            # FIXME: Until we have a better way to handle self-signed
175
            # certificates (like allowing them in a test specific
176
            # authentication.conf for example), we need some specialized pycurl
177
            # transport for tests.
178
            class HTTPS_pycurl_transport(PyCurlTransport):
179
180
                def __init__(self, base, _from_transport=None):
181
                    super(HTTPS_pycurl_transport, self).__init__(
182
                        base, _from_transport)
183
                    self.cabundle = str(ssl_certs.build_path('ca.crt'))
184
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
185
            activity_scenarios.append(
186
                ('pycurl,https', dict(_activity_server=ActivityHTTPSServer,
187
                                      _transport=HTTPS_pycurl_transport,)),)
4382.1.1 by Vincent Ladeuil
Fix test failures for https/pycurl.
188
4382.1.3 by Vincent Ladeuil
Take more configurations into account.
189
    tpact_scenarios = tests.multiply_scenarios(activity_scenarios,
190
                                               protocol_scenarios)
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
191
    tests.multiply_tests(tpact_tests, tpact_scenarios, result)
3945.1.7 by Vincent Ladeuil
Test against https.
192
193
    # No parametrization for the remaining tests
194
    result.addTests(remaining_tests)
195
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
196
    return result
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
197
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
198
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
199
class FakeManager(object):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
200
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
201
    def __init__(self):
202
        self.credentials = []
2004.3.1 by vila
Test ConnectionError exceptions.
203
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
204
    def add_password(self, realm, host, username, password):
205
        self.credentials.append([realm, host, username, password])
206
1553.1.2 by James Henstridge
Add a test to make sure the user-agent header is being sent correctly.
207
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
208
class RecordingServer(object):
209
    """A fake HTTP server.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
210
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
211
    It records the bytes sent to it, and replies with a 200.
212
    """
213
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
214
    def __init__(self, expect_body_tail=None, scheme=''):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
215
        """Constructor.
216
217
        :type expect_body_tail: str
218
        :param expect_body_tail: a reply won't be sent until this string is
219
            received.
220
        """
221
        self._expect_body_tail = expect_body_tail
222
        self.host = None
223
        self.port = None
224
        self.received_bytes = ''
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
225
        self.scheme = scheme
226
227
    def get_url(self):
228
        return '%s://%s:%s/' % (self.scheme, self.host, self.port)
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
229
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
230
    def start_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
231
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
232
        self._sock.bind(('127.0.0.1', 0))
233
        self.host, self.port = self._sock.getsockname()
234
        self._ready = threading.Event()
5247.2.5 by Vincent Ladeuil
Some cleanups.
235
        self._thread = test_server.ThreadWithException(
236
            event=self._ready, target=self._accept_read_and_reply)
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
237
        self._thread.start()
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
238
        if 'threads' in tests.selftest_debug_flags:
5247.5.29 by Vincent Ladeuil
Fixed as per jam's review.
239
            sys.stderr.write('Thread started: %s\n' % (self._thread.ident,))
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
240
        self._ready.wait()
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
241
242
    def _accept_read_and_reply(self):
243
        self._sock.listen(1)
244
        self._ready.set()
5247.2.5 by Vincent Ladeuil
Some cleanups.
245
        conn, address = self._sock.accept()
246
        if self._expect_body_tail is not None:
247
            while not self.received_bytes.endswith(self._expect_body_tail):
248
                self.received_bytes += conn.recv(4096)
249
            conn.sendall('HTTP/1.1 200 OK\r\n')
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
250
        try:
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
251
            self._sock.close()
252
        except socket.error:
253
            # The client may have already closed the socket.
254
            pass
255
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
256
    def stop_server(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
257
        try:
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
258
            # Issue a fake connection to wake up the server and allow it to
259
            # finish quickly
5247.3.7 by Vincent Ladeuil
Provide connect_socket (socket.create_connection) for pythons older than 2.6.
260
            fake_conn = osutils.connect_socket((self.host, self.port))
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
261
            fake_conn.close()
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
262
        except socket.error:
263
            # We might have already closed it.  We don't care.
264
            pass
265
        self.host = None
266
        self.port = None
4731.2.4 by Vincent Ladeuil
No more leaks in http tests.
267
        self._thread.join()
4731.2.9 by Vincent Ladeuil
Implement a new -Ethreads to better track the leaks.
268
        if 'threads' in tests.selftest_debug_flags:
5247.5.29 by Vincent Ladeuil
Fixed as per jam's review.
269
            sys.stderr.write('Thread  joined: %s\n' % (self._thread.ident,))
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
270
271
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
272
class TestAuthHeader(tests.TestCase):
273
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
274
    def parse_header(self, header, auth_handler_class=None):
275
        if auth_handler_class is None:
276
            auth_handler_class = _urllib2_wrappers.AbstractAuthHandler
277
        self.auth_handler =  auth_handler_class()
278
        return self.auth_handler._parse_auth_header(header)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
279
280
    def test_empty_header(self):
281
        scheme, remainder = self.parse_header('')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
282
        self.assertEqual('', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
283
        self.assertIs(None, remainder)
284
285
    def test_negotiate_header(self):
286
        scheme, remainder = self.parse_header('Negotiate')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
287
        self.assertEqual('negotiate', scheme)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
288
        self.assertIs(None, remainder)
289
290
    def test_basic_header(self):
291
        scheme, remainder = self.parse_header(
292
            'Basic realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
293
        self.assertEqual('basic', scheme)
294
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
295
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
296
    def test_basic_extract_realm(self):
297
        scheme, remainder = self.parse_header(
298
            'Basic realm="Thou should not pass"',
299
            _urllib2_wrappers.BasicAuthHandler)
300
        match, realm = self.auth_handler.extract_realm(remainder)
301
        self.assertTrue(match is not None)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
302
        self.assertEqual('Thou should not pass', realm)
4284.1.1 by Vincent Ladeuil
Fix wrong realm extraction in http basic authentication (reported
303
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
304
    def test_digest_header(self):
305
        scheme, remainder = self.parse_header(
306
            'Digest realm="Thou should not pass"')
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
307
        self.assertEqual('digest', scheme)
308
        self.assertEqual('realm="Thou should not pass"', remainder)
4050.2.2 by Vincent Ladeuil
Ensures all auth handlers correctly parse all auth headers.
309
310
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
311
class TestHTTPServer(tests.TestCase):
312
    """Test the HTTP servers implementations."""
313
314
    def test_invalid_protocol(self):
315
        class BogusRequestHandler(http_server.TestingHTTPRequestHandler):
316
317
            protocol_version = 'HTTP/0.1'
318
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
319
        self.assertRaises(httplib.UnknownProtocol,
320
                          http_server.HttpServer, BogusRequestHandler)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
321
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
322
    def test_force_invalid_protocol(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
323
        self.assertRaises(httplib.UnknownProtocol,
324
                          http_server.HttpServer, protocol_version='HTTP/0.1')
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
325
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
326
    def test_server_start_and_stop(self):
327
        server = http_server.HttpServer()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
328
        self.addCleanup(server.stop_server)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
329
        server.start_server()
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
330
        self.assertTrue(server.server is not None)
331
        self.assertTrue(server.server.serving is not None)
5247.6.7 by Vincent Ladeuil
Merge propagate-exceptions into http-leaks resolving conflicts
332
        self.assertTrue(server.server.serving)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
333
334
    def test_create_http_server_one_zero(self):
335
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
336
337
            protocol_version = 'HTTP/1.0'
338
339
        server = http_server.HttpServer(RequestHandlerOneZero)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
340
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
341
        self.assertIsInstance(server.server, http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
342
343
    def test_create_http_server_one_one(self):
344
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
345
346
            protocol_version = 'HTTP/1.1'
347
348
        server = http_server.HttpServer(RequestHandlerOneOne)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
349
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
350
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
351
                              http_server.TestingThreadingHTTPServer)
352
353
    def test_create_http_server_force_one_one(self):
354
        class RequestHandlerOneZero(http_server.TestingHTTPRequestHandler):
355
356
            protocol_version = 'HTTP/1.0'
357
358
        server = http_server.HttpServer(RequestHandlerOneZero,
359
                                        protocol_version='HTTP/1.1')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
360
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
361
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
362
                              http_server.TestingThreadingHTTPServer)
363
364
    def test_create_http_server_force_one_zero(self):
365
        class RequestHandlerOneOne(http_server.TestingHTTPRequestHandler):
366
367
            protocol_version = 'HTTP/1.1'
368
369
        server = http_server.HttpServer(RequestHandlerOneOne,
370
                                        protocol_version='HTTP/1.0')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
371
        self.start_server(server)
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
372
        self.assertIsInstance(server.server,
3111.1.17 by Vincent Ladeuil
Add tests for the protocol version parameter.
373
                              http_server.TestingHTTPServer)
3111.1.4 by Vincent Ladeuil
Select the server depending on the request handler protocol. Add tests.
374
375
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
376
class TestWithTransport_pycurl(object):
377
    """Test case to inherit from if pycurl is present"""
378
379
    def _get_pycurl_maybe(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
380
        self.requireFeature(features.pycurl)
381
        return PyCurlTransport
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
382
383
    _transport = property(_get_pycurl_maybe)
384
385
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
386
class TestHttpUrls(tests.TestCase):
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
387
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
388
    # TODO: This should be moved to authorization tests once they
389
    # are written.
2004.1.40 by v.ladeuil+lp at free
Fix the race condition again and correct some small typos to be in
390
1185.40.20 by Robey Pointer
allow user:pass@ info in http urls to be used for auth; this should be easily expandable later to use auth config files
391
    def test_url_parsing(self):
392
        f = FakeManager()
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
393
        url = http.extract_auth('http://example.com', f)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
394
        self.assertEqual('http://example.com', url)
395
        self.assertEqual(0, len(f.credentials))
3111.1.30 by Vincent Ladeuil
Update NEWS. Some cosmetic changes.
396
        url = http.extract_auth(
4988.4.2 by Martin Pool
Change url to canonical.com or wiki, plus some doc improvements in passing
397
            'http://user:pass@example.com/bzr/bzr.dev', f)
398
        self.assertEqual('http://example.com/bzr/bzr.dev', url)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
399
        self.assertEqual(1, len(f.credentials))
4988.4.2 by Martin Pool
Change url to canonical.com or wiki, plus some doc improvements in passing
400
        self.assertEqual([None, 'example.com', 'user', 'pass'],
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
401
                         f.credentials[0])
2004.3.1 by vila
Test ConnectionError exceptions.
402
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
403
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
404
class TestHttpTransportUrls(tests.TestCase):
405
    """Test the http urls."""
406
407
    def test_abs_url(self):
408
        """Construction of absolute http URLs"""
409
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
410
        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')
414
        eq(t.abspath('.bzr/1//2/./3'),
415
           'http://bazaar-vcs.org/bzr/bzr.dev/.bzr/1/2/3')
416
417
    def test_invalid_http_urls(self):
418
        """Trap invalid construction of urls"""
419
        t = self._transport('http://bazaar-vcs.org/bzr/bzr.dev/')
420
        self.assertRaises(errors.InvalidURL,
421
                          self._transport,
422
                          'http://http://bazaar-vcs.org/bzr/bzr.dev/')
423
424
    def test_http_root_urls(self):
425
        """Construction of URLs from server root"""
426
        t = self._transport('http://bzr.ozlabs.org/')
427
        eq = self.assertEqualDiff
428
        eq(t.abspath('.bzr/tree-version'),
429
           'http://bzr.ozlabs.org/.bzr/tree-version')
430
431
    def test_http_impl_urls(self):
432
        """There are servers which ask for particular clients to connect"""
433
        server = self._server()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
434
        server.start_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
435
        try:
436
            url = server.get_url()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
437
            self.assertTrue(url.startswith('%s://' % self._url_protocol))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
438
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
439
            server.stop_server()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
440
441
3111.1.9 by Vincent Ladeuil
Most refactoring regarding parameterization for urllib/pycurl and custom
442
class TestHttps_pycurl(TestWithTransport_pycurl, tests.TestCase):
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
443
444
    # TODO: This should really be moved into another pycurl
445
    # specific test. When https tests will be implemented, take
446
    # this one into account.
447
    def test_pycurl_without_https_support(self):
448
        """Test that pycurl without SSL do not fail with a traceback.
449
450
        For the purpose of the test, we force pycurl to ignore
451
        https by supplying a fake version_info that do not
452
        support it.
453
        """
4913.2.13 by John Arbash Meinel
Finish the pycurl feature.
454
        self.requireFeature(features.pycurl)
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
455
        # Import the module locally now that we now it's available.
456
        pycurl = features.pycurl.module
3111.1.14 by Vincent Ladeuil
Fix test leakage.
457
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
458
        self.overrideAttr(pycurl, 'version_info',
459
                          # Fake the pycurl version_info This was taken from
460
                          # a windows pycurl without SSL (thanks to bialix)
461
                          lambda : (2,
462
                                    '7.13.2',
463
                                    462082,
464
                                    'i386-pc-win32',
465
                                    2576,
466
                                    None,
467
                                    0,
468
                                    None,
469
                                    ('ftp', 'gopher', 'telnet',
470
                                     'dict', 'ldap', 'http', 'file'),
471
                                    None,
472
                                    0,
473
                                    None))
4926.1.1 by Vincent Ladeuil
Fix ModuleFeature() side-effect.
474
        self.assertRaises(errors.DependencyNotPresent, self._transport,
475
                          'https://launchpad.net')
2294.3.1 by Vincent Ladeuil
Fix #85305 by issuing an exception instead of a traceback.
476
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
477
478
class TestHTTPConnections(http_utils.TestCaseWithWebserver):
479
    """Test the http connections."""
480
481
    def setUp(self):
482
        http_utils.TestCaseWithWebserver.setUp(self)
483
        self.build_tree(['foo/', 'foo/bar'], line_endings='binary',
484
                        transport=self.get_transport())
485
486
    def test_http_has(self):
487
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
488
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
489
        self.assertEqual(t.has('foo/bar'), True)
490
        self.assertEqual(len(server.logs), 1)
491
        self.assertContainsRe(server.logs[0],
492
            r'"HEAD /foo/bar HTTP/1.." (200|302) - "-" "bzr/')
493
494
    def test_http_has_not_found(self):
495
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
496
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
497
        self.assertEqual(t.has('not-found'), False)
498
        self.assertContainsRe(server.logs[1],
499
            r'"HEAD /not-found HTTP/1.." 404 - "-" "bzr/')
500
501
    def test_http_get(self):
502
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
503
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
504
        fp = t.get('foo/bar')
505
        self.assertEqualDiff(
506
            fp.read(),
507
            'contents of foo/bar\n')
508
        self.assertEqual(len(server.logs), 1)
509
        self.assertTrue(server.logs[0].find(
510
            '"GET /foo/bar HTTP/1.1" 200 - "-" "bzr/%s'
511
            % bzrlib.__version__) > -1)
512
513
    def test_has_on_bogus_host(self):
514
        # Get a free address and don't 'accept' on it, so that we
515
        # can be sure there is no http handler there, but set a
516
        # reasonable timeout to not slow down tests too much.
517
        default_timeout = socket.getdefaulttimeout()
518
        try:
519
            socket.setdefaulttimeout(2)
520
            s = socket.socket()
521
            s.bind(('localhost', 0))
522
            t = self._transport('http://%s:%s/' % s.getsockname())
523
            self.assertRaises(errors.ConnectionError, t.has, 'foo/bar')
524
        finally:
525
            socket.setdefaulttimeout(default_timeout)
526
527
528
class TestHttpTransportRegistration(tests.TestCase):
529
    """Test registrations of various http implementations"""
530
531
    def test_http_registered(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
532
        t = transport.get_transport('%s://foo.com/' % self._url_protocol)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
533
        self.assertIsInstance(t, transport.Transport)
534
        self.assertIsInstance(t, self._transport)
535
536
537
class TestPost(tests.TestCase):
538
539
    def test_post_body_is_received(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
540
        server = RecordingServer(expect_body_tail='end-of-body',
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
541
                                 scheme=self._url_protocol)
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
542
        self.start_server(server)
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
543
        url = server.get_url()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
544
        # FIXME: needs a cleanup -- vila 20100611
545
        http_transport = transport.get_transport(url)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
546
        code, response = http_transport._post('abc def end-of-body')
547
        self.assertTrue(
548
            server.received_bytes.startswith('POST /.bzr/smart HTTP/1.'))
549
        self.assertTrue('content-length: 19\r' in server.received_bytes.lower())
550
        # The transport should not be assuming that the server can accept
551
        # chunked encoding the first time it connects, because HTTP/1.1, so we
552
        # check for the literal string.
553
        self.assertTrue(
554
            server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
555
556
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
557
class TestRangeHeader(tests.TestCase):
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
558
    """Test range_header method"""
559
560
    def check_header(self, value, ranges=[], tail=0):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
561
        offsets = [ (start, end - start + 1) for start, end in ranges]
3111.1.10 by Vincent Ladeuil
Finish http parameterization, 24 auth tests failing for pycurl (not
562
        coalesce = transport.Transport._coalesce_offsets
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
563
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
564
        range_header = http.HttpTransportBase._range_header
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
565
        self.assertEqual(value, range_header(coalesced, tail))
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
566
567
    def test_range_header_single(self):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
568
        self.check_header('0-9', ranges=[(0,9)])
569
        self.check_header('100-109', ranges=[(100,109)])
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
570
571
    def test_range_header_tail(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
572
        self.check_header('-10', tail=10)
573
        self.check_header('-50', tail=50)
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
574
575
    def test_range_header_multi(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
576
        self.check_header('0-9,100-200,300-5000',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
577
                          ranges=[(0,9), (100, 200), (300,5000)])
578
579
    def test_range_header_mixed(self):
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
580
        self.check_header('0-9,300-5000,-50',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
581
                          ranges=[(0,9), (300,5000)],
582
                          tail=50)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
583
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
584
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
585
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
586
    """Tests a specific request handler.
587
3111.1.31 by Vincent Ladeuil
Review feeback.
588
    Daughter classes are expected to override _req_handler_class
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
589
    """
590
591
    # Provide a useful default
592
    _req_handler_class = http_server.TestingHTTPRequestHandler
593
594
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
595
        server = http_server.HttpServer(self._req_handler_class,
596
                                        protocol_version=self._protocol_version)
597
        server._url_protocol = self._url_protocol
598
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
599
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
600
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
601
        # TODO: This is duplicated for lots of the classes in this file
602
        return (features.pycurl.available()
603
                and self._transport == PyCurlTransport)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
604
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
605
606
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
607
    """Whatever request comes in, close the connection"""
608
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
609
    def _handle_one_request(self):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
610
        """Handle a single HTTP request, by abruptly closing the connection"""
611
        self.close_connection = 1
612
613
614
class TestWallServer(TestSpecificRequestHandler):
615
    """Tests exceptions during the connection phase"""
616
617
    _req_handler_class = WallRequestHandler
618
619
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
620
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
621
        # Unfortunately httplib (see HTTPResponse._read_status
622
        # for details) make no distinction between a closed
623
        # socket and badly formatted status line, so we can't
624
        # just test for ConnectionError, we have to test
4628.1.2 by Vincent Ladeuil
More complete fix.
625
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
626
        # instead of ConnectionError too.
627
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
628
                            errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
629
                          t.has, 'foo/bar')
630
631
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
632
        t = self.get_readonly_transport()
4628.1.2 by Vincent Ladeuil
More complete fix.
633
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
634
                           errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
635
                          t.get, 'foo/bar')
636
637
638
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
639
    """Whatever request comes in, returns a bad status"""
640
641
    def parse_request(self):
642
        """Fakes handling a single HTTP request, returns a bad status"""
643
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
644
        self.send_response(0, "Bad status")
645
        self.close_connection = 1
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
646
        return False
647
648
649
class TestBadStatusServer(TestSpecificRequestHandler):
650
    """Tests bad status from server."""
651
652
    _req_handler_class = BadStatusRequestHandler
653
654
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
655
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
656
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
657
658
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
659
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
660
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
661
662
663
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
664
    """Whatever request comes in, returns an invalid status"""
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
665
666
    def parse_request(self):
667
        """Fakes handling a single HTTP request, returns a bad status"""
668
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
669
        self.wfile.write("Invalid status line\r\n")
5247.6.6 by Vincent Ladeuil
Closing the connection is what pycurl was waiting for.
670
        # If we don't close the connection pycurl will hang. Since this is a
671
        # stress test we don't *have* to respect the protocol, but we don't
672
        # have to sabotage it too much either.
673
        self.close_connection = True
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
674
        return False
675
676
677
class TestInvalidStatusServer(TestBadStatusServer):
678
    """Tests invalid status from server.
679
680
    Both implementations raises the same error as for a bad status.
681
    """
682
683
    _req_handler_class = InvalidStatusRequestHandler
684
685
686
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
687
    """Whatever request comes in, returns a bad protocol version"""
688
689
    def parse_request(self):
690
        """Fakes handling a single HTTP request, returns a bad status"""
691
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
692
        # Returns an invalid protocol version, but curl just
693
        # ignores it and those cannot be tested.
694
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
695
                                           404,
696
                                           'Look at my protocol version'))
697
        return False
698
699
700
class TestBadProtocolServer(TestSpecificRequestHandler):
701
    """Tests bad protocol from server."""
702
703
    _req_handler_class = BadProtocolRequestHandler
704
705
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
706
        if self._testing_pycurl():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
707
            raise tests.TestNotApplicable(
708
                "pycurl doesn't check the protocol version")
709
        super(TestBadProtocolServer, self).setUp()
710
711
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
712
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
713
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
714
715
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
716
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
717
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
718
719
720
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
721
    """Whatever request comes in, returns a 403 code"""
722
723
    def parse_request(self):
724
        """Handle a single HTTP request, by replying we cannot handle it"""
725
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
726
        self.send_error(403)
727
        return False
728
729
730
class TestForbiddenServer(TestSpecificRequestHandler):
731
    """Tests forbidden server"""
732
733
    _req_handler_class = ForbiddenRequestHandler
734
735
    def test_http_has(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
736
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
737
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
738
739
    def test_http_get(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
740
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
741
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
742
743
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
744
class TestRecordingServer(tests.TestCase):
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
745
746
    def test_create(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
747
        server = RecordingServer(expect_body_tail=None)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
748
        self.assertEqual('', server.received_bytes)
749
        self.assertEqual(None, server.host)
750
        self.assertEqual(None, server.port)
751
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
752
    def test_setUp_and_stop(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
753
        server = RecordingServer(expect_body_tail=None)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
754
        server.start_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
755
        try:
756
            self.assertNotEqual(None, server.host)
757
            self.assertNotEqual(None, server.port)
758
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
759
            server.stop_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
760
        self.assertEqual(None, server.host)
761
        self.assertEqual(None, server.port)
762
763
    def test_send_receive_bytes(self):
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
764
        server = RecordingServer(expect_body_tail='c', scheme='http')
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
765
        self.start_server(server)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
766
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
767
        sock.connect((server.host, server.port))
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
768
        sock.sendall('abc')
769
        self.assertEqual('HTTP/1.1 200 OK\r\n',
770
                         osutils.recv_all(sock, 4096))
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
771
        self.assertEqual('abc', server.received_bytes)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
772
773
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
774
class TestRangeRequestServer(TestSpecificRequestHandler):
775
    """Tests readv requests against server.
776
777
    We test against default "normal" server.
778
    """
779
780
    def setUp(self):
781
        super(TestRangeRequestServer, self).setUp()
782
        self.build_tree_contents([('a', '0123456789')],)
783
784
    def test_readv(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
785
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
786
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
787
        self.assertEqual(l[0], (0, '0'))
788
        self.assertEqual(l[1], (1, '1'))
789
        self.assertEqual(l[2], (3, '34'))
790
        self.assertEqual(l[3], (9, '9'))
791
792
    def test_readv_out_of_order(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
793
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
794
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
795
        self.assertEqual(l[0], (1, '1'))
796
        self.assertEqual(l[1], (9, '9'))
797
        self.assertEqual(l[2], (0, '0'))
798
        self.assertEqual(l[3], (3, '34'))
799
800
    def test_readv_invalid_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
801
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
802
803
        # This is intentionally reading off the end of the file
804
        # since we are sure that it cannot get there
805
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
806
                              t.readv, 'a', [(1,1), (8,10)])
807
808
        # This is trying to seek past the end of the file, it should
809
        # also raise a special error
810
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
811
                              t.readv, 'a', [(12,2)])
812
813
    def test_readv_multiple_get_requests(self):
814
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
815
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
816
        # force transport to issue multiple requests
817
        t._max_readv_combine = 1
818
        t._max_get_ranges = 1
819
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
820
        self.assertEqual(l[0], (0, '0'))
821
        self.assertEqual(l[1], (1, '1'))
822
        self.assertEqual(l[2], (3, '34'))
823
        self.assertEqual(l[3], (9, '9'))
824
        # The server should have issued 4 requests
825
        self.assertEqual(4, server.GET_request_nb)
826
827
    def test_readv_get_max_size(self):
828
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
829
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
830
        # force transport to issue multiple requests by limiting the number of
831
        # bytes by request. Note that this apply to coalesced offsets only, a
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
832
        # single range will keep its size even if bigger than the limit.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
833
        t._get_max_size = 2
834
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
835
        self.assertEqual(l[0], (0, '0'))
836
        self.assertEqual(l[1], (1, '1'))
837
        self.assertEqual(l[2], (2, '2345'))
838
        self.assertEqual(l[3], (6, '6789'))
839
        # The server should have issued 3 requests
840
        self.assertEqual(3, server.GET_request_nb)
841
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
842
    def test_complete_readv_leave_pipe_clean(self):
843
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
844
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
845
        # force transport to issue multiple requests
846
        t._get_max_size = 2
847
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
848
        # The server should have issued 3 requests
849
        self.assertEqual(3, server.GET_request_nb)
850
        self.assertEqual('0123456789', t.get_bytes('a'))
851
        self.assertEqual(4, server.GET_request_nb)
852
853
    def test_incomplete_readv_leave_pipe_clean(self):
854
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
855
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
856
        # force transport to issue multiple requests
857
        t._get_max_size = 2
858
        # Don't collapse readv results into a list so that we leave unread
859
        # bytes on the socket
860
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
861
        self.assertEqual((0, '0'), ireadv.next())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
862
        # The server should have issued one request so far
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
863
        self.assertEqual(1, server.GET_request_nb)
864
        self.assertEqual('0123456789', t.get_bytes('a'))
865
        # get_bytes issued an additional request, the readv pending ones are
866
        # lost
867
        self.assertEqual(2, server.GET_request_nb)
868
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
869
870
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
871
    """Always reply to range request as if they were single.
872
873
    Don't be explicit about it, just to annoy the clients.
874
    """
875
876
    def get_multiple_ranges(self, file, file_size, ranges):
877
        """Answer as if it was a single range request and ignores the rest"""
878
        (start, end) = ranges[0]
879
        return self.get_single_range(file, file_size, start, end)
880
881
882
class TestSingleRangeRequestServer(TestRangeRequestServer):
883
    """Test readv against a server which accept only single range requests"""
884
885
    _req_handler_class = SingleRangeRequestHandler
886
887
888
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
889
    """Only reply to simple range requests, errors out on multiple"""
890
891
    def get_multiple_ranges(self, file, file_size, ranges):
892
        """Refuses the multiple ranges request"""
893
        if len(ranges) > 1:
894
            file.close()
895
            self.send_error(416, "Requested range not satisfiable")
896
            return
897
        (start, end) = ranges[0]
898
        return self.get_single_range(file, file_size, start, end)
899
900
901
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
902
    """Test readv against a server which only accept single range requests"""
903
904
    _req_handler_class = SingleOnlyRangeRequestHandler
905
906
907
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
908
    """Ignore range requests without notice"""
909
910
    def do_GET(self):
911
        # Update the statistics
912
        self.server.test_case_server.GET_request_nb += 1
913
        # Just bypass the range handling done by TestingHTTPRequestHandler
914
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
915
916
917
class TestNoRangeRequestServer(TestRangeRequestServer):
918
    """Test readv against a server which do not accept range requests"""
919
920
    _req_handler_class = NoRangeRequestHandler
921
922
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
923
class MultipleRangeWithoutContentLengthRequestHandler(
924
    http_server.TestingHTTPRequestHandler):
925
    """Reply to multiple range requests without content length header."""
926
927
    def get_multiple_ranges(self, file, file_size, ranges):
928
        self.send_response(206)
929
        self.send_header('Accept-Ranges', 'bytes')
930
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
931
        self.send_header("Content-Type",
932
                         "multipart/byteranges; boundary=%s" % boundary)
933
        self.end_headers()
934
        for (start, end) in ranges:
935
            self.wfile.write("--%s\r\n" % boundary)
936
            self.send_header("Content-type", 'application/octet-stream')
937
            self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
938
                                                                  end,
939
                                                                  file_size))
940
            self.end_headers()
941
            self.send_range_content(file, start, end - start + 1)
942
        # Final boundary
943
        self.wfile.write("--%s\r\n" % boundary)
944
945
946
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
947
948
    _req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
949
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
950
951
class TruncatedMultipleRangeRequestHandler(
952
    http_server.TestingHTTPRequestHandler):
953
    """Reply to multiple range requests truncating the last ones.
954
955
    This server generates responses whose Content-Length describes all the
956
    ranges, but fail to include the last ones leading to client short reads.
957
    This has been observed randomly with lighttpd (bug #179368).
958
    """
959
960
    _truncated_ranges = 2
961
962
    def get_multiple_ranges(self, file, file_size, ranges):
963
        self.send_response(206)
964
        self.send_header('Accept-Ranges', 'bytes')
965
        boundary = 'tagada'
966
        self.send_header('Content-Type',
967
                         'multipart/byteranges; boundary=%s' % boundary)
968
        boundary_line = '--%s\r\n' % boundary
969
        # Calculate the Content-Length
970
        content_length = 0
971
        for (start, end) in ranges:
972
            content_length += len(boundary_line)
973
            content_length += self._header_line_length(
974
                'Content-type', 'application/octet-stream')
975
            content_length += self._header_line_length(
976
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
977
            content_length += len('\r\n') # end headers
978
            content_length += end - start # + 1
979
        content_length += len(boundary_line)
980
        self.send_header('Content-length', content_length)
981
        self.end_headers()
982
983
        # Send the multipart body
984
        cur = 0
985
        for (start, end) in ranges:
986
            self.wfile.write(boundary_line)
987
            self.send_header('Content-type', 'application/octet-stream')
988
            self.send_header('Content-Range', 'bytes %d-%d/%d'
989
                             % (start, end, file_size))
990
            self.end_headers()
991
            if cur + self._truncated_ranges >= len(ranges):
992
                # Abruptly ends the response and close the connection
993
                self.close_connection = 1
994
                return
995
            self.send_range_content(file, start, end - start + 1)
996
            cur += 1
997
        # No final boundary
998
        self.wfile.write(boundary_line)
999
1000
1001
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
1002
1003
    _req_handler_class = TruncatedMultipleRangeRequestHandler
1004
1005
    def setUp(self):
1006
        super(TestTruncatedMultipleRangeServer, self).setUp()
1007
        self.build_tree_contents([('a', '0123456789')],)
1008
1009
    def test_readv_with_short_reads(self):
1010
        server = self.get_readonly_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1011
        t = self.get_readonly_transport()
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
1012
        # Force separate ranges for each offset
1013
        t._bytes_to_read_before_seek = 0
1014
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
1015
        self.assertEqual((0, '0'), ireadv.next())
1016
        self.assertEqual((2, '2'), ireadv.next())
1017
        if not self._testing_pycurl():
1018
            # Only one request have been issued so far (except for pycurl that
1019
            # try to read the whole response at once)
1020
            self.assertEqual(1, server.GET_request_nb)
1021
        self.assertEqual((4, '45'), ireadv.next())
1022
        self.assertEqual((9, '9'), ireadv.next())
1023
        # Both implementations issue 3 requests but:
1024
        # - urllib does two multiple (4 ranges, then 2 ranges) then a single
1025
        #   range,
1026
        # - pycurl does two multiple (4 ranges, 4 ranges) then a single range
1027
        self.assertEqual(3, server.GET_request_nb)
1028
        # Finally the client have tried a single range request and stays in
1029
        # that mode
1030
        self.assertEqual('single', t._range_hint)
1031
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1032
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1033
    """Errors out when range specifiers exceed the limit"""
1034
1035
    def get_multiple_ranges(self, file, file_size, ranges):
1036
        """Refuses the multiple ranges request"""
1037
        tcs = self.server.test_case_server
1038
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1039
            file.close()
1040
            # Emulate apache behavior
1041
            self.send_error(400, "Bad Request")
1042
            return
1043
        return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1044
            self, file, file_size, ranges)
1045
1046
1047
class LimitedRangeHTTPServer(http_server.HttpServer):
1048
    """An HttpServer erroring out on requests with too much range specifiers"""
1049
1050
    def __init__(self, request_handler=LimitedRangeRequestHandler,
1051
                 protocol_version=None,
1052
                 range_limit=None):
1053
        http_server.HttpServer.__init__(self, request_handler,
1054
                                        protocol_version=protocol_version)
1055
        self.range_limit = range_limit
1056
1057
1058
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1059
    """Tests readv requests against a server erroring out on too much ranges."""
1060
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1061
    # Requests with more range specifiers will error out
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1062
    range_limit = 3
1063
1064
    def create_transport_readonly_server(self):
1065
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1066
                                      protocol_version=self._protocol_version)
1067
1068
    def setUp(self):
1069
        http_utils.TestCaseWithWebserver.setUp(self)
1070
        # We need to manipulate ranges that correspond to real chunks in the
1071
        # response, so we build a content appropriately.
1072
        filler = ''.join(['abcdefghij' for x in range(102)])
1073
        content = ''.join(['%04d' % v + filler for v in range(16)])
1074
        self.build_tree_contents([('a', content)],)
1075
1076
    def test_few_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1077
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1078
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1079
        self.assertEqual(l[0], (0, '0000'))
1080
        self.assertEqual(l[1], (1024, '0001'))
1081
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1082
1083
    def test_more_ranges(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1084
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1085
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1086
        self.assertEqual(l[0], (0, '0000'))
1087
        self.assertEqual(l[1], (1024, '0001'))
1088
        self.assertEqual(l[2], (4096, '0004'))
1089
        self.assertEqual(l[3], (8192, '0008'))
1090
        # The server will refuse to serve the first request (too much ranges),
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1091
        # a second request will succeed.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1092
        self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1093
1094
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1095
class TestHttpProxyWhiteBox(tests.TestCase):
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1096
    """Whitebox test proxy http authorization.
1097
2420.1.3 by Vincent Ladeuil
Implement http proxy basic authentication.
1098
    Only the urllib implementation is tested here.
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1099
    """
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1100
1101
    def setUp(self):
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1102
        tests.TestCase.setUp(self)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1103
        self._old_env = {}
1104
1105
    def tearDown(self):
1106
        self._restore_env()
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1107
        tests.TestCase.tearDown(self)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1108
1109
    def _install_env(self, env):
1110
        for name, value in env.iteritems():
2420.1.2 by Vincent Ladeuil
Define tests for http proxy basic authentication. They fail.
1111
            self._old_env[name] = osutils.set_or_unset_env(name, value)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1112
1113
    def _restore_env(self):
1114
        for name, value in self._old_env.iteritems():
1115
            osutils.set_or_unset_env(name, value)
1116
1117
    def _proxied_request(self):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1118
        handler = _urllib2_wrappers.ProxyHandler()
1119
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1120
        handler.set_proxy(request, 'http')
1121
        return request
1122
1123
    def test_empty_user(self):
1124
        self._install_env({'http_proxy': 'http://bar.com'})
1125
        request = self._proxied_request()
1126
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1127
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1128
    def test_invalid_proxy(self):
1129
        """A proxy env variable without scheme"""
1130
        self._install_env({'http_proxy': 'host:1234'})
1131
        self.assertRaises(errors.InvalidURL, self._proxied_request)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1132
1133
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1134
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1135
    """Tests proxy server.
1136
1137
    Be aware that we do not setup a real proxy here. Instead, we
1138
    check that the *connection* goes through the proxy by serving
1139
    different content (the faked proxy server append '-proxied'
1140
    to the file names).
1141
    """
1142
1143
    # FIXME: We don't have an https server available, so we don't
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1144
    # test https connections. --vila toolongago
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1145
1146
    def setUp(self):
1147
        super(TestProxyHttpServer, self).setUp()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1148
        self.transport_secondary_server = http_utils.ProxyServer
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1149
        self.build_tree_contents([('foo', 'contents of foo\n'),
1150
                                  ('foo-proxied', 'proxied contents of foo\n')])
1151
        # Let's setup some attributes for tests
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1152
        server = self.get_readonly_server()
1153
        self.server_host_port = '%s:%d' % (server.host, server.port)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1154
        if self._testing_pycurl():
1155
            # Oh my ! pycurl does not check for the port as part of
1156
            # no_proxy :-( So we just test the host part
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1157
            self.no_proxy_host = server.host
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1158
        else:
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1159
            self.no_proxy_host = self.server_host_port
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1160
        # The secondary server is the proxy
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1161
        self.proxy_url = self.get_secondary_url()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1162
        self._old_env = {}
1163
1164
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1165
        # TODO: This is duplicated for lots of the classes in this file
1166
        return (features.pycurl.available()
1167
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1168
1169
    def _install_env(self, env):
1170
        for name, value in env.iteritems():
1171
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1172
1173
    def _restore_env(self):
1174
        for name, value in self._old_env.iteritems():
1175
            osutils.set_or_unset_env(name, value)
1176
1177
    def proxied_in_env(self, env):
1178
        self._install_env(env)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1179
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1180
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1181
            self.assertEqual('proxied contents of foo\n', t.get('foo').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1182
        finally:
1183
            self._restore_env()
1184
1185
    def not_proxied_in_env(self, env):
1186
        self._install_env(env)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1187
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1188
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1189
            self.assertEqual('contents of foo\n', t.get('foo').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1190
        finally:
1191
            self._restore_env()
1192
1193
    def test_http_proxy(self):
1194
        self.proxied_in_env({'http_proxy': self.proxy_url})
1195
1196
    def test_HTTP_PROXY(self):
1197
        if self._testing_pycurl():
1198
            # pycurl does not check HTTP_PROXY for security reasons
1199
            # (for use in a CGI context that we do not care
1200
            # about. Should we ?)
1201
            raise tests.TestNotApplicable(
1202
                'pycurl does not check HTTP_PROXY for security reasons')
1203
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1204
1205
    def test_all_proxy(self):
1206
        self.proxied_in_env({'all_proxy': self.proxy_url})
1207
1208
    def test_ALL_PROXY(self):
1209
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1210
1211
    def test_http_proxy_with_no_proxy(self):
1212
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
1213
                                 'no_proxy': self.no_proxy_host})
1214
1215
    def test_HTTP_PROXY_with_NO_PROXY(self):
1216
        if self._testing_pycurl():
1217
            raise tests.TestNotApplicable(
1218
                'pycurl does not check HTTP_PROXY for security reasons')
1219
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1220
                                 'NO_PROXY': self.no_proxy_host})
1221
1222
    def test_all_proxy_with_no_proxy(self):
1223
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
1224
                                 'no_proxy': self.no_proxy_host})
1225
1226
    def test_ALL_PROXY_with_NO_PROXY(self):
1227
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1228
                                 'NO_PROXY': self.no_proxy_host})
1229
1230
    def test_http_proxy_without_scheme(self):
1231
        if self._testing_pycurl():
1232
            # pycurl *ignores* invalid proxy env variables. If that ever change
1233
            # in the future, this test will fail indicating that pycurl do not
1234
            # ignore anymore such variables.
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1235
            self.not_proxied_in_env({'http_proxy': self.server_host_port})
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1236
        else:
1237
            self.assertRaises(errors.InvalidURL,
1238
                              self.proxied_in_env,
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1239
                              {'http_proxy': self.server_host_port})
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1240
1241
1242
class TestRanges(http_utils.TestCaseWithWebserver):
1243
    """Test the Range header in GET methods."""
1244
1245
    def setUp(self):
1246
        http_utils.TestCaseWithWebserver.setUp(self)
1247
        self.build_tree_contents([('a', '0123456789')],)
1248
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1249
    def create_transport_readonly_server(self):
1250
        return http_server.HttpServer(protocol_version=self._protocol_version)
1251
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1252
    def _file_contents(self, relpath, ranges):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1253
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1254
        offsets = [ (start, end - start + 1) for start, end in ranges]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1255
        coalesce = t._coalesce_offsets
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1256
        coalesced = list(coalesce(offsets, limit=0, fudge_factor=0))
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1257
        code, data = t._get(relpath, coalesced)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1258
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1259
        for start, end in ranges:
1260
            data.seek(start)
1261
            yield data.read(end - start + 1)
1262
1263
    def _file_tail(self, relpath, tail_amount):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1264
        t = self.get_readonly_transport()
1265
        code, data = t._get(relpath, [], tail_amount)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1266
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1267
        data.seek(-tail_amount, 2)
1268
        return data.read(tail_amount)
1269
1270
    def test_range_header(self):
1271
        # Valid ranges
1272
        map(self.assertEqual,['0', '234'],
1273
            list(self._file_contents('a', [(0,0), (2,4)])),)
1274
1275
    def test_range_header_tail(self):
1276
        self.assertEqual('789', self._file_tail('a', 3))
1277
1278
    def test_syntactically_invalid_range_header(self):
1279
        self.assertListRaises(errors.InvalidHttpRange,
1280
                          self._file_contents, 'a', [(4, 3)])
1281
1282
    def test_semantically_invalid_range_header(self):
1283
        self.assertListRaises(errors.InvalidHttpRange,
1284
                          self._file_contents, 'a', [(42, 128)])
1285
1286
1287
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1288
    """Test redirection between http servers."""
1289
1290
    def setUp(self):
1291
        super(TestHTTPRedirections, self).setUp()
1292
        self.build_tree_contents([('a', '0123456789'),
1293
                                  ('bundle',
1294
                                  '# Bazaar revision bundle v0.9\n#\n')
1295
                                  ],)
1296
1297
    def test_redirected(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1298
        self.assertRaises(errors.RedirectRequested,
1299
                          self.get_old_transport().get, 'a')
1300
        self.assertEqual('0123456789', self.get_new_transport().get('a').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1301
1302
    def test_read_redirected_bundle_from_url(self):
1303
        from bzrlib.bundle import read_bundle_from_url
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1304
        url = self.get_old_url('bundle')
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
1305
        bundle = self.applyDeprecated(deprecated_in((1, 12, 0)),
1306
                read_bundle_from_url, url)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1307
        # If read_bundle_from_url was successful we get an empty bundle
1308
        self.assertEqual([], bundle.revisions)
1309
1310
1311
class RedirectedRequest(_urllib2_wrappers.Request):
1312
    """Request following redirections. """
1313
1314
    init_orig = _urllib2_wrappers.Request.__init__
1315
1316
    def __init__(self, method, url, *args, **kwargs):
1317
        """Constructor.
1318
1319
        """
1320
        # Since the tests using this class will replace
1321
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1322
        # or we'll loop.
4208.3.2 by Andrew Bennetts
Fix one test failure in test_http under Python 2.7a0.
1323
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1324
        self.follow_redirections = True
1325
1326
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1327
def install_redirected_request(test):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1328
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1329
1330
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1331
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1332
    """Test redirections.
1333
1334
    http implementations do not redirect silently anymore (they
1335
    do not redirect at all in fact). The mechanism is still in
1336
    place at the _urllib2_wrappers.Request level and these tests
1337
    exercise it.
1338
1339
    For the pycurl implementation
1340
    the redirection have been deleted as we may deprecate pycurl
1341
    and I have no place to keep a working implementation.
1342
    -- vila 20070212
1343
    """
1344
1345
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1346
        if (features.pycurl.available()
1347
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1348
            raise tests.TestNotApplicable(
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1349
                "pycurl doesn't redirect silently anymore")
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1350
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1351
        install_redirected_request(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1352
        self.build_tree_contents([('a','a'),
1353
                                  ('1/',),
1354
                                  ('1/a', 'redirected once'),
1355
                                  ('2/',),
1356
                                  ('2/a', 'redirected twice'),
1357
                                  ('3/',),
1358
                                  ('3/a', 'redirected thrice'),
1359
                                  ('4/',),
1360
                                  ('4/a', 'redirected 4 times'),
1361
                                  ('5/',),
1362
                                  ('5/a', 'redirected 5 times'),
1363
                                  ],)
1364
1365
    def test_one_redirection(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1366
        t = self.get_old_transport()
1367
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1368
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1369
                                       self.new_server.port)
1370
        self.old_server.redirections = \
1371
            [('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1372
        self.assertEqual('redirected once', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1373
1374
    def test_five_redirections(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1375
        t = self.get_old_transport()
1376
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1377
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1378
                                       self.old_server.port)
1379
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1380
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1381
        self.old_server.redirections = [
1382
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1383
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1384
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1385
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1386
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1387
            ]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1388
        self.assertEqual('redirected 5 times', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1389
1390
1391
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1392
    """Test transport.do_catching_redirections."""
1393
1394
    def setUp(self):
1395
        super(TestDoCatchRedirections, self).setUp()
1396
        self.build_tree_contents([('a', '0123456789'),],)
1397
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1398
        self.old_transport = self.get_old_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1399
5247.3.31 by Vincent Ladeuil
Cleanup some imports in http_utils.py.
1400
    def get_a(self, t):
1401
        return t.get('a')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1402
1403
    def test_no_redirection(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1404
        t = self.get_new_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1405
1406
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1407
        self.assertEqual('0123456789',
1408
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1409
                self.get_a, t, None).read())
1410
1411
    def test_one_redirection(self):
1412
        self.redirections = 0
1413
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1414
        def redirected(t, exception, redirection_notice):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1415
            self.redirections += 1
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1416
            redirected_t = t._redirected_to(exception.source, exception.target)
1417
            return redirected_t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1418
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1419
        self.assertEqual('0123456789',
1420
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1421
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1422
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1423
1424
    def test_redirection_loop(self):
1425
1426
        def redirected(transport, exception, redirection_notice):
1427
            # By using the redirected url as a base dir for the
1428
            # *old* transport, we create a loop: a => a/a =>
1429
            # a/a/a
1430
            return self.old_transport.clone(exception.target)
1431
1432
        self.assertRaises(errors.TooManyRedirections,
1433
                          transport.do_catching_redirections,
1434
                          self.get_a, self.old_transport, redirected)
1435
1436
1437
class TestAuth(http_utils.TestCaseWithWebserver):
1438
    """Test authentication scheme"""
1439
1440
    _auth_header = 'Authorization'
1441
    _password_prompt_prefix = ''
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1442
    _username_prompt_prefix = ''
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1443
    # Set by load_tests
1444
    _auth_server = None
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1445
1446
    def setUp(self):
1447
        super(TestAuth, self).setUp()
1448
        self.server = self.get_readonly_server()
1449
        self.build_tree_contents([('a', 'contents of a\n'),
1450
                                  ('b', 'contents of b\n'),])
1451
1452
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1453
        server = self._auth_server(protocol_version=self._protocol_version)
1454
        server._url_protocol = self._url_protocol
1455
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1456
1457
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1458
        # TODO: This is duplicated for lots of the classes in this file
1459
        return (features.pycurl.available()
1460
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1461
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1462
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1463
        """Build an url embedding user and password"""
1464
        url = '%s://' % self.server._url_protocol
1465
        if user is not None:
1466
            url += user
1467
            if password is not None:
1468
                url += ':' + password
1469
            url += '@'
1470
        url += '%s:%s/' % (self.server.host, self.server.port)
1471
        return url
1472
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1473
    def get_user_transport(self, user, password):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1474
        t = transport.get_transport(self.get_user_url(user, password))
1475
        return t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1476
1477
    def test_no_user(self):
1478
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1479
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1480
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1481
        # Only one 'Authentication Required' error should occur
1482
        self.assertEqual(1, self.server.auth_required_errors)
1483
1484
    def test_empty_pass(self):
1485
        self.server.add_user('joe', '')
1486
        t = self.get_user_transport('joe', '')
1487
        self.assertEqual('contents of a\n', t.get('a').read())
1488
        # Only one 'Authentication Required' error should occur
1489
        self.assertEqual(1, self.server.auth_required_errors)
1490
1491
    def test_user_pass(self):
1492
        self.server.add_user('joe', 'foo')
1493
        t = self.get_user_transport('joe', 'foo')
1494
        self.assertEqual('contents of a\n', t.get('a').read())
1495
        # Only one 'Authentication Required' error should occur
1496
        self.assertEqual(1, self.server.auth_required_errors)
1497
1498
    def test_unknown_user(self):
1499
        self.server.add_user('joe', 'foo')
1500
        t = self.get_user_transport('bill', 'foo')
1501
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1502
        # Two 'Authentication Required' errors should occur (the
1503
        # initial 'who are you' and 'I don't know you, who are
1504
        # you').
1505
        self.assertEqual(2, self.server.auth_required_errors)
1506
1507
    def test_wrong_pass(self):
1508
        self.server.add_user('joe', 'foo')
1509
        t = self.get_user_transport('joe', 'bar')
1510
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1511
        # Two 'Authentication Required' errors should occur (the
1512
        # initial 'who are you' and 'this is not you, who are you')
1513
        self.assertEqual(2, self.server.auth_required_errors)
1514
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1515
    def test_prompt_for_username(self):
1516
        if self._testing_pycurl():
1517
            raise tests.TestNotApplicable(
1518
                'pycurl cannot prompt, it handles auth by embedding'
1519
                ' user:pass in urls only')
1520
1521
        self.server.add_user('joe', 'foo')
1522
        t = self.get_user_transport(None, None)
1523
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1524
        stderr = tests.StringIOWrapper()
1525
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1526
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1527
        self.assertEqual('contents of a\n',t.get('a').read())
1528
        # stdin should be empty
1529
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1530
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1531
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1532
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1533
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1534
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1535
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1536
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1537
    def test_prompt_for_password(self):
1538
        if self._testing_pycurl():
1539
            raise tests.TestNotApplicable(
1540
                'pycurl cannot prompt, it handles auth by embedding'
1541
                ' user:pass in urls only')
1542
1543
        self.server.add_user('joe', 'foo')
1544
        t = self.get_user_transport('joe', None)
1545
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1546
        stderr = tests.StringIOWrapper()
1547
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1548
                                            stdout=stdout, stderr=stderr)
1549
        self.assertEqual('contents of a\n', t.get('a').read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1550
        # stdin should be empty
1551
        self.assertEqual('', ui.ui_factory.stdin.readline())
1552
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1553
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1554
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1555
        # And we shouldn't prompt again for a different request
1556
        # against the same transport.
1557
        self.assertEqual('contents of b\n',t.get('b').read())
1558
        t2 = t.clone()
1559
        # And neither against a clone
1560
        self.assertEqual('contents of b\n',t2.get('b').read())
1561
        # Only one 'Authentication Required' error should occur
1562
        self.assertEqual(1, self.server.auth_required_errors)
1563
1564
    def _check_password_prompt(self, scheme, user, actual_prompt):
1565
        expected_prompt = (self._password_prompt_prefix
1566
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1567
                              % (scheme.upper(),
1568
                                 user, self.server.host, self.server.port,
1569
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1570
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1571
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1572
    def _expected_username_prompt(self, scheme):
1573
        return (self._username_prompt_prefix
1574
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1575
                                 self.server.host, self.server.port,
1576
                                 self.server.auth_realm))
1577
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1578
    def test_no_prompt_for_password_when_using_auth_config(self):
1579
        if self._testing_pycurl():
1580
            raise tests.TestNotApplicable(
1581
                'pycurl does not support authentication.conf'
1582
                ' since it cannot prompt')
1583
1584
        user =' joe'
1585
        password = 'foo'
1586
        stdin_content = 'bar\n'  # Not the right password
1587
        self.server.add_user(user, password)
1588
        t = self.get_user_transport(user, None)
1589
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1590
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1591
        # Create a minimal config file with the right password
1592
        conf = config.AuthenticationConfig()
1593
        conf._get_config().update(
1594
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1595
                          'user': user, 'password': password}})
1596
        conf._save()
1597
        # Issue a request to the server to connect
1598
        self.assertEqual('contents of a\n',t.get('a').read())
1599
        # stdin should have  been left untouched
1600
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1601
        # Only one 'Authentication Required' error should occur
1602
        self.assertEqual(1, self.server.auth_required_errors)
1603
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1604
    def test_user_from_auth_conf(self):
1605
        if self._testing_pycurl():
1606
            raise tests.TestNotApplicable(
1607
                'pycurl does not support authentication.conf')
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1608
        user = 'joe'
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1609
        password = 'foo'
1610
        self.server.add_user(user, password)
1611
        # Create a minimal config file with the right password
1612
        conf = config.AuthenticationConfig()
1613
        conf._get_config().update(
1614
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1615
                          'user': user, 'password': password}})
1616
        conf._save()
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1617
        t = self.get_user_transport(None, None)
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1618
        # Issue a request to the server to connect
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1619
        self.assertEqual('contents of a\n', t.get('a').read())
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1620
        # Only one 'Authentication Required' error should occur
1621
        self.assertEqual(1, self.server.auth_required_errors)
1622
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1623
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1624
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1625
                                     http_utils.ProxyDigestAuthServer):
1626
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1627
        if self._testing_pycurl():
1628
            raise tests.KnownFailure(
1629
                'pycurl does not handle a nonce change')
1630
        self.server.add_user('joe', 'foo')
1631
        t = self.get_user_transport('joe', 'foo')
1632
        self.assertEqual('contents of a\n', t.get('a').read())
1633
        self.assertEqual('contents of b\n', t.get('b').read())
1634
        # Only one 'Authentication Required' error should have
1635
        # occured so far
1636
        self.assertEqual(1, self.server.auth_required_errors)
1637
        # The server invalidates the current nonce
1638
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1639
        self.assertEqual('contents of a\n', t.get('a').read())
1640
        # Two 'Authentication Required' errors should occur (the
1641
        # initial 'who are you' and a second 'who are you' with the new nonce)
1642
        self.assertEqual(2, self.server.auth_required_errors)
1643
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1644
1645
1646
class TestProxyAuth(TestAuth):
1647
    """Test proxy authentication schemes."""
1648
1649
    _auth_header = 'Proxy-authorization'
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1650
    _password_prompt_prefix = 'Proxy '
1651
    _username_prompt_prefix = 'Proxy '
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1652
1653
    def setUp(self):
1654
        super(TestProxyAuth, self).setUp()
1655
        self._old_env = {}
1656
        self.addCleanup(self._restore_env)
1657
        # Override the contents to avoid false positives
1658
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1659
                                  ('b', 'not proxied contents of b\n'),
1660
                                  ('a-proxied', 'contents of a\n'),
1661
                                  ('b-proxied', 'contents of b\n'),
1662
                                  ])
1663
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1664
    def get_user_transport(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1665
        self._install_env({'all_proxy': self.get_user_url(user, password)})
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1666
        return TestAuth.get_user_transport(self, user, password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1667
1668
    def _install_env(self, env):
1669
        for name, value in env.iteritems():
1670
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1671
1672
    def _restore_env(self):
1673
        for name, value in self._old_env.iteritems():
1674
            osutils.set_or_unset_env(name, value)
1675
1676
    def test_empty_pass(self):
1677
        if self._testing_pycurl():
1678
            import pycurl
1679
            if pycurl.version_info()[1] < '7.16.0':
1680
                raise tests.KnownFailure(
1681
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1682
        super(TestProxyAuth, self).test_empty_pass()
1683
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1684
1685
class SampleSocket(object):
1686
    """A socket-like object for use in testing the HTTP request handler."""
1687
1688
    def __init__(self, socket_read_content):
1689
        """Constructs a sample socket.
1690
1691
        :param socket_read_content: a byte sequence
1692
        """
1693
        # Use plain python StringIO so we can monkey-patch the close method to
1694
        # not discard the contents.
1695
        from StringIO import StringIO
1696
        self.readfile = StringIO(socket_read_content)
1697
        self.writefile = StringIO()
1698
        self.writefile.close = lambda: None
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
1699
        self.close = lambda: None
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1700
1701
    def makefile(self, mode='r', bufsize=None):
1702
        if 'r' in mode:
1703
            return self.readfile
1704
        else:
1705
            return self.writefile
1706
1707
1708
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1709
1710
    def setUp(self):
1711
        super(SmartHTTPTunnellingTest, self).setUp()
1712
        # We use the VFS layer as part of HTTP tunnelling tests.
1713
        self._captureVar('BZR_NO_SMART_VFS', None)
1714
        self.transport_readonly_server = http_utils.HTTPServerWithSmarts
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1715
        self.http_server = self.get_readonly_server()
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1716
1717
    def create_transport_readonly_server(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1718
        server = http_utils.HTTPServerWithSmarts(
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1719
            protocol_version=self._protocol_version)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1720
        server._url_protocol = self._url_protocol
1721
        return server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1722
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1723
    def test_open_bzrdir(self):
1724
        branch = self.make_branch('relpath')
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1725
        url = self.http_server.get_url() + 'relpath'
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1726
        bd = bzrdir.BzrDir.open(url)
1727
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1728
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1729
    def test_bulk_data(self):
1730
        # We should be able to send and receive bulk data in a single message.
1731
        # The 'readv' command in the smart protocol both sends and receives
1732
        # bulk data, so we use that.
1733
        self.build_tree(['data-file'])
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1734
        http_transport = transport.get_transport(self.http_server.get_url())
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1735
        medium = http_transport.get_smart_medium()
1736
        # Since we provide the medium, the url below will be mostly ignored
1737
        # during the test, as long as the path is '/'.
1738
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1739
                                                  medium=medium)
1740
        self.assertEqual(
1741
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1742
1743
    def test_http_send_smart_request(self):
1744
1745
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1746
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1747
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1748
        http_transport = transport.get_transport(self.http_server.get_url())
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1749
        medium = http_transport.get_smart_medium()
1750
        response = medium.send_http_smart_request(post_body)
1751
        reply_body = response.read()
1752
        self.assertEqual(expected_reply_body, reply_body)
1753
1754
    def test_smart_http_server_post_request_handler(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1755
        httpd = self.http_server.server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1756
1757
        socket = SampleSocket(
1758
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1759
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1760
            # for 1.0)
1761
            + 'Content-Length: 6\r\n'
1762
            '\r\n'
1763
            'hello\n')
1764
        # Beware: the ('localhost', 80) below is the
1765
        # client_address parameter, but we don't have one because
1766
        # we have defined a socket which is not bound to an
1767
        # address. The test framework never uses this client
1768
        # address, so far...
1769
        request_handler = http_utils.SmartRequestHandler(socket,
1770
                                                         ('localhost', 80),
1771
                                                         httpd)
1772
        response = socket.writefile.getvalue()
1773
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1774
        # This includes the end of the HTTP headers, and all the body.
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1775
        expected_end_of_response = '\r\n\r\nok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1776
        self.assertEndsWith(response, expected_end_of_response)
1777
1778
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1779
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1780
    """No smart server here request handler."""
1781
1782
    def do_POST(self):
1783
        self.send_error(403, "Forbidden")
1784
1785
1786
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1787
    """Test smart client behaviour against an http server without smarts."""
1788
1789
    _req_handler_class = ForbiddenRequestHandler
1790
1791
    def test_probe_smart_server(self):
1792
        """Test error handling against server refusing smart requests."""
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1793
        t = self.get_readonly_transport()
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1794
        # No need to build a valid smart request here, the server will not even
1795
        # try to interpret it.
1796
        self.assertRaises(errors.SmartProtocolError,
3734.3.1 by Vincent Ladeuil
Fix SmartHTTPMedium refactoring related test.
1797
                          t.get_smart_medium().send_http_smart_request,
1798
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1799
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
1800
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1801
class Test_redirected_to(tests.TestCase):
1802
1803
    def test_redirected_to_subdir(self):
1804
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1805
        r = t._redirected_to('http://www.example.com/foo',
1806
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1807
        self.assertIsInstance(r, type(t))
1808
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1809
        self.assertEqual(t._get_connection(), r._get_connection())
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1810
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1811
    def test_redirected_to_self_with_slash(self):
1812
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1813
        r = t._redirected_to('http://www.example.com/foo',
1814
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1815
        self.assertIsInstance(r, type(t))
1816
        # Both transports share the some connection (one can argue that we
1817
        # should return the exact same transport here, but that seems
1818
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1819
        self.assertEqual(t._get_connection(), r._get_connection())
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1820
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1821
    def test_redirected_to_host(self):
1822
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1823
        r = t._redirected_to('http://www.example.com/foo',
1824
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1825
        self.assertIsInstance(r, type(t))
1826
1827
    def test_redirected_to_same_host_sibling_protocol(self):
1828
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1829
        r = t._redirected_to('http://www.example.com/foo',
1830
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1831
        self.assertIsInstance(r, type(t))
1832
1833
    def test_redirected_to_same_host_different_protocol(self):
1834
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1835
        r = t._redirected_to('http://www.example.com/foo',
1836
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1837
        self.assertNotEquals(type(r), type(t))
1838
1839
    def test_redirected_to_different_host_same_user(self):
1840
        t = self._transport('http://joe@www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1841
        r = t._redirected_to('http://www.example.com/foo',
1842
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1843
        self.assertIsInstance(r, type(t))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1844
        self.assertEqual(t._user, r._user)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1845
1846
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1847
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1848
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1849
1850
    The only thing we care about here is how many bytes travel on the wire. But
1851
    since we want to measure it for a real http client, we have to send it
1852
    correct responses.
1853
1854
    We expect to receive a *single* request nothing more (and we won't even
1855
    check what request it is, we just measure the bytes read until an empty
1856
    line.
1857
    """
1858
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
1859
    def _handle_one_request(self):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1860
        tcs = self.server.test_case_server
1861
        requestline = self.rfile.readline()
1862
        headers = self.MessageClass(self.rfile, 0)
1863
        # We just read: the request, the headers, an empty line indicating the
1864
        # end of the headers.
1865
        bytes_read = len(requestline)
1866
        for line in headers.headers:
1867
            bytes_read += len(line)
1868
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1869
        if requestline.startswith('POST'):
1870
            # The body should be a single line (or we don't know where it ends
1871
            # and we don't want to issue a blocking read)
1872
            body = self.rfile.readline()
1873
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1874
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1875
1876
        # We set the bytes written *before* issuing the write, the client is
1877
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
1878
1879
        # Doing the oppposite may lead to test failure: we may be interrupted
1880
        # after the write but before updating the value. The client can then
1881
        # continue and read the value *before* we can update it. And yes,
1882
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1883
        tcs.bytes_written = len(tcs.canned_response)
1884
        self.wfile.write(tcs.canned_response)
1885
1886
1887
class ActivityServerMixin(object):
1888
1889
    def __init__(self, protocol_version):
1890
        super(ActivityServerMixin, self).__init__(
1891
            request_handler=PredefinedRequestHandler,
1892
            protocol_version=protocol_version)
1893
        # Bytes read and written by the server
1894
        self.bytes_read = 0
1895
        self.bytes_written = 0
1896
        self.canned_response = None
1897
1898
1899
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1900
    pass
1901
1902
1903
if tests.HTTPSServerFeature.available():
1904
    from bzrlib.tests import https_server
1905
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1906
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1907
1908
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
1909
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1910
    """Test socket activity reporting.
1911
1912
    We use a special purpose server to control the bytes sent and received and
1913
    be able to predict the activity on the client socket.
1914
    """
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1915
    def get_transport(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1916
        t = self._transport(self.server.get_url())
1917
        # FIXME: Needs cleanup -- vila 20100611
1918
        return t
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1919
1920
    def assertActivitiesMatch(self):
1921
        self.assertEqual(self.server.bytes_read,
1922
                         self.activities.get('write', 0), 'written bytes')
1923
        self.assertEqual(self.server.bytes_written,
1924
                         self.activities.get('read', 0), 'read bytes')
1925
1926
    def test_get(self):
1927
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1928
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1929
Server: Apache/2.0.54 (Fedora)\r
1930
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1931
ETag: "56691-23-38e9ae00"\r
1932
Accept-Ranges: bytes\r
1933
Content-Length: 35\r
1934
Connection: close\r
1935
Content-Type: text/plain; charset=UTF-8\r
1936
\r
1937
Bazaar-NG meta directory, format 1
1938
'''
1939
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1940
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
1941
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1942
        self.assertActivitiesMatch()
1943
1944
    def test_has(self):
1945
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1946
Server: SimpleHTTP/0.6 Python/2.5.2\r
1947
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
1948
Content-type: application/octet-stream\r
1949
Content-Length: 20\r
1950
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
1951
\r
1952
'''
1953
        t = self.get_transport()
1954
        self.assertTrue(t.has('foo/bar'))
1955
        self.assertActivitiesMatch()
1956
1957
    def test_readv(self):
1958
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
1959
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
1960
Server: Apache/2.0.54 (Fedora)\r
1961
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
1962
ETag: "238a3c-16ec2-805c5540"\r
1963
Accept-Ranges: bytes\r
1964
Content-Length: 1534\r
1965
Connection: close\r
1966
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
1967
\r
1968
\r
1969
--418470f848b63279b\r
1970
Content-type: text/plain; charset=UTF-8\r
1971
Content-range: bytes 0-254/93890\r
1972
\r
1973
mbp@sourcefrog.net-20050309040815-13242001617e4a06
1974
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
1975
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
1976
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
1977
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
1978
\r
1979
--418470f848b63279b\r
1980
Content-type: text/plain; charset=UTF-8\r
1981
Content-range: bytes 1000-2049/93890\r
1982
\r
1983
40-fd4ec249b6b139ab
1984
mbp@sourcefrog.net-20050311063625-07858525021f270b
1985
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
1986
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
1987
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
1988
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
1989
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
1990
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
1991
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
1992
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
1993
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
1994
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
1995
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
1996
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
1997
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
1998
mbp@sourcefrog.net-20050313120651-497bd231b19df600
1999
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2000
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2001
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2002
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2003
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2004
mbp@source\r
2005
--418470f848b63279b--\r
2006
'''
2007
        t = self.get_transport()
2008
        # Remember that the request is ignored and that the ranges below
2009
        # doesn't have to match the canned response.
2010
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2011
        self.assertEqual(2, len(l))
2012
        self.assertActivitiesMatch()
2013
2014
    def test_post(self):
2015
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2016
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2017
Server: Apache/2.0.54 (Fedora)\r
2018
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2019
ETag: "56691-23-38e9ae00"\r
2020
Accept-Ranges: bytes\r
2021
Content-Length: 35\r
2022
Connection: close\r
2023
Content-Type: text/plain; charset=UTF-8\r
2024
\r
2025
lalala whatever as long as itsssss
2026
'''
2027
        t = self.get_transport()
2028
        # We must send a single line of body bytes, see
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
2029
        # PredefinedRequestHandler._handle_one_request
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2030
        code, f = t._post('abc def end-of-body\n')
2031
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2032
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2033
2034
2035
class TestActivity(tests.TestCase, TestActivityMixin):
2036
2037
    def setUp(self):
2038
        tests.TestCase.setUp(self)
2039
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2040
        self.server.start_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2041
        self.addCleanup(self.server.stop_server)
2042
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2043
        self.activities = {}
2044
        def report_activity(t, bytes, direction):
2045
            count = self.activities.get(direction, 0)
2046
            count += bytes
2047
            self.activities[direction] = count
2048
        # We override at class level because constructors may propagate the
2049
        # bound method and render instance overriding ineffective (an
2050
        # alternative would be to define a specific ui factory instead...)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2051
        self.overrideAttr(self._transport, '_report_activity', report_activity)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2052
2053
2054
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2055
2056
    def setUp(self):
2057
        tests.TestCase.setUp(self)
2058
        # Unlike TestActivity, we are really testing ReportingFileSocket and
2059
        # ReportingSocket, so we don't need all the parametrization. Since
2060
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2061
        # test them through their use by the transport than directly (that's a
2062
        # bit less clean but far more simpler and effective).
2063
        self.server = ActivityHTTPServer('HTTP/1.1')
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2064
        self._transport = _urllib.HttpTransport_urllib
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2065
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2066
        self.server.start_server()
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2067
        self.addCleanup(self.server.stop_server)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2068
2069
        # We override at class level because constructors may propagate the
2070
        # bound method and render instance overriding ineffective (an
2071
        # alternative would be to define a specific ui factory instead...)
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2072
        self.overrideAttr(self._transport, '_report_activity', None)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2073
2074
    def assertActivitiesMatch(self):
2075
        # Nothing to check here
2076
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2077
2078
2079
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2080
    """Test authentication on the redirected http server."""
2081
2082
    _auth_header = 'Authorization'
2083
    _password_prompt_prefix = ''
2084
    _username_prompt_prefix = ''
2085
    _auth_server = http_utils.HTTPBasicAuthServer
2086
    _transport = _urllib.HttpTransport_urllib
2087
2088
    def setUp(self):
2089
        super(TestAuthOnRedirected, self).setUp()
2090
        self.build_tree_contents([('a','a'),
2091
                                  ('1/',),
2092
                                  ('1/a', 'redirected once'),
2093
                                  ],)
2094
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2095
                                       self.new_server.port)
2096
        self.old_server.redirections = [
2097
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2098
        self.old_transport = self.get_old_transport()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2099
        self.new_server.add_user('joe', 'foo')
2100
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2101
    def create_transport_readonly_server(self):
2102
        server = self._auth_server(protocol_version=self._protocol_version)
2103
        server._url_protocol = self._url_protocol
2104
        return server
2105
2106
    def get_a(self, t):
2107
        return t.get('a')
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2108
2109
    def test_auth_on_redirected_via_do_catching_redirections(self):
2110
        self.redirections = 0
2111
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2112
        def redirected(t, exception, redirection_notice):
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2113
            self.redirections += 1
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2114
            redirected_t = t._redirected_to(exception.source, exception.target)
2115
            return redirected_t
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2116
2117
        stdout = tests.StringIOWrapper()
2118
        stderr = tests.StringIOWrapper()
2119
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2120
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2121
        self.assertEqual('redirected once',
2122
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2123
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2124
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2125
        # stdin should be empty
2126
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2127
        # stdout should be empty, stderr will contains the prompts
2128
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2129
2130
    def test_auth_on_redirected_via_following_redirections(self):
2131
        self.new_server.add_user('joe', 'foo')
2132
        stdout = tests.StringIOWrapper()
2133
        stderr = tests.StringIOWrapper()
2134
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2135
                                            stdout=stdout, stderr=stderr)
2136
        t = self.old_transport
2137
        req = RedirectedRequest('GET', t.abspath('a'))
2138
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2139
                                       self.new_server.port)
2140
        self.old_server.redirections = [
2141
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2142
        self.assertEqual('redirected once',t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2143
        # stdin should be empty
2144
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2145
        # stdout should be empty, stderr will contains the prompts
2146
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2147
2148