/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
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
964
        # Final boundary
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
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
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
999
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1000
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1001
    """Errors out when range specifiers exceed the limit"""
1002
1003
    def get_multiple_ranges(self, file, file_size, ranges):
1004
        """Refuses the multiple ranges request"""
1005
        tcs = self.server.test_case_server
1006
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1007
            file.close()
1008
            # Emulate apache behavior
1009
            self.send_error(400, "Bad Request")
1010
            return
1011
        return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1012
            self, file, file_size, ranges)
1013
1014
1015
class LimitedRangeHTTPServer(http_server.HttpServer):
1016
    """An HttpServer erroring out on requests with too much range specifiers"""
1017
1018
    def __init__(self, request_handler=LimitedRangeRequestHandler,
1019
                 protocol_version=None,
1020
                 range_limit=None):
1021
        http_server.HttpServer.__init__(self, request_handler,
1022
                                        protocol_version=protocol_version)
1023
        self.range_limit = range_limit
1024
1025
1026
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1027
    """Tests readv requests against a server erroring out on too much ranges."""
1028
5462.3.15 by Martin Pool
Turn variations into scenario lists
1029
    scenarios = multiply_scenarios(
1030
        vary_by_http_client_implementation(), 
1031
        vary_by_http_protocol_version(),
1032
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1033
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1034
    # Requests with more range specifiers will error out
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1035
    range_limit = 3
1036
1037
    def create_transport_readonly_server(self):
1038
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1039
                                      protocol_version=self._protocol_version)
1040
1041
    def setUp(self):
1042
        http_utils.TestCaseWithWebserver.setUp(self)
1043
        # We need to manipulate ranges that correspond to real chunks in the
1044
        # response, so we build a content appropriately.
1045
        filler = ''.join(['abcdefghij' for x in range(102)])
1046
        content = ''.join(['%04d' % v + filler for v in range(16)])
1047
        self.build_tree_contents([('a', content)],)
1048
1049
    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.
1050
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1051
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1052
        self.assertEqual(l[0], (0, '0000'))
1053
        self.assertEqual(l[1], (1024, '0001'))
1054
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1055
1056
    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.
1057
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1058
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1059
        self.assertEqual(l[0], (0, '0000'))
1060
        self.assertEqual(l[1], (1024, '0001'))
1061
        self.assertEqual(l[2], (4096, '0004'))
1062
        self.assertEqual(l[3], (8192, '0008'))
1063
        # The server will refuse to serve the first request (too much ranges),
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1064
        # a second request will succeed.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1065
        self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1066
1067
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1068
class TestHttpProxyWhiteBox(tests.TestCase):
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1069
    """Whitebox test proxy http authorization.
1070
2420.1.3 by Vincent Ladeuil
Implement http proxy basic authentication.
1071
    Only the urllib implementation is tested here.
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1072
    """
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1073
1074
    def setUp(self):
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1075
        tests.TestCase.setUp(self)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1076
        self._old_env = {}
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
1077
        self.addCleanup(self._restore_env)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1078
1079
    def _install_env(self, env):
1080
        for name, value in env.iteritems():
2420.1.2 by Vincent Ladeuil
Define tests for http proxy basic authentication. They fail.
1081
            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.
1082
1083
    def _restore_env(self):
1084
        for name, value in self._old_env.iteritems():
1085
            osutils.set_or_unset_env(name, value)
1086
1087
    def _proxied_request(self):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1088
        handler = _urllib2_wrappers.ProxyHandler()
1089
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1090
        handler.set_proxy(request, 'http')
1091
        return request
1092
1093
    def test_empty_user(self):
1094
        self._install_env({'http_proxy': 'http://bar.com'})
1095
        request = self._proxied_request()
1096
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1097
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1098
    def test_invalid_proxy(self):
1099
        """A proxy env variable without scheme"""
1100
        self._install_env({'http_proxy': 'host:1234'})
1101
        self.assertRaises(errors.InvalidURL, self._proxied_request)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1102
1103
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1104
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1105
    """Tests proxy server.
1106
1107
    Be aware that we do not setup a real proxy here. Instead, we
1108
    check that the *connection* goes through the proxy by serving
1109
    different content (the faked proxy server append '-proxied'
1110
    to the file names).
1111
    """
1112
5462.3.15 by Martin Pool
Turn variations into scenario lists
1113
    scenarios = multiply_scenarios(
1114
        vary_by_http_client_implementation(), 
1115
        vary_by_http_protocol_version(),
1116
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1117
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1118
    # 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.
1119
    # test https connections. --vila toolongago
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1120
1121
    def setUp(self):
1122
        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.
1123
        self.transport_secondary_server = http_utils.ProxyServer
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1124
        self.build_tree_contents([('foo', 'contents of foo\n'),
1125
                                  ('foo-proxied', 'proxied contents of foo\n')])
1126
        # 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.
1127
        server = self.get_readonly_server()
1128
        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.
1129
        if self._testing_pycurl():
1130
            # Oh my ! pycurl does not check for the port as part of
1131
            # 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.
1132
            self.no_proxy_host = server.host
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1133
        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.
1134
            self.no_proxy_host = self.server_host_port
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1135
        # 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.
1136
        self.proxy_url = self.get_secondary_url()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1137
        self._old_env = {}
1138
1139
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1140
        # TODO: This is duplicated for lots of the classes in this file
1141
        return (features.pycurl.available()
1142
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1143
1144
    def _install_env(self, env):
1145
        for name, value in env.iteritems():
1146
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1147
1148
    def _restore_env(self):
1149
        for name, value in self._old_env.iteritems():
1150
            osutils.set_or_unset_env(name, value)
1151
1152
    def proxied_in_env(self, env):
1153
        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.
1154
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1155
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1156
            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.
1157
        finally:
1158
            self._restore_env()
1159
1160
    def not_proxied_in_env(self, env):
1161
        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.
1162
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1163
        try:
3734.2.8 by Vincent Ladeuil
Catch spurious exceptions (python-2.6) when SocketServer is shut down.
1164
            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.
1165
        finally:
1166
            self._restore_env()
1167
1168
    def test_http_proxy(self):
1169
        self.proxied_in_env({'http_proxy': self.proxy_url})
1170
1171
    def test_HTTP_PROXY(self):
1172
        if self._testing_pycurl():
1173
            # pycurl does not check HTTP_PROXY for security reasons
1174
            # (for use in a CGI context that we do not care
1175
            # about. Should we ?)
1176
            raise tests.TestNotApplicable(
1177
                'pycurl does not check HTTP_PROXY for security reasons')
1178
        self.proxied_in_env({'HTTP_PROXY': self.proxy_url})
1179
1180
    def test_all_proxy(self):
1181
        self.proxied_in_env({'all_proxy': self.proxy_url})
1182
1183
    def test_ALL_PROXY(self):
1184
        self.proxied_in_env({'ALL_PROXY': self.proxy_url})
1185
1186
    def test_http_proxy_with_no_proxy(self):
1187
        self.not_proxied_in_env({'http_proxy': self.proxy_url,
1188
                                 'no_proxy': self.no_proxy_host})
1189
1190
    def test_HTTP_PROXY_with_NO_PROXY(self):
1191
        if self._testing_pycurl():
1192
            raise tests.TestNotApplicable(
1193
                'pycurl does not check HTTP_PROXY for security reasons')
1194
        self.not_proxied_in_env({'HTTP_PROXY': self.proxy_url,
1195
                                 'NO_PROXY': self.no_proxy_host})
1196
1197
    def test_all_proxy_with_no_proxy(self):
1198
        self.not_proxied_in_env({'all_proxy': self.proxy_url,
1199
                                 'no_proxy': self.no_proxy_host})
1200
1201
    def test_ALL_PROXY_with_NO_PROXY(self):
1202
        self.not_proxied_in_env({'ALL_PROXY': self.proxy_url,
1203
                                 'NO_PROXY': self.no_proxy_host})
1204
1205
    def test_http_proxy_without_scheme(self):
1206
        if self._testing_pycurl():
1207
            # pycurl *ignores* invalid proxy env variables. If that ever change
1208
            # in the future, this test will fail indicating that pycurl do not
1209
            # 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.
1210
            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.
1211
        else:
1212
            self.assertRaises(errors.InvalidURL,
1213
                              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.
1214
                              {'http_proxy': self.server_host_port})
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1215
1216
1217
class TestRanges(http_utils.TestCaseWithWebserver):
1218
    """Test the Range header in GET methods."""
1219
5462.3.15 by Martin Pool
Turn variations into scenario lists
1220
    scenarios = multiply_scenarios(
1221
        vary_by_http_client_implementation(), 
1222
        vary_by_http_protocol_version(),
1223
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1224
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1225
    def setUp(self):
1226
        http_utils.TestCaseWithWebserver.setUp(self)
1227
        self.build_tree_contents([('a', '0123456789')],)
1228
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1229
    def create_transport_readonly_server(self):
1230
        return http_server.HttpServer(protocol_version=self._protocol_version)
1231
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1232
    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.
1233
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1234
        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.
1235
        coalesce = t._coalesce_offsets
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1236
        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.
1237
        code, data = t._get(relpath, coalesced)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1238
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1239
        for start, end in ranges:
1240
            data.seek(start)
1241
            yield data.read(end - start + 1)
1242
1243
    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.
1244
        t = self.get_readonly_transport()
1245
        code, data = t._get(relpath, [], tail_amount)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1246
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1247
        data.seek(-tail_amount, 2)
1248
        return data.read(tail_amount)
1249
1250
    def test_range_header(self):
1251
        # Valid ranges
1252
        map(self.assertEqual,['0', '234'],
1253
            list(self._file_contents('a', [(0,0), (2,4)])),)
1254
1255
    def test_range_header_tail(self):
1256
        self.assertEqual('789', self._file_tail('a', 3))
1257
1258
    def test_syntactically_invalid_range_header(self):
1259
        self.assertListRaises(errors.InvalidHttpRange,
1260
                          self._file_contents, 'a', [(4, 3)])
1261
1262
    def test_semantically_invalid_range_header(self):
1263
        self.assertListRaises(errors.InvalidHttpRange,
1264
                          self._file_contents, 'a', [(42, 128)])
1265
1266
1267
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1268
    """Test redirection between http servers."""
1269
5462.3.15 by Martin Pool
Turn variations into scenario lists
1270
    scenarios = multiply_scenarios(
1271
        vary_by_http_client_implementation(), 
1272
        vary_by_http_protocol_version(),
1273
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1274
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1275
    def setUp(self):
1276
        super(TestHTTPRedirections, self).setUp()
1277
        self.build_tree_contents([('a', '0123456789'),
1278
                                  ('bundle',
1279
                                  '# Bazaar revision bundle v0.9\n#\n')
1280
                                  ],)
1281
1282
    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.
1283
        self.assertRaises(errors.RedirectRequested,
1284
                          self.get_old_transport().get, 'a')
1285
        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.
1286
1287
1288
class RedirectedRequest(_urllib2_wrappers.Request):
1289
    """Request following redirections. """
1290
1291
    init_orig = _urllib2_wrappers.Request.__init__
1292
1293
    def __init__(self, method, url, *args, **kwargs):
1294
        """Constructor.
1295
1296
        """
1297
        # Since the tests using this class will replace
1298
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1299
        # or we'll loop.
4208.3.2 by Andrew Bennetts
Fix one test failure in test_http under Python 2.7a0.
1300
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1301
        self.follow_redirections = True
1302
1303
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1304
def install_redirected_request(test):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1305
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1306
1307
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1308
def cleanup_http_redirection_connections(test):
1309
    # Some sockets are opened but never seen by _urllib, so we trap them at
1310
    # the _urllib2_wrappers level to be able to clean them up.
1311
    def socket_disconnect(sock):
1312
        try:
1313
            sock.shutdown(socket.SHUT_RDWR)
1314
            sock.close()
1315
        except socket.error:
1316
            pass
1317
    def connect(connection):
1318
        test.http_connect_orig(connection)
1319
        test.addCleanup(socket_disconnect, connection.sock)
1320
    test.http_connect_orig = test.overrideAttr(
1321
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1322
    def connect(connection):
1323
        test.https_connect_orig(connection)
1324
        test.addCleanup(socket_disconnect, connection.sock)
1325
    test.https_connect_orig = test.overrideAttr(
1326
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1327
1328
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1329
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1330
    """Test redirections.
1331
1332
    http implementations do not redirect silently anymore (they
1333
    do not redirect at all in fact). The mechanism is still in
1334
    place at the _urllib2_wrappers.Request level and these tests
1335
    exercise it.
1336
1337
    For the pycurl implementation
1338
    the redirection have been deleted as we may deprecate pycurl
1339
    and I have no place to keep a working implementation.
1340
    -- vila 20070212
1341
    """
1342
5462.3.15 by Martin Pool
Turn variations into scenario lists
1343
    scenarios = multiply_scenarios(
1344
        vary_by_http_client_implementation(), 
1345
        vary_by_http_protocol_version(),
1346
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1347
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1348
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1349
        if (features.pycurl.available()
1350
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1351
            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.
1352
                "pycurl doesn't redirect silently anymore")
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1353
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1354
        install_redirected_request(self)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1355
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1356
        self.build_tree_contents([('a','a'),
1357
                                  ('1/',),
1358
                                  ('1/a', 'redirected once'),
1359
                                  ('2/',),
1360
                                  ('2/a', 'redirected twice'),
1361
                                  ('3/',),
1362
                                  ('3/a', 'redirected thrice'),
1363
                                  ('4/',),
1364
                                  ('4/a', 'redirected 4 times'),
1365
                                  ('5/',),
1366
                                  ('5/a', 'redirected 5 times'),
1367
                                  ],)
1368
1369
    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.
1370
        t = self.get_old_transport()
1371
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1372
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1373
                                       self.new_server.port)
1374
        self.old_server.redirections = \
1375
            [('(.*)', 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.
1376
        self.assertEqual('redirected once', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1377
1378
    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.
1379
        t = self.get_old_transport()
1380
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1381
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1382
                                       self.old_server.port)
1383
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1384
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1385
        self.old_server.redirections = [
1386
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1387
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1388
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1389
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1390
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1391
            ]
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.
1392
        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.
1393
1394
1395
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1396
    """Test transport.do_catching_redirections."""
1397
5462.3.15 by Martin Pool
Turn variations into scenario lists
1398
    scenarios = multiply_scenarios(
1399
        vary_by_http_client_implementation(), 
1400
        vary_by_http_protocol_version(),
1401
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1402
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1403
    def setUp(self):
1404
        super(TestDoCatchRedirections, self).setUp()
1405
        self.build_tree_contents([('a', '0123456789'),],)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1406
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1407
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.
1408
        self.old_transport = self.get_old_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1409
5247.3.31 by Vincent Ladeuil
Cleanup some imports in http_utils.py.
1410
    def get_a(self, t):
1411
        return t.get('a')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1412
1413
    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.
1414
        t = self.get_new_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1415
1416
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1417
        self.assertEqual('0123456789',
1418
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1419
                self.get_a, t, None).read())
1420
1421
    def test_one_redirection(self):
1422
        self.redirections = 0
1423
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.
1424
        def redirected(t, exception, redirection_notice):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1425
            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.
1426
            redirected_t = t._redirected_to(exception.source, exception.target)
1427
            return redirected_t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1428
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1429
        self.assertEqual('0123456789',
1430
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1431
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1432
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1433
1434
    def test_redirection_loop(self):
1435
1436
        def redirected(transport, exception, redirection_notice):
1437
            # By using the redirected url as a base dir for the
1438
            # *old* transport, we create a loop: a => a/a =>
1439
            # a/a/a
1440
            return self.old_transport.clone(exception.target)
1441
1442
        self.assertRaises(errors.TooManyRedirections,
1443
                          transport.do_catching_redirections,
1444
                          self.get_a, self.old_transport, redirected)
1445
1446
1447
class TestAuth(http_utils.TestCaseWithWebserver):
1448
    """Test authentication scheme"""
1449
5462.3.15 by Martin Pool
Turn variations into scenario lists
1450
    scenarios = multiply_scenarios(
1451
        vary_by_http_client_implementation(),
1452
        vary_by_http_protocol_version(),
1453
        vary_by_http_auth_scheme(),
1454
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1455
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1456
    _auth_header = 'Authorization'
1457
    _password_prompt_prefix = ''
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1458
    _username_prompt_prefix = ''
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1459
    # Set by load_tests
1460
    _auth_server = None
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1461
1462
    def setUp(self):
1463
        super(TestAuth, self).setUp()
1464
        self.server = self.get_readonly_server()
1465
        self.build_tree_contents([('a', 'contents of a\n'),
1466
                                  ('b', 'contents of b\n'),])
1467
1468
    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.
1469
        server = self._auth_server(protocol_version=self._protocol_version)
1470
        server._url_protocol = self._url_protocol
1471
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1472
1473
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1474
        # TODO: This is duplicated for lots of the classes in this file
1475
        return (features.pycurl.available()
1476
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1477
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1478
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1479
        """Build an url embedding user and password"""
1480
        url = '%s://' % self.server._url_protocol
1481
        if user is not None:
1482
            url += user
1483
            if password is not None:
1484
                url += ':' + password
1485
            url += '@'
1486
        url += '%s:%s/' % (self.server.host, self.server.port)
1487
        return url
1488
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1489
    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.
1490
        t = transport.get_transport(self.get_user_url(user, password))
1491
        return t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1492
1493
    def test_no_user(self):
1494
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1495
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1496
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1497
        # Only one 'Authentication Required' error should occur
1498
        self.assertEqual(1, self.server.auth_required_errors)
1499
1500
    def test_empty_pass(self):
1501
        self.server.add_user('joe', '')
1502
        t = self.get_user_transport('joe', '')
1503
        self.assertEqual('contents of a\n', t.get('a').read())
1504
        # Only one 'Authentication Required' error should occur
1505
        self.assertEqual(1, self.server.auth_required_errors)
1506
1507
    def test_user_pass(self):
1508
        self.server.add_user('joe', 'foo')
1509
        t = self.get_user_transport('joe', 'foo')
1510
        self.assertEqual('contents of a\n', t.get('a').read())
1511
        # Only one 'Authentication Required' error should occur
1512
        self.assertEqual(1, self.server.auth_required_errors)
1513
1514
    def test_unknown_user(self):
1515
        self.server.add_user('joe', 'foo')
1516
        t = self.get_user_transport('bill', 'foo')
1517
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1518
        # Two 'Authentication Required' errors should occur (the
1519
        # initial 'who are you' and 'I don't know you, who are
1520
        # you').
1521
        self.assertEqual(2, self.server.auth_required_errors)
1522
1523
    def test_wrong_pass(self):
1524
        self.server.add_user('joe', 'foo')
1525
        t = self.get_user_transport('joe', 'bar')
1526
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1527
        # Two 'Authentication Required' errors should occur (the
1528
        # initial 'who are you' and 'this is not you, who are you')
1529
        self.assertEqual(2, self.server.auth_required_errors)
1530
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1531
    def test_prompt_for_username(self):
1532
        if self._testing_pycurl():
1533
            raise tests.TestNotApplicable(
1534
                'pycurl cannot prompt, it handles auth by embedding'
1535
                ' user:pass in urls only')
1536
1537
        self.server.add_user('joe', 'foo')
1538
        t = self.get_user_transport(None, None)
1539
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1540
        stderr = tests.StringIOWrapper()
1541
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1542
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1543
        self.assertEqual('contents of a\n',t.get('a').read())
1544
        # stdin should be empty
1545
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1546
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1547
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1548
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1549
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1550
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1551
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1552
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1553
    def test_prompt_for_password(self):
1554
        if self._testing_pycurl():
1555
            raise tests.TestNotApplicable(
1556
                'pycurl cannot prompt, it handles auth by embedding'
1557
                ' user:pass in urls only')
1558
1559
        self.server.add_user('joe', 'foo')
1560
        t = self.get_user_transport('joe', None)
1561
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1562
        stderr = tests.StringIOWrapper()
1563
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1564
                                            stdout=stdout, stderr=stderr)
1565
        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.
1566
        # stdin should be empty
1567
        self.assertEqual('', ui.ui_factory.stdin.readline())
1568
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1569
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1570
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1571
        # And we shouldn't prompt again for a different request
1572
        # against the same transport.
1573
        self.assertEqual('contents of b\n',t.get('b').read())
1574
        t2 = t.clone()
1575
        # And neither against a clone
1576
        self.assertEqual('contents of b\n',t2.get('b').read())
1577
        # Only one 'Authentication Required' error should occur
1578
        self.assertEqual(1, self.server.auth_required_errors)
1579
1580
    def _check_password_prompt(self, scheme, user, actual_prompt):
1581
        expected_prompt = (self._password_prompt_prefix
1582
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1583
                              % (scheme.upper(),
1584
                                 user, self.server.host, self.server.port,
1585
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1586
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1587
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1588
    def _expected_username_prompt(self, scheme):
1589
        return (self._username_prompt_prefix
1590
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1591
                                 self.server.host, self.server.port,
1592
                                 self.server.auth_realm))
1593
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1594
    def test_no_prompt_for_password_when_using_auth_config(self):
1595
        if self._testing_pycurl():
1596
            raise tests.TestNotApplicable(
1597
                'pycurl does not support authentication.conf'
1598
                ' since it cannot prompt')
1599
1600
        user =' joe'
1601
        password = 'foo'
1602
        stdin_content = 'bar\n'  # Not the right password
1603
        self.server.add_user(user, password)
1604
        t = self.get_user_transport(user, None)
1605
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1606
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1607
        # Create a minimal config file with the right password
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1608
        _setup_authentication_config(
1609
            scheme='http', 
1610
            port=self.server.port,
1611
            user=user,
1612
            password=password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1613
        # Issue a request to the server to connect
1614
        self.assertEqual('contents of a\n',t.get('a').read())
1615
        # stdin should have  been left untouched
1616
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1617
        # Only one 'Authentication Required' error should occur
1618
        self.assertEqual(1, self.server.auth_required_errors)
1619
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1620
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1621
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1622
                                     http_utils.ProxyDigestAuthServer):
1623
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1624
        if self._testing_pycurl():
1625
            raise tests.KnownFailure(
1626
                'pycurl does not handle a nonce change')
1627
        self.server.add_user('joe', 'foo')
1628
        t = self.get_user_transport('joe', 'foo')
1629
        self.assertEqual('contents of a\n', t.get('a').read())
1630
        self.assertEqual('contents of b\n', t.get('b').read())
1631
        # Only one 'Authentication Required' error should have
1632
        # occured so far
1633
        self.assertEqual(1, self.server.auth_required_errors)
1634
        # The server invalidates the current nonce
1635
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1636
        self.assertEqual('contents of a\n', t.get('a').read())
1637
        # Two 'Authentication Required' errors should occur (the
1638
        # initial 'who are you' and a second 'who are you' with the new nonce)
1639
        self.assertEqual(2, self.server.auth_required_errors)
1640
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1641
    def test_user_from_auth_conf(self):
1642
        if self._testing_pycurl():
1643
            raise tests.TestNotApplicable(
1644
                'pycurl does not support authentication.conf')
1645
        user = 'joe'
1646
        password = 'foo'
1647
        self.server.add_user(user, password)
1648
        _setup_authentication_config(
1649
            scheme='http', 
1650
            port=self.server.port,
1651
            user=user,
1652
            password=password)
1653
        t = self.get_user_transport(None, None)
1654
        # Issue a request to the server to connect
1655
        self.assertEqual('contents of a\n', t.get('a').read())
1656
        # Only one 'Authentication Required' error should occur
1657
        self.assertEqual(1, self.server.auth_required_errors)
1658
1659
1660
def _setup_authentication_config(**kwargs):
1661
    conf = config.AuthenticationConfig()
1662
    conf._get_config().update({'httptest': kwargs})
1663
    conf._save()
1664
1665
1666
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1667
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1668
    """Unit tests for glue by which urllib2 asks us for authentication"""
1669
1670
    def test_get_user_password_without_port(self):
1671
        """We cope if urllib2 doesn't tell us the port.
1672
1673
        See https://bugs.launchpad.net/bzr/+bug/654684
1674
        """
1675
        user = 'joe'
1676
        password = 'foo'
1677
        _setup_authentication_config(
1678
            scheme='http', 
1679
            host='localhost',
1680
            user=user,
1681
            password=password)
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1682
        handler = _urllib2_wrappers.HTTPAuthHandler()
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1683
        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
1684
            user='joe',
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1685
            protocol='http',
1686
            host='localhost',
1687
            path='/',
1688
            realm='Realm',
1689
            ))
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1690
        self.assertEquals((user, password), got_pass)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1691
1692
1693
class TestProxyAuth(TestAuth):
1694
    """Test proxy authentication schemes."""
1695
5462.3.15 by Martin Pool
Turn variations into scenario lists
1696
    scenarios = multiply_scenarios(
1697
        vary_by_http_client_implementation(),
1698
        vary_by_http_protocol_version(),
1699
        vary_by_http_proxy_auth_scheme(),
1700
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1701
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1702
    _auth_header = 'Proxy-authorization'
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1703
    _password_prompt_prefix = 'Proxy '
1704
    _username_prompt_prefix = 'Proxy '
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1705
1706
    def setUp(self):
1707
        super(TestProxyAuth, self).setUp()
1708
        self._old_env = {}
1709
        self.addCleanup(self._restore_env)
1710
        # Override the contents to avoid false positives
1711
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1712
                                  ('b', 'not proxied contents of b\n'),
1713
                                  ('a-proxied', 'contents of a\n'),
1714
                                  ('b-proxied', 'contents of b\n'),
1715
                                  ])
1716
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1717
    def get_user_transport(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1718
        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.
1719
        return TestAuth.get_user_transport(self, user, password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1720
1721
    def _install_env(self, env):
1722
        for name, value in env.iteritems():
1723
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1724
1725
    def _restore_env(self):
1726
        for name, value in self._old_env.iteritems():
1727
            osutils.set_or_unset_env(name, value)
1728
1729
    def test_empty_pass(self):
1730
        if self._testing_pycurl():
1731
            import pycurl
1732
            if pycurl.version_info()[1] < '7.16.0':
1733
                raise tests.KnownFailure(
1734
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1735
        super(TestProxyAuth, self).test_empty_pass()
1736
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1737
1738
class SampleSocket(object):
1739
    """A socket-like object for use in testing the HTTP request handler."""
1740
1741
    def __init__(self, socket_read_content):
1742
        """Constructs a sample socket.
1743
1744
        :param socket_read_content: a byte sequence
1745
        """
1746
        # Use plain python StringIO so we can monkey-patch the close method to
1747
        # not discard the contents.
1748
        from StringIO import StringIO
1749
        self.readfile = StringIO(socket_read_content)
1750
        self.writefile = StringIO()
1751
        self.writefile.close = lambda: None
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
1752
        self.close = lambda: None
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1753
1754
    def makefile(self, mode='r', bufsize=None):
1755
        if 'r' in mode:
1756
            return self.readfile
1757
        else:
1758
            return self.writefile
1759
1760
1761
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1762
5462.3.15 by Martin Pool
Turn variations into scenario lists
1763
    scenarios = multiply_scenarios(
1764
        vary_by_http_client_implementation(), 
1765
        vary_by_http_protocol_version(),
1766
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1767
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1768
    def setUp(self):
1769
        super(SmartHTTPTunnellingTest, self).setUp()
1770
        # We use the VFS layer as part of HTTP tunnelling tests.
1771
        self._captureVar('BZR_NO_SMART_VFS', None)
1772
        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.
1773
        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.
1774
1775
    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.
1776
        server = http_utils.HTTPServerWithSmarts(
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1777
            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.
1778
        server._url_protocol = self._url_protocol
1779
        return server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1780
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1781
    def test_open_bzrdir(self):
1782
        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.
1783
        url = self.http_server.get_url() + 'relpath'
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1784
        bd = bzrdir.BzrDir.open(url)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
1785
        self.addCleanup(bd.transport.disconnect)
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1786
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1787
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1788
    def test_bulk_data(self):
1789
        # We should be able to send and receive bulk data in a single message.
1790
        # The 'readv' command in the smart protocol both sends and receives
1791
        # bulk data, so we use that.
1792
        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.
1793
        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.
1794
        medium = http_transport.get_smart_medium()
1795
        # Since we provide the medium, the url below will be mostly ignored
1796
        # during the test, as long as the path is '/'.
1797
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1798
                                                  medium=medium)
1799
        self.assertEqual(
1800
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1801
1802
    def test_http_send_smart_request(self):
1803
1804
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1805
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1806
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.
1807
        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.
1808
        medium = http_transport.get_smart_medium()
1809
        response = medium.send_http_smart_request(post_body)
1810
        reply_body = response.read()
1811
        self.assertEqual(expected_reply_body, reply_body)
1812
1813
    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.
1814
        httpd = self.http_server.server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1815
1816
        socket = SampleSocket(
1817
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1818
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1819
            # for 1.0)
1820
            + 'Content-Length: 6\r\n'
1821
            '\r\n'
1822
            'hello\n')
1823
        # Beware: the ('localhost', 80) below is the
1824
        # client_address parameter, but we don't have one because
1825
        # we have defined a socket which is not bound to an
1826
        # address. The test framework never uses this client
1827
        # address, so far...
1828
        request_handler = http_utils.SmartRequestHandler(socket,
1829
                                                         ('localhost', 80),
1830
                                                         httpd)
1831
        response = socket.writefile.getvalue()
1832
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1833
        # 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.
1834
        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.
1835
        self.assertEndsWith(response, expected_end_of_response)
1836
1837
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1838
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1839
    """No smart server here request handler."""
1840
1841
    def do_POST(self):
1842
        self.send_error(403, "Forbidden")
1843
1844
1845
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1846
    """Test smart client behaviour against an http server without smarts."""
1847
1848
    _req_handler_class = ForbiddenRequestHandler
1849
1850
    def test_probe_smart_server(self):
1851
        """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.
1852
        t = self.get_readonly_transport()
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1853
        # No need to build a valid smart request here, the server will not even
1854
        # try to interpret it.
1855
        self.assertRaises(errors.SmartProtocolError,
3734.3.1 by Vincent Ladeuil
Fix SmartHTTPMedium refactoring related test.
1856
                          t.get_smart_medium().send_http_smart_request,
1857
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1858
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
1859
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1860
class Test_redirected_to(tests.TestCase):
1861
5462.3.15 by Martin Pool
Turn variations into scenario lists
1862
    scenarios = vary_by_http_client_implementation()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1863
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1864
    def test_redirected_to_subdir(self):
1865
        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.
1866
        r = t._redirected_to('http://www.example.com/foo',
1867
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1868
        self.assertIsInstance(r, type(t))
1869
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1870
        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.
1871
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1872
    def test_redirected_to_self_with_slash(self):
1873
        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.
1874
        r = t._redirected_to('http://www.example.com/foo',
1875
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1876
        self.assertIsInstance(r, type(t))
1877
        # Both transports share the some connection (one can argue that we
1878
        # should return the exact same transport here, but that seems
1879
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1880
        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
1881
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1882
    def test_redirected_to_host(self):
1883
        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.
1884
        r = t._redirected_to('http://www.example.com/foo',
1885
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1886
        self.assertIsInstance(r, type(t))
1887
1888
    def test_redirected_to_same_host_sibling_protocol(self):
1889
        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.
1890
        r = t._redirected_to('http://www.example.com/foo',
1891
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1892
        self.assertIsInstance(r, type(t))
1893
1894
    def test_redirected_to_same_host_different_protocol(self):
1895
        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.
1896
        r = t._redirected_to('http://www.example.com/foo',
1897
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1898
        self.assertNotEquals(type(r), type(t))
1899
1900
    def test_redirected_to_different_host_same_user(self):
1901
        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.
1902
        r = t._redirected_to('http://www.example.com/foo',
1903
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1904
        self.assertIsInstance(r, type(t))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1905
        self.assertEqual(t._user, r._user)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1906
1907
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1908
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1909
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1910
1911
    The only thing we care about here is how many bytes travel on the wire. But
1912
    since we want to measure it for a real http client, we have to send it
1913
    correct responses.
1914
1915
    We expect to receive a *single* request nothing more (and we won't even
1916
    check what request it is, we just measure the bytes read until an empty
1917
    line.
1918
    """
1919
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
1920
    def _handle_one_request(self):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1921
        tcs = self.server.test_case_server
1922
        requestline = self.rfile.readline()
1923
        headers = self.MessageClass(self.rfile, 0)
1924
        # We just read: the request, the headers, an empty line indicating the
1925
        # end of the headers.
1926
        bytes_read = len(requestline)
1927
        for line in headers.headers:
1928
            bytes_read += len(line)
1929
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1930
        if requestline.startswith('POST'):
1931
            # The body should be a single line (or we don't know where it ends
1932
            # and we don't want to issue a blocking read)
1933
            body = self.rfile.readline()
1934
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1935
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1936
1937
        # We set the bytes written *before* issuing the write, the client is
1938
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
1939
1940
        # Doing the oppposite may lead to test failure: we may be interrupted
1941
        # after the write but before updating the value. The client can then
1942
        # continue and read the value *before* we can update it. And yes,
1943
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1944
        tcs.bytes_written = len(tcs.canned_response)
1945
        self.wfile.write(tcs.canned_response)
1946
1947
1948
class ActivityServerMixin(object):
1949
1950
    def __init__(self, protocol_version):
1951
        super(ActivityServerMixin, self).__init__(
1952
            request_handler=PredefinedRequestHandler,
1953
            protocol_version=protocol_version)
1954
        # Bytes read and written by the server
1955
        self.bytes_read = 0
1956
        self.bytes_written = 0
1957
        self.canned_response = None
1958
1959
1960
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1961
    pass
1962
1963
1964
if tests.HTTPSServerFeature.available():
1965
    from bzrlib.tests import https_server
1966
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1967
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1968
1969
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
1970
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1971
    """Test socket activity reporting.
1972
1973
    We use a special purpose server to control the bytes sent and received and
1974
    be able to predict the activity on the client socket.
1975
    """
1976
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1977
    def setUp(self):
1978
        tests.TestCase.setUp(self)
1979
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1980
        self.server.start_server()
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1981
        self.activities = {}
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1982
        def report_activity(t, bytes, direction):
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1983
            count = self.activities.get(direction, 0)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1984
            count += bytes
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1985
            self.activities[direction] = count
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1986
1987
        # We override at class level because constructors may propagate the
1988
        # bound method and render instance overriding ineffective (an
4031.3.1 by Frank Aspell
Fixing various typos
1989
        # alternative would be to define a specific ui factory instead...)
4986.2.6 by Martin Pool
Clean up test_http setUp methods
1990
        self.overrideAttr(self._transport, '_report_activity', report_activity)
1991
        self.addCleanup(self.server.stop_server)
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1992
1993
    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.
1994
        t = self._transport(self.server.get_url())
1995
        # FIXME: Needs cleanup -- vila 20100611
1996
        return t
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1997
1998
    def assertActivitiesMatch(self):
1999
        self.assertEqual(self.server.bytes_read,
2000
                         self.activities.get('write', 0), 'written bytes')
2001
        self.assertEqual(self.server.bytes_written,
2002
                         self.activities.get('read', 0), 'read bytes')
2003
2004
    def test_get(self):
2005
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2006
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2007
Server: Apache/2.0.54 (Fedora)\r
2008
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2009
ETag: "56691-23-38e9ae00"\r
2010
Accept-Ranges: bytes\r
2011
Content-Length: 35\r
2012
Connection: close\r
2013
Content-Type: text/plain; charset=UTF-8\r
2014
\r
2015
Bazaar-NG meta directory, format 1
2016
'''
2017
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
2018
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
2019
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2020
        self.assertActivitiesMatch()
2021
2022
    def test_has(self):
2023
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2024
Server: SimpleHTTP/0.6 Python/2.5.2\r
2025
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
2026
Content-type: application/octet-stream\r
2027
Content-Length: 20\r
2028
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
2029
\r
2030
'''
2031
        t = self.get_transport()
2032
        self.assertTrue(t.has('foo/bar'))
2033
        self.assertActivitiesMatch()
2034
2035
    def test_readv(self):
2036
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2037
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2038
Server: Apache/2.0.54 (Fedora)\r
2039
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2040
ETag: "238a3c-16ec2-805c5540"\r
2041
Accept-Ranges: bytes\r
2042
Content-Length: 1534\r
2043
Connection: close\r
2044
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2045
\r
2046
\r
2047
--418470f848b63279b\r
2048
Content-type: text/plain; charset=UTF-8\r
2049
Content-range: bytes 0-254/93890\r
2050
\r
2051
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2052
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2053
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2054
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2055
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2056
\r
2057
--418470f848b63279b\r
2058
Content-type: text/plain; charset=UTF-8\r
2059
Content-range: bytes 1000-2049/93890\r
2060
\r
2061
40-fd4ec249b6b139ab
2062
mbp@sourcefrog.net-20050311063625-07858525021f270b
2063
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2064
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2065
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2066
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2067
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2068
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2069
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2070
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2071
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2072
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2073
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2074
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2075
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2076
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2077
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2078
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2079
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2080
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2081
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2082
mbp@source\r
2083
--418470f848b63279b--\r
2084
'''
2085
        t = self.get_transport()
2086
        # Remember that the request is ignored and that the ranges below
2087
        # doesn't have to match the canned response.
2088
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2089
        self.assertEqual(2, len(l))
2090
        self.assertActivitiesMatch()
2091
2092
    def test_post(self):
2093
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2094
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2095
Server: Apache/2.0.54 (Fedora)\r
2096
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2097
ETag: "56691-23-38e9ae00"\r
2098
Accept-Ranges: bytes\r
2099
Content-Length: 35\r
2100
Connection: close\r
2101
Content-Type: text/plain; charset=UTF-8\r
2102
\r
2103
lalala whatever as long as itsssss
2104
'''
2105
        t = self.get_transport()
2106
        # 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.
2107
        # PredefinedRequestHandler._handle_one_request
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2108
        code, f = t._post('abc def end-of-body\n')
2109
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2110
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2111
2112
2113
class TestActivity(tests.TestCase, TestActivityMixin):
2114
5462.3.15 by Martin Pool
Turn variations into scenario lists
2115
    scenarios = multiply_scenarios(
2116
        vary_by_http_activity(),
2117
        vary_by_http_protocol_version(),
2118
        )
5462.3.11 by Martin Pool
Delete test_http.load_tests, and just specify variations per test
2119
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2120
    def setUp(self):
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2121
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2122
2123
2124
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2125
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2126
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2127
    # ReportingSocket, so we don't need all the parametrization. Since
2128
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2129
    # test them through their use by the transport than directly (that's a
2130
    # bit less clean but far more simpler and effective).
2131
    _activity_server = ActivityHTTPServer
2132
    _protocol_version = 'HTTP/1.1'
2133
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2134
    def setUp(self):
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2135
        self._transport =_urllib.HttpTransport_urllib
2136
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2137
2138
    def assertActivitiesMatch(self):
2139
        # Nothing to check here
2140
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2141
2142
2143
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2144
    """Test authentication on the redirected http server."""
2145
5462.3.15 by Martin Pool
Turn variations into scenario lists
2146
    scenarios = vary_by_http_protocol_version()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
2147
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2148
    _auth_header = 'Authorization'
2149
    _password_prompt_prefix = ''
2150
    _username_prompt_prefix = ''
2151
    _auth_server = http_utils.HTTPBasicAuthServer
2152
    _transport = _urllib.HttpTransport_urllib
2153
2154
    def setUp(self):
2155
        super(TestAuthOnRedirected, self).setUp()
2156
        self.build_tree_contents([('a','a'),
2157
                                  ('1/',),
2158
                                  ('1/a', 'redirected once'),
2159
                                  ],)
2160
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2161
                                       self.new_server.port)
2162
        self.old_server.redirections = [
2163
            ('(.*)', 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.
2164
        self.old_transport = self.get_old_transport()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2165
        self.new_server.add_user('joe', 'foo')
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
2166
        cleanup_http_redirection_connections(self)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2167
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.
2168
    def create_transport_readonly_server(self):
2169
        server = self._auth_server(protocol_version=self._protocol_version)
2170
        server._url_protocol = self._url_protocol
2171
        return server
2172
2173
    def get_a(self, t):
2174
        return t.get('a')
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2175
2176
    def test_auth_on_redirected_via_do_catching_redirections(self):
2177
        self.redirections = 0
2178
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.
2179
        def redirected(t, exception, redirection_notice):
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2180
            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.
2181
            redirected_t = t._redirected_to(exception.source, exception.target)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2182
            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.
2183
            return redirected_t
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2184
2185
        stdout = tests.StringIOWrapper()
2186
        stderr = tests.StringIOWrapper()
2187
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2188
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2189
        self.assertEqual('redirected once',
2190
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2191
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2192
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2193
        # stdin should be empty
2194
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2195
        # stdout should be empty, stderr will contains the prompts
2196
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2197
2198
    def test_auth_on_redirected_via_following_redirections(self):
2199
        self.new_server.add_user('joe', 'foo')
2200
        stdout = tests.StringIOWrapper()
2201
        stderr = tests.StringIOWrapper()
2202
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2203
                                            stdout=stdout, stderr=stderr)
2204
        t = self.old_transport
2205
        req = RedirectedRequest('GET', t.abspath('a'))
2206
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2207
                                       self.new_server.port)
2208
        self.old_server.redirections = [
2209
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2210
        self.assertEqual('redirected once', t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2211
        # stdin should be empty
2212
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2213
        # stdout should be empty, stderr will contains the prompts
2214
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2215
2216