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