~bzr-pqm/bzr/bzr.dev

5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2005-2011 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,
3995.2.2 by Martin Pool
Cope with read_bundle_from_url deprecation in test_http
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"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
357
        t = self._transport('http://example.com/bzr/bzr.dev/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
358
        eq = self.assertEqualDiff
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
359
        eq(t.abspath('.'), 'http://example.com/bzr/bzr.dev')
360
        eq(t.abspath('foo/bar'), 'http://example.com/bzr/bzr.dev/foo/bar')
361
        eq(t.abspath('.bzr'), 'http://example.com/bzr/bzr.dev/.bzr')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
362
        eq(t.abspath('.bzr/1//2/./3'),
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
363
           'http://example.com/bzr/bzr.dev/.bzr/1/2/3')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
364
365
    def test_invalid_http_urls(self):
366
        """Trap invalid construction of urls"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
367
        self._transport('http://example.com/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,
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
370
                          'http://http://example.com/bzr/bzr.dev/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
371
372
    def test_http_root_urls(self):
373
        """Construction of URLs from server root"""
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
374
        t = self._transport('http://example.com/')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
375
        eq = self.assertEqualDiff
376
        eq(t.abspath('.bzr/tree-version'),
5560.2.1 by Vincent Ladeuil
Fix the remaining references to http://bazaar-vcs.org (except the explicitly historical ones).
377
           'http://example.com/.bzr/tree-version')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
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())
5514.1.1 by Vincent Ladeuil
Correctly set the Content-Type header when POSTing.
510
        self.assertTrue('content-type: application/octet-stream\r'
511
                        in server.received_bytes.lower())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
512
        # The transport should not be assuming that the server can accept
513
        # chunked encoding the first time it connects, because HTTP/1.1, so we
514
        # check for the literal string.
515
        self.assertTrue(
516
            server.received_bytes.endswith('\r\n\r\nabc def end-of-body'))
517
518
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
519
class TestRangeHeader(tests.TestCase):
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
520
    """Test range_header method"""
521
522
    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.
523
        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
524
        coalesce = transport.Transport._coalesce_offsets
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
525
        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.
526
        range_header = http.HttpTransportBase._range_header
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
527
        self.assertEqual(value, range_header(coalesced, tail))
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
528
529
    def test_range_header_single(self):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
530
        self.check_header('0-9', ranges=[(0,9)])
531
        self.check_header('100-109', ranges=[(100,109)])
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
532
533
    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=
534
        self.check_header('-10', tail=10)
535
        self.check_header('-50', tail=50)
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
536
537
    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=
538
        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
539
                          ranges=[(0,9), (100, 200), (300,5000)])
540
541
    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=
542
        self.check_header('0-9,300-5000,-50',
1786.1.28 by John Arbash Meinel
Update and add tests for the HttpTransportBase.range_header
543
                          ranges=[(0,9), (300,5000)],
544
                          tail=50)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
545
2004.1.15 by v.ladeuil+lp at free
Better design for bogus servers. Both urllib and pycurl pass tests.
546
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
547
class TestSpecificRequestHandler(http_utils.TestCaseWithWebserver):
548
    """Tests a specific request handler.
549
3111.1.31 by Vincent Ladeuil
Review feeback.
550
    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.
551
    """
552
5462.3.15 by Martin Pool
Turn variations into scenario lists
553
    scenarios = multiply_scenarios(
554
        vary_by_http_client_implementation(), 
555
        vary_by_http_protocol_version(),
556
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
557
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
558
    # Provide a useful default
559
    _req_handler_class = http_server.TestingHTTPRequestHandler
560
561
    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.
562
        server = http_server.HttpServer(self._req_handler_class,
563
                                        protocol_version=self._protocol_version)
564
        server._url_protocol = self._url_protocol
565
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
566
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
567
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
568
        # TODO: This is duplicated for lots of the classes in this file
569
        return (features.pycurl.available()
570
                and self._transport == PyCurlTransport)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
571
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
572
573
class WallRequestHandler(http_server.TestingHTTPRequestHandler):
574
    """Whatever request comes in, close the connection"""
575
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
576
    def _handle_one_request(self):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
577
        """Handle a single HTTP request, by abruptly closing the connection"""
578
        self.close_connection = 1
579
580
581
class TestWallServer(TestSpecificRequestHandler):
582
    """Tests exceptions during the connection phase"""
583
584
    _req_handler_class = WallRequestHandler
585
586
    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.
587
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
588
        # Unfortunately httplib (see HTTPResponse._read_status
589
        # for details) make no distinction between a closed
590
        # socket and badly formatted status line, so we can't
591
        # just test for ConnectionError, we have to test
4628.1.2 by Vincent Ladeuil
More complete fix.
592
        # InvalidHttpResponse too. And pycurl may raise ConnectionReset
593
        # instead of ConnectionError too.
594
        self.assertRaises(( errors.ConnectionError, errors.ConnectionReset,
595
                            errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
596
                          t.has, 'foo/bar')
597
598
    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.
599
        t = self.get_readonly_transport()
4628.1.2 by Vincent Ladeuil
More complete fix.
600
        self.assertRaises((errors.ConnectionError, errors.ConnectionReset,
601
                           errors.InvalidHttpResponse),
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
602
                          t.get, 'foo/bar')
603
604
605
class BadStatusRequestHandler(http_server.TestingHTTPRequestHandler):
606
    """Whatever request comes in, returns a bad status"""
607
608
    def parse_request(self):
609
        """Fakes handling a single HTTP request, returns a bad status"""
610
        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.
611
        self.send_response(0, "Bad status")
612
        self.close_connection = 1
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
613
        return False
614
615
616
class TestBadStatusServer(TestSpecificRequestHandler):
617
    """Tests bad status from server."""
618
619
    _req_handler_class = BadStatusRequestHandler
620
621
    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.
622
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
623
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
624
625
    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.
626
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
627
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
628
629
630
class InvalidStatusRequestHandler(http_server.TestingHTTPRequestHandler):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
631
    """Whatever request comes in, returns an invalid status"""
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
632
633
    def parse_request(self):
634
        """Fakes handling a single HTTP request, returns a bad status"""
635
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
636
        self.wfile.write("Invalid status line\r\n")
5247.6.6 by Vincent Ladeuil
Closing the connection is what pycurl was waiting for.
637
        # If we don't close the connection pycurl will hang. Since this is a
638
        # stress test we don't *have* to respect the protocol, but we don't
639
        # have to sabotage it too much either.
640
        self.close_connection = True
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
641
        return False
642
643
644
class TestInvalidStatusServer(TestBadStatusServer):
645
    """Tests invalid status from server.
646
647
    Both implementations raises the same error as for a bad status.
648
    """
649
650
    _req_handler_class = InvalidStatusRequestHandler
651
652
653
class BadProtocolRequestHandler(http_server.TestingHTTPRequestHandler):
654
    """Whatever request comes in, returns a bad protocol version"""
655
656
    def parse_request(self):
657
        """Fakes handling a single HTTP request, returns a bad status"""
658
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
659
        # Returns an invalid protocol version, but curl just
660
        # ignores it and those cannot be tested.
661
        self.wfile.write("%s %d %s\r\n" % ('HTTP/0.0',
662
                                           404,
663
                                           'Look at my protocol version'))
664
        return False
665
666
667
class TestBadProtocolServer(TestSpecificRequestHandler):
668
    """Tests bad protocol from server."""
669
670
    _req_handler_class = BadProtocolRequestHandler
671
672
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
673
        if self._testing_pycurl():
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
674
            raise tests.TestNotApplicable(
675
                "pycurl doesn't check the protocol version")
676
        super(TestBadProtocolServer, self).setUp()
677
678
    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.
679
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
680
        self.assertRaises(errors.InvalidHttpResponse, t.has, 'foo/bar')
681
682
    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.
683
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
684
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'foo/bar')
685
686
687
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
688
    """Whatever request comes in, returns a 403 code"""
689
690
    def parse_request(self):
691
        """Handle a single HTTP request, by replying we cannot handle it"""
692
        ignored = http_server.TestingHTTPRequestHandler.parse_request(self)
693
        self.send_error(403)
694
        return False
695
696
697
class TestForbiddenServer(TestSpecificRequestHandler):
698
    """Tests forbidden server"""
699
700
    _req_handler_class = ForbiddenRequestHandler
701
702
    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.
703
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
704
        self.assertRaises(errors.TransportError, t.has, 'foo/bar')
705
706
    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.
707
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
708
        self.assertRaises(errors.TransportError, t.get, 'foo/bar')
709
710
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
711
class TestRecordingServer(tests.TestCase):
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
712
713
    def test_create(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
714
        server = RecordingServer(expect_body_tail=None)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
715
        self.assertEqual('', server.received_bytes)
716
        self.assertEqual(None, server.host)
717
        self.assertEqual(None, server.port)
718
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
719
    def test_setUp_and_stop(self):
3111.1.29 by Vincent Ladeuil
Cancel RecordingServer move, that was useless.
720
        server = RecordingServer(expect_body_tail=None)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
721
        server.start_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
722
        try:
723
            self.assertNotEqual(None, server.host)
724
            self.assertNotEqual(None, server.port)
725
        finally:
4934.3.1 by Martin Pool
Rename Server.tearDown to .stop_server
726
            server.stop_server()
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
727
        self.assertEqual(None, server.host)
728
        self.assertEqual(None, server.port)
729
730
    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.
731
        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,
732
        self.start_server(server)
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
733
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
734
        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.
735
        sock.sendall('abc')
736
        self.assertEqual('HTTP/1.1 200 OK\r\n',
737
                         osutils.recv_all(sock, 4096))
2018.2.9 by Andrew Bennetts
(Andrew Bennetts, Robert Collins) Add test_http.RecordingServer, and use it to
738
        self.assertEqual('abc', server.received_bytes)
2004.1.29 by v.ladeuil+lp at free
New tests for http range requests handling.
739
740
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
741
class TestRangeRequestServer(TestSpecificRequestHandler):
742
    """Tests readv requests against server.
743
744
    We test against default "normal" server.
745
    """
746
747
    def setUp(self):
748
        super(TestRangeRequestServer, self).setUp()
749
        self.build_tree_contents([('a', '0123456789')],)
750
751
    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.
752
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
753
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
754
        self.assertEqual(l[0], (0, '0'))
755
        self.assertEqual(l[1], (1, '1'))
756
        self.assertEqual(l[2], (3, '34'))
757
        self.assertEqual(l[3], (9, '9'))
758
759
    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.
760
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
761
        l = list(t.readv('a', ((1, 1), (9, 1), (0, 1), (3, 2))))
762
        self.assertEqual(l[0], (1, '1'))
763
        self.assertEqual(l[1], (9, '9'))
764
        self.assertEqual(l[2], (0, '0'))
765
        self.assertEqual(l[3], (3, '34'))
766
767
    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.
768
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
769
770
        # This is intentionally reading off the end of the file
771
        # since we are sure that it cannot get there
772
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
773
                              t.readv, 'a', [(1,1), (8,10)])
774
775
        # This is trying to seek past the end of the file, it should
776
        # also raise a special error
777
        self.assertListRaises((errors.InvalidRange, errors.ShortReadvError,),
778
                              t.readv, 'a', [(12,2)])
779
780
    def test_readv_multiple_get_requests(self):
781
        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.
782
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
783
        # force transport to issue multiple requests
784
        t._max_readv_combine = 1
785
        t._max_get_ranges = 1
786
        l = list(t.readv('a', ((0, 1), (1, 1), (3, 2), (9, 1))))
787
        self.assertEqual(l[0], (0, '0'))
788
        self.assertEqual(l[1], (1, '1'))
789
        self.assertEqual(l[2], (3, '34'))
790
        self.assertEqual(l[3], (9, '9'))
791
        # The server should have issued 4 requests
792
        self.assertEqual(4, server.GET_request_nb)
793
794
    def test_readv_get_max_size(self):
795
        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.
796
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
797
        # force transport to issue multiple requests by limiting the number of
798
        # 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.
799
        # 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.
800
        t._get_max_size = 2
801
        l = list(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
802
        self.assertEqual(l[0], (0, '0'))
803
        self.assertEqual(l[1], (1, '1'))
804
        self.assertEqual(l[2], (2, '2345'))
805
        self.assertEqual(l[3], (6, '6789'))
806
        # The server should have issued 3 requests
807
        self.assertEqual(3, server.GET_request_nb)
808
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
809
    def test_complete_readv_leave_pipe_clean(self):
810
        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.
811
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
812
        # force transport to issue multiple requests
813
        t._get_max_size = 2
5462.3.16 by Martin Pool
pyflakes cleanups
814
        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.
815
        # The server should have issued 3 requests
816
        self.assertEqual(3, server.GET_request_nb)
817
        self.assertEqual('0123456789', t.get_bytes('a'))
818
        self.assertEqual(4, server.GET_request_nb)
819
820
    def test_incomplete_readv_leave_pipe_clean(self):
821
        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.
822
        t = self.get_readonly_transport()
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
823
        # force transport to issue multiple requests
824
        t._get_max_size = 2
825
        # Don't collapse readv results into a list so that we leave unread
826
        # bytes on the socket
827
        ireadv = iter(t.readv('a', ((0, 1), (1, 1), (2, 4), (6, 4))))
828
        self.assertEqual((0, '0'), ireadv.next())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
829
        # The server should have issued one request so far
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
830
        self.assertEqual(1, server.GET_request_nb)
831
        self.assertEqual('0123456789', t.get_bytes('a'))
832
        # get_bytes issued an additional request, the readv pending ones are
833
        # lost
834
        self.assertEqual(2, server.GET_request_nb)
835
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
836
837
class SingleRangeRequestHandler(http_server.TestingHTTPRequestHandler):
838
    """Always reply to range request as if they were single.
839
840
    Don't be explicit about it, just to annoy the clients.
841
    """
842
843
    def get_multiple_ranges(self, file, file_size, ranges):
844
        """Answer as if it was a single range request and ignores the rest"""
845
        (start, end) = ranges[0]
846
        return self.get_single_range(file, file_size, start, end)
847
848
849
class TestSingleRangeRequestServer(TestRangeRequestServer):
850
    """Test readv against a server which accept only single range requests"""
851
852
    _req_handler_class = SingleRangeRequestHandler
853
854
855
class SingleOnlyRangeRequestHandler(http_server.TestingHTTPRequestHandler):
856
    """Only reply to simple range requests, errors out on multiple"""
857
858
    def get_multiple_ranges(self, file, file_size, ranges):
859
        """Refuses the multiple ranges request"""
860
        if len(ranges) > 1:
861
            file.close()
862
            self.send_error(416, "Requested range not satisfiable")
863
            return
864
        (start, end) = ranges[0]
865
        return self.get_single_range(file, file_size, start, end)
866
867
868
class TestSingleOnlyRangeRequestServer(TestRangeRequestServer):
869
    """Test readv against a server which only accept single range requests"""
870
871
    _req_handler_class = SingleOnlyRangeRequestHandler
872
873
874
class NoRangeRequestHandler(http_server.TestingHTTPRequestHandler):
875
    """Ignore range requests without notice"""
876
877
    def do_GET(self):
878
        # Update the statistics
879
        self.server.test_case_server.GET_request_nb += 1
880
        # Just bypass the range handling done by TestingHTTPRequestHandler
881
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
882
883
884
class TestNoRangeRequestServer(TestRangeRequestServer):
885
    """Test readv against a server which do not accept range requests"""
886
887
    _req_handler_class = NoRangeRequestHandler
888
889
3111.1.28 by Vincent Ladeuil
Fix the multi-ranges http server and add tests.
890
class MultipleRangeWithoutContentLengthRequestHandler(
891
    http_server.TestingHTTPRequestHandler):
892
    """Reply to multiple range requests without content length header."""
893
894
    def get_multiple_ranges(self, file, file_size, ranges):
895
        self.send_response(206)
896
        self.send_header('Accept-Ranges', 'bytes')
5462.3.16 by Martin Pool
pyflakes cleanups
897
        # XXX: this is strange; the 'random' name below seems undefined and
5462.3.19 by Martin Pool
Mention bug 658773 in comment
898
        # 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.
899
        boundary = "%d" % random.randint(0,0x7FFFFFFF)
900
        self.send_header("Content-Type",
901
                         "multipart/byteranges; boundary=%s" % boundary)
902
        self.end_headers()
903
        for (start, end) in ranges:
904
            self.wfile.write("--%s\r\n" % boundary)
905
            self.send_header("Content-type", 'application/octet-stream')
906
            self.send_header("Content-Range", "bytes %d-%d/%d" % (start,
907
                                                                  end,
908
                                                                  file_size))
909
            self.end_headers()
910
            self.send_range_content(file, start, end - start + 1)
911
        # Final boundary
912
        self.wfile.write("--%s\r\n" % boundary)
913
914
915
class TestMultipleRangeWithoutContentLengthServer(TestRangeRequestServer):
916
917
    _req_handler_class = MultipleRangeWithoutContentLengthRequestHandler
918
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
919
920
class TruncatedMultipleRangeRequestHandler(
921
    http_server.TestingHTTPRequestHandler):
922
    """Reply to multiple range requests truncating the last ones.
923
924
    This server generates responses whose Content-Length describes all the
925
    ranges, but fail to include the last ones leading to client short reads.
926
    This has been observed randomly with lighttpd (bug #179368).
927
    """
928
929
    _truncated_ranges = 2
930
931
    def get_multiple_ranges(self, file, file_size, ranges):
932
        self.send_response(206)
933
        self.send_header('Accept-Ranges', 'bytes')
934
        boundary = 'tagada'
935
        self.send_header('Content-Type',
936
                         'multipart/byteranges; boundary=%s' % boundary)
937
        boundary_line = '--%s\r\n' % boundary
938
        # Calculate the Content-Length
939
        content_length = 0
940
        for (start, end) in ranges:
941
            content_length += len(boundary_line)
942
            content_length += self._header_line_length(
943
                'Content-type', 'application/octet-stream')
944
            content_length += self._header_line_length(
945
                'Content-Range', 'bytes %d-%d/%d' % (start, end, file_size))
946
            content_length += len('\r\n') # end headers
947
            content_length += end - start # + 1
948
        content_length += len(boundary_line)
949
        self.send_header('Content-length', content_length)
950
        self.end_headers()
951
952
        # Send the multipart body
953
        cur = 0
954
        for (start, end) in ranges:
955
            self.wfile.write(boundary_line)
956
            self.send_header('Content-type', 'application/octet-stream')
957
            self.send_header('Content-Range', 'bytes %d-%d/%d'
958
                             % (start, end, file_size))
959
            self.end_headers()
960
            if cur + self._truncated_ranges >= len(ranges):
961
                # Abruptly ends the response and close the connection
962
                self.close_connection = 1
963
                return
964
            self.send_range_content(file, start, end - start + 1)
965
            cur += 1
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
966
        # Final boundary
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
967
        self.wfile.write(boundary_line)
968
969
970
class TestTruncatedMultipleRangeServer(TestSpecificRequestHandler):
971
972
    _req_handler_class = TruncatedMultipleRangeRequestHandler
973
974
    def setUp(self):
975
        super(TestTruncatedMultipleRangeServer, self).setUp()
976
        self.build_tree_contents([('a', '0123456789')],)
977
978
    def test_readv_with_short_reads(self):
979
        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.
980
        t = self.get_readonly_transport()
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
981
        # Force separate ranges for each offset
982
        t._bytes_to_read_before_seek = 0
983
        ireadv = iter(t.readv('a', ((0, 1), (2, 1), (4, 2), (9, 1))))
984
        self.assertEqual((0, '0'), ireadv.next())
985
        self.assertEqual((2, '2'), ireadv.next())
986
        if not self._testing_pycurl():
987
            # Only one request have been issued so far (except for pycurl that
988
            # try to read the whole response at once)
989
            self.assertEqual(1, server.GET_request_nb)
990
        self.assertEqual((4, '45'), ireadv.next())
991
        self.assertEqual((9, '9'), ireadv.next())
992
        # Both implementations issue 3 requests but:
993
        # - urllib does two multiple (4 ranges, then 2 ranges) then a single
994
        #   range,
995
        # - pycurl does two multiple (4 ranges, 4 ranges) then a single range
996
        self.assertEqual(3, server.GET_request_nb)
997
        # Finally the client have tried a single range request and stays in
998
        # that mode
999
        self.assertEqual('single', t._range_hint)
1000
5504.4.1 by Vincent Ladeuil
Fix http test spurious failures and get rid of some useless messages in log.
1001
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1002
class LimitedRangeRequestHandler(http_server.TestingHTTPRequestHandler):
1003
    """Errors out when range specifiers exceed the limit"""
1004
1005
    def get_multiple_ranges(self, file, file_size, ranges):
1006
        """Refuses the multiple ranges request"""
1007
        tcs = self.server.test_case_server
1008
        if tcs.range_limit is not None and len(ranges) > tcs.range_limit:
1009
            file.close()
1010
            # Emulate apache behavior
1011
            self.send_error(400, "Bad Request")
1012
            return
1013
        return http_server.TestingHTTPRequestHandler.get_multiple_ranges(
1014
            self, file, file_size, ranges)
1015
1016
1017
class LimitedRangeHTTPServer(http_server.HttpServer):
1018
    """An HttpServer erroring out on requests with too much range specifiers"""
1019
1020
    def __init__(self, request_handler=LimitedRangeRequestHandler,
1021
                 protocol_version=None,
1022
                 range_limit=None):
1023
        http_server.HttpServer.__init__(self, request_handler,
1024
                                        protocol_version=protocol_version)
1025
        self.range_limit = range_limit
1026
1027
1028
class TestLimitedRangeRequestServer(http_utils.TestCaseWithWebserver):
1029
    """Tests readv requests against a server erroring out on too much ranges."""
1030
5462.3.15 by Martin Pool
Turn variations into scenario lists
1031
    scenarios = multiply_scenarios(
1032
        vary_by_http_client_implementation(), 
1033
        vary_by_http_protocol_version(),
1034
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1035
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1036
    # Requests with more range specifiers will error out
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1037
    range_limit = 3
1038
1039
    def create_transport_readonly_server(self):
1040
        return LimitedRangeHTTPServer(range_limit=self.range_limit,
1041
                                      protocol_version=self._protocol_version)
1042
1043
    def setUp(self):
1044
        http_utils.TestCaseWithWebserver.setUp(self)
1045
        # We need to manipulate ranges that correspond to real chunks in the
1046
        # response, so we build a content appropriately.
1047
        filler = ''.join(['abcdefghij' for x in range(102)])
1048
        content = ''.join(['%04d' % v + filler for v in range(16)])
1049
        self.build_tree_contents([('a', content)],)
1050
1051
    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.
1052
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1053
        l = list(t.readv('a', ((0, 4), (1024, 4), )))
1054
        self.assertEqual(l[0], (0, '0000'))
1055
        self.assertEqual(l[1], (1024, '0001'))
1056
        self.assertEqual(1, self.get_readonly_server().GET_request_nb)
1057
1058
    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.
1059
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1060
        l = list(t.readv('a', ((0, 4), (1024, 4), (4096, 4), (8192, 4))))
1061
        self.assertEqual(l[0], (0, '0000'))
1062
        self.assertEqual(l[1], (1024, '0001'))
1063
        self.assertEqual(l[2], (4096, '0004'))
1064
        self.assertEqual(l[3], (8192, '0008'))
1065
        # The server will refuse to serve the first request (too much ranges),
3199.1.2 by Vincent Ladeuil
Fix two more leaked log files.
1066
        # a second request will succeed.
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1067
        self.assertEqual(2, self.get_readonly_server().GET_request_nb)
1068
1069
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
1070
class TestHttpProxyWhiteBox(tests.TestCase):
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1071
    """Whitebox test proxy http authorization.
1072
2420.1.3 by Vincent Ladeuil
Implement http proxy basic authentication.
1073
    Only the urllib implementation is tested here.
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1074
    """
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1075
1076
    def _proxied_request(self):
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1077
        handler = _urllib2_wrappers.ProxyHandler()
1078
        request = _urllib2_wrappers.Request('GET','http://baz/buzzle')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1079
        handler.set_proxy(request, 'http')
1080
        return request
1081
1082
    def test_empty_user(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1083
        self.overrideEnv('http_proxy', 'http://bar.com')
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1084
        request = self._proxied_request()
1085
        self.assertFalse(request.headers.has_key('Proxy-authorization'))
1086
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1087
    def test_invalid_proxy(self):
1088
        """A proxy env variable without scheme"""
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1089
        self.overrideEnv('http_proxy', 'host:1234')
2298.7.1 by Vincent Ladeuil
Fix bug #87765: proxy env variables without scheme should cause
1090
        self.assertRaises(errors.InvalidURL, self._proxied_request)
2273.2.2 by v.ladeuil+lp at free
Really fix bug #83954, with tests.
1091
1092
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1093
class TestProxyHttpServer(http_utils.TestCaseWithTwoWebservers):
1094
    """Tests proxy server.
1095
1096
    Be aware that we do not setup a real proxy here. Instead, we
1097
    check that the *connection* goes through the proxy by serving
1098
    different content (the faked proxy server append '-proxied'
1099
    to the file names).
1100
    """
1101
5462.3.15 by Martin Pool
Turn variations into scenario lists
1102
    scenarios = multiply_scenarios(
1103
        vary_by_http_client_implementation(), 
1104
        vary_by_http_protocol_version(),
1105
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1106
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1107
    # 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.
1108
    # test https connections. --vila toolongago
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1109
1110
    def setUp(self):
1111
        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.
1112
        self.transport_secondary_server = http_utils.ProxyServer
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1113
        self.build_tree_contents([('foo', 'contents of foo\n'),
1114
                                  ('foo-proxied', 'proxied contents of foo\n')])
1115
        # 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.
1116
        server = self.get_readonly_server()
1117
        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.
1118
        if self._testing_pycurl():
1119
            # Oh my ! pycurl does not check for the port as part of
1120
            # 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.
1121
            self.no_proxy_host = server.host
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1122
        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.
1123
            self.no_proxy_host = self.server_host_port
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1124
        # 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.
1125
        self.proxy_url = self.get_secondary_url()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1126
1127
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1128
        # TODO: This is duplicated for lots of the classes in this file
1129
        return (features.pycurl.available()
1130
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1131
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1132
    def assertProxied(self):
1133
        t = self.get_readonly_transport()
1134
        self.assertEqual('proxied contents of foo\n', t.get('foo').read())
1135
1136
    def assertNotProxied(self):
1137
        t = self.get_readonly_transport()
1138
        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.
1139
1140
    def test_http_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1141
        self.overrideEnv('http_proxy', self.proxy_url)
1142
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1143
1144
    def test_HTTP_PROXY(self):
1145
        if self._testing_pycurl():
1146
            # pycurl does not check HTTP_PROXY for security reasons
1147
            # (for use in a CGI context that we do not care
1148
            # about. Should we ?)
1149
            raise tests.TestNotApplicable(
1150
                'pycurl does not check HTTP_PROXY for security reasons')
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1151
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1152
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1153
1154
    def test_all_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1155
        self.overrideEnv('all_proxy', self.proxy_url)
1156
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1157
1158
    def test_ALL_PROXY(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1159
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1160
        self.assertProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1161
1162
    def test_http_proxy_with_no_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1163
        self.overrideEnv('no_proxy', self.no_proxy_host)
1164
        self.overrideEnv('http_proxy', self.proxy_url)
1165
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1166
1167
    def test_HTTP_PROXY_with_NO_PROXY(self):
1168
        if self._testing_pycurl():
1169
            raise tests.TestNotApplicable(
1170
                'pycurl does not check HTTP_PROXY for security reasons')
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1171
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1172
        self.overrideEnv('HTTP_PROXY', self.proxy_url)
1173
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1174
1175
    def test_all_proxy_with_no_proxy(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1176
        self.overrideEnv('no_proxy', self.no_proxy_host)
1177
        self.overrideEnv('all_proxy', self.proxy_url)
1178
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1179
1180
    def test_ALL_PROXY_with_NO_PROXY(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1181
        self.overrideEnv('NO_PROXY', self.no_proxy_host)
1182
        self.overrideEnv('ALL_PROXY', self.proxy_url)
1183
        self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1184
1185
    def test_http_proxy_without_scheme(self):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1186
        self.overrideEnv('http_proxy', self.server_host_port)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1187
        if self._testing_pycurl():
1188
            # pycurl *ignores* invalid proxy env variables. If that ever change
1189
            # in the future, this test will fail indicating that pycurl do not
1190
            # ignore anymore such variables.
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1191
            self.assertNotProxied()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1192
        else:
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1193
            self.assertRaises(errors.InvalidURL, self.assertProxied)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1194
1195
1196
class TestRanges(http_utils.TestCaseWithWebserver):
1197
    """Test the Range header in GET methods."""
1198
5462.3.15 by Martin Pool
Turn variations into scenario lists
1199
    scenarios = multiply_scenarios(
1200
        vary_by_http_client_implementation(), 
1201
        vary_by_http_protocol_version(),
1202
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1203
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1204
    def setUp(self):
1205
        http_utils.TestCaseWithWebserver.setUp(self)
1206
        self.build_tree_contents([('a', '0123456789')],)
1207
3111.1.22 by Vincent Ladeuil
Rework TestingHTTPServer classes, fix test bug.
1208
    def create_transport_readonly_server(self):
1209
        return http_server.HttpServer(protocol_version=self._protocol_version)
1210
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1211
    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.
1212
        t = self.get_readonly_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1213
        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.
1214
        coalesce = t._coalesce_offsets
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1215
        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.
1216
        code, data = t._get(relpath, coalesced)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1217
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1218
        for start, end in ranges:
1219
            data.seek(start)
1220
            yield data.read(end - start + 1)
1221
1222
    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.
1223
        t = self.get_readonly_transport()
1224
        code, data = t._get(relpath, [], tail_amount)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1225
        self.assertTrue(code in (200, 206),'_get returns: %d' % code)
1226
        data.seek(-tail_amount, 2)
1227
        return data.read(tail_amount)
1228
1229
    def test_range_header(self):
1230
        # Valid ranges
1231
        map(self.assertEqual,['0', '234'],
1232
            list(self._file_contents('a', [(0,0), (2,4)])),)
1233
1234
    def test_range_header_tail(self):
1235
        self.assertEqual('789', self._file_tail('a', 3))
1236
1237
    def test_syntactically_invalid_range_header(self):
1238
        self.assertListRaises(errors.InvalidHttpRange,
1239
                          self._file_contents, 'a', [(4, 3)])
1240
1241
    def test_semantically_invalid_range_header(self):
1242
        self.assertListRaises(errors.InvalidHttpRange,
1243
                          self._file_contents, 'a', [(42, 128)])
1244
1245
1246
class TestHTTPRedirections(http_utils.TestCaseWithRedirectedWebserver):
1247
    """Test redirection between http servers."""
1248
5462.3.15 by Martin Pool
Turn variations into scenario lists
1249
    scenarios = multiply_scenarios(
1250
        vary_by_http_client_implementation(), 
1251
        vary_by_http_protocol_version(),
1252
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1253
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1254
    def setUp(self):
1255
        super(TestHTTPRedirections, self).setUp()
1256
        self.build_tree_contents([('a', '0123456789'),
1257
                                  ('bundle',
1258
                                  '# Bazaar revision bundle v0.9\n#\n')
1259
                                  ],)
1260
1261
    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.
1262
        self.assertRaises(errors.RedirectRequested,
1263
                          self.get_old_transport().get, 'a')
1264
        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.
1265
1266
1267
class RedirectedRequest(_urllib2_wrappers.Request):
1268
    """Request following redirections. """
1269
1270
    init_orig = _urllib2_wrappers.Request.__init__
1271
1272
    def __init__(self, method, url, *args, **kwargs):
1273
        """Constructor.
1274
1275
        """
1276
        # Since the tests using this class will replace
1277
        # _urllib2_wrappers.Request, we can't just call the base class __init__
1278
        # or we'll loop.
4208.3.2 by Andrew Bennetts
Fix one test failure in test_http under Python 2.7a0.
1279
        RedirectedRequest.init_orig(self, method, url, *args, **kwargs)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1280
        self.follow_redirections = True
1281
1282
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1283
def install_redirected_request(test):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1284
    test.overrideAttr(_urllib2_wrappers, 'Request', RedirectedRequest)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1285
1286
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1287
def cleanup_http_redirection_connections(test):
1288
    # Some sockets are opened but never seen by _urllib, so we trap them at
1289
    # the _urllib2_wrappers level to be able to clean them up.
1290
    def socket_disconnect(sock):
1291
        try:
1292
            sock.shutdown(socket.SHUT_RDWR)
1293
            sock.close()
1294
        except socket.error:
1295
            pass
1296
    def connect(connection):
1297
        test.http_connect_orig(connection)
1298
        test.addCleanup(socket_disconnect, connection.sock)
1299
    test.http_connect_orig = test.overrideAttr(
1300
        _urllib2_wrappers.HTTPConnection, 'connect', connect)
1301
    def connect(connection):
1302
        test.https_connect_orig(connection)
1303
        test.addCleanup(socket_disconnect, connection.sock)
1304
    test.https_connect_orig = test.overrideAttr(
1305
        _urllib2_wrappers.HTTPSConnection, 'connect', connect)
1306
1307
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1308
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1309
    """Test redirections.
1310
1311
    http implementations do not redirect silently anymore (they
1312
    do not redirect at all in fact). The mechanism is still in
1313
    place at the _urllib2_wrappers.Request level and these tests
1314
    exercise it.
1315
1316
    For the pycurl implementation
1317
    the redirection have been deleted as we may deprecate pycurl
1318
    and I have no place to keep a working implementation.
1319
    -- vila 20070212
1320
    """
1321
5462.3.15 by Martin Pool
Turn variations into scenario lists
1322
    scenarios = multiply_scenarios(
1323
        vary_by_http_client_implementation(), 
1324
        vary_by_http_protocol_version(),
1325
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1326
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1327
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1328
        if (features.pycurl.available()
1329
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1330
            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.
1331
                "pycurl doesn't redirect silently anymore")
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1332
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1333
        install_redirected_request(self)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1334
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1335
        self.build_tree_contents([('a','a'),
1336
                                  ('1/',),
1337
                                  ('1/a', 'redirected once'),
1338
                                  ('2/',),
1339
                                  ('2/a', 'redirected twice'),
1340
                                  ('3/',),
1341
                                  ('3/a', 'redirected thrice'),
1342
                                  ('4/',),
1343
                                  ('4/a', 'redirected 4 times'),
1344
                                  ('5/',),
1345
                                  ('5/a', 'redirected 5 times'),
1346
                                  ],)
1347
1348
    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.
1349
        t = self.get_old_transport()
1350
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1351
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1352
                                       self.new_server.port)
1353
        self.old_server.redirections = \
1354
            [('(.*)', 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.
1355
        self.assertEqual('redirected once', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1356
1357
    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.
1358
        t = self.get_old_transport()
1359
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1360
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1361
                                       self.old_server.port)
1362
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1363
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1364
        self.old_server.redirections = [
1365
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1366
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1367
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1368
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1369
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1370
            ]
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.
1371
        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.
1372
1373
1374
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1375
    """Test transport.do_catching_redirections."""
1376
5462.3.15 by Martin Pool
Turn variations into scenario lists
1377
    scenarios = multiply_scenarios(
1378
        vary_by_http_client_implementation(), 
1379
        vary_by_http_protocol_version(),
1380
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1381
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1382
    def setUp(self):
1383
        super(TestDoCatchRedirections, self).setUp()
1384
        self.build_tree_contents([('a', '0123456789'),],)
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
1385
        cleanup_http_redirection_connections(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1386
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.
1387
        self.old_transport = self.get_old_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1388
5247.3.31 by Vincent Ladeuil
Cleanup some imports in http_utils.py.
1389
    def get_a(self, t):
1390
        return t.get('a')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1391
1392
    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.
1393
        t = self.get_new_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1394
1395
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1396
        self.assertEqual('0123456789',
1397
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1398
                self.get_a, t, None).read())
1399
1400
    def test_one_redirection(self):
1401
        self.redirections = 0
1402
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.
1403
        def redirected(t, exception, redirection_notice):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1404
            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.
1405
            redirected_t = t._redirected_to(exception.source, exception.target)
1406
            return redirected_t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1407
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1408
        self.assertEqual('0123456789',
1409
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1410
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1411
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1412
1413
    def test_redirection_loop(self):
1414
1415
        def redirected(transport, exception, redirection_notice):
1416
            # By using the redirected url as a base dir for the
1417
            # *old* transport, we create a loop: a => a/a =>
1418
            # a/a/a
1419
            return self.old_transport.clone(exception.target)
1420
1421
        self.assertRaises(errors.TooManyRedirections,
1422
                          transport.do_catching_redirections,
1423
                          self.get_a, self.old_transport, redirected)
1424
1425
1426
class TestAuth(http_utils.TestCaseWithWebserver):
1427
    """Test authentication scheme"""
1428
5462.3.15 by Martin Pool
Turn variations into scenario lists
1429
    scenarios = multiply_scenarios(
1430
        vary_by_http_client_implementation(),
1431
        vary_by_http_protocol_version(),
1432
        vary_by_http_auth_scheme(),
1433
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1434
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1435
    _auth_header = 'Authorization'
1436
    _password_prompt_prefix = ''
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1437
    _username_prompt_prefix = ''
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1438
    # Set by load_tests
1439
    _auth_server = None
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1440
1441
    def setUp(self):
1442
        super(TestAuth, self).setUp()
1443
        self.server = self.get_readonly_server()
1444
        self.build_tree_contents([('a', 'contents of a\n'),
1445
                                  ('b', 'contents of b\n'),])
1446
1447
    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.
1448
        server = self._auth_server(protocol_version=self._protocol_version)
1449
        server._url_protocol = self._url_protocol
1450
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1451
1452
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1453
        # TODO: This is duplicated for lots of the classes in this file
1454
        return (features.pycurl.available()
1455
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1456
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1457
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1458
        """Build an url embedding user and password"""
1459
        url = '%s://' % self.server._url_protocol
1460
        if user is not None:
1461
            url += user
1462
            if password is not None:
1463
                url += ':' + password
1464
            url += '@'
1465
        url += '%s:%s/' % (self.server.host, self.server.port)
1466
        return url
1467
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1468
    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.
1469
        t = transport.get_transport(self.get_user_url(user, password))
1470
        return t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1471
1472
    def test_no_user(self):
1473
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1474
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1475
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1476
        # Only one 'Authentication Required' error should occur
1477
        self.assertEqual(1, self.server.auth_required_errors)
1478
1479
    def test_empty_pass(self):
1480
        self.server.add_user('joe', '')
1481
        t = self.get_user_transport('joe', '')
1482
        self.assertEqual('contents of a\n', t.get('a').read())
1483
        # Only one 'Authentication Required' error should occur
1484
        self.assertEqual(1, self.server.auth_required_errors)
1485
1486
    def test_user_pass(self):
1487
        self.server.add_user('joe', 'foo')
1488
        t = self.get_user_transport('joe', 'foo')
1489
        self.assertEqual('contents of a\n', t.get('a').read())
1490
        # Only one 'Authentication Required' error should occur
1491
        self.assertEqual(1, self.server.auth_required_errors)
1492
1493
    def test_unknown_user(self):
1494
        self.server.add_user('joe', 'foo')
1495
        t = self.get_user_transport('bill', 'foo')
1496
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1497
        # Two 'Authentication Required' errors should occur (the
1498
        # initial 'who are you' and 'I don't know you, who are
1499
        # you').
1500
        self.assertEqual(2, self.server.auth_required_errors)
1501
1502
    def test_wrong_pass(self):
1503
        self.server.add_user('joe', 'foo')
1504
        t = self.get_user_transport('joe', 'bar')
1505
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1506
        # Two 'Authentication Required' errors should occur (the
1507
        # initial 'who are you' and 'this is not you, who are you')
1508
        self.assertEqual(2, self.server.auth_required_errors)
1509
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1510
    def test_prompt_for_username(self):
1511
        if self._testing_pycurl():
1512
            raise tests.TestNotApplicable(
1513
                'pycurl cannot prompt, it handles auth by embedding'
1514
                ' user:pass in urls only')
1515
1516
        self.server.add_user('joe', 'foo')
1517
        t = self.get_user_transport(None, None)
1518
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1519
        stderr = tests.StringIOWrapper()
1520
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1521
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1522
        self.assertEqual('contents of a\n',t.get('a').read())
1523
        # stdin should be empty
1524
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1525
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1526
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1527
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1528
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1529
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1530
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1531
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1532
    def test_prompt_for_password(self):
1533
        if self._testing_pycurl():
1534
            raise tests.TestNotApplicable(
1535
                'pycurl cannot prompt, it handles auth by embedding'
1536
                ' user:pass in urls only')
1537
1538
        self.server.add_user('joe', 'foo')
1539
        t = self.get_user_transport('joe', None)
1540
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1541
        stderr = tests.StringIOWrapper()
1542
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1543
                                            stdout=stdout, stderr=stderr)
1544
        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.
1545
        # stdin should be empty
1546
        self.assertEqual('', ui.ui_factory.stdin.readline())
1547
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1548
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1549
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1550
        # And we shouldn't prompt again for a different request
1551
        # against the same transport.
1552
        self.assertEqual('contents of b\n',t.get('b').read())
1553
        t2 = t.clone()
1554
        # And neither against a clone
1555
        self.assertEqual('contents of b\n',t2.get('b').read())
1556
        # Only one 'Authentication Required' error should occur
1557
        self.assertEqual(1, self.server.auth_required_errors)
1558
1559
    def _check_password_prompt(self, scheme, user, actual_prompt):
1560
        expected_prompt = (self._password_prompt_prefix
1561
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1562
                              % (scheme.upper(),
1563
                                 user, self.server.host, self.server.port,
1564
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1565
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1566
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1567
    def _expected_username_prompt(self, scheme):
1568
        return (self._username_prompt_prefix
1569
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1570
                                 self.server.host, self.server.port,
1571
                                 self.server.auth_realm))
1572
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1573
    def test_no_prompt_for_password_when_using_auth_config(self):
1574
        if self._testing_pycurl():
1575
            raise tests.TestNotApplicable(
1576
                'pycurl does not support authentication.conf'
1577
                ' since it cannot prompt')
1578
1579
        user =' joe'
1580
        password = 'foo'
1581
        stdin_content = 'bar\n'  # Not the right password
1582
        self.server.add_user(user, password)
1583
        t = self.get_user_transport(user, None)
1584
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1585
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1586
        # Create a minimal config file with the right password
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1587
        _setup_authentication_config(
1588
            scheme='http', 
1589
            port=self.server.port,
1590
            user=user,
1591
            password=password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1592
        # Issue a request to the server to connect
1593
        self.assertEqual('contents of a\n',t.get('a').read())
1594
        # stdin should have  been left untouched
1595
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1596
        # Only one 'Authentication Required' error should occur
1597
        self.assertEqual(1, self.server.auth_required_errors)
1598
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1599
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1600
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1601
                                     http_utils.ProxyDigestAuthServer):
1602
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1603
        if self._testing_pycurl():
1604
            raise tests.KnownFailure(
1605
                'pycurl does not handle a nonce change')
1606
        self.server.add_user('joe', 'foo')
1607
        t = self.get_user_transport('joe', 'foo')
1608
        self.assertEqual('contents of a\n', t.get('a').read())
1609
        self.assertEqual('contents of b\n', t.get('b').read())
1610
        # Only one 'Authentication Required' error should have
1611
        # occured so far
1612
        self.assertEqual(1, self.server.auth_required_errors)
1613
        # The server invalidates the current nonce
1614
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1615
        self.assertEqual('contents of a\n', t.get('a').read())
1616
        # Two 'Authentication Required' errors should occur (the
1617
        # initial 'who are you' and a second 'who are you' with the new nonce)
1618
        self.assertEqual(2, self.server.auth_required_errors)
1619
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1620
    def test_user_from_auth_conf(self):
1621
        if self._testing_pycurl():
1622
            raise tests.TestNotApplicable(
1623
                'pycurl does not support authentication.conf')
1624
        user = 'joe'
1625
        password = 'foo'
1626
        self.server.add_user(user, password)
1627
        _setup_authentication_config(
1628
            scheme='http', 
1629
            port=self.server.port,
1630
            user=user,
1631
            password=password)
1632
        t = self.get_user_transport(None, None)
1633
        # Issue a request to the server to connect
1634
        self.assertEqual('contents of a\n', t.get('a').read())
1635
        # Only one 'Authentication Required' error should occur
1636
        self.assertEqual(1, self.server.auth_required_errors)
1637
1638
1639
def _setup_authentication_config(**kwargs):
1640
    conf = config.AuthenticationConfig()
1641
    conf._get_config().update({'httptest': kwargs})
1642
    conf._save()
1643
1644
1645
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1646
class TestUrllib2AuthHandler(tests.TestCaseWithTransport):
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1647
    """Unit tests for glue by which urllib2 asks us for authentication"""
1648
1649
    def test_get_user_password_without_port(self):
1650
        """We cope if urllib2 doesn't tell us the port.
1651
1652
        See https://bugs.launchpad.net/bzr/+bug/654684
1653
        """
1654
        user = 'joe'
1655
        password = 'foo'
1656
        _setup_authentication_config(
1657
            scheme='http', 
1658
            host='localhost',
1659
            user=user,
1660
            password=password)
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1661
        handler = _urllib2_wrappers.HTTPAuthHandler()
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1662
        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
1663
            user='joe',
5484.2.1 by Martin Pool
Add failing test for AbstractAuthHandler and bug 654684
1664
            protocol='http',
1665
            host='localhost',
1666
            path='/',
1667
            realm='Realm',
1668
            ))
5484.2.2 by Martin Pool
Cope gracefully if urllib2 doesn't tell us the port number in the authentication callback
1669
        self.assertEquals((user, password), got_pass)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1670
1671
1672
class TestProxyAuth(TestAuth):
1673
    """Test proxy authentication schemes."""
1674
5462.3.15 by Martin Pool
Turn variations into scenario lists
1675
    scenarios = multiply_scenarios(
1676
        vary_by_http_client_implementation(),
1677
        vary_by_http_protocol_version(),
1678
        vary_by_http_proxy_auth_scheme(),
1679
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1680
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1681
    _auth_header = 'Proxy-authorization'
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1682
    _password_prompt_prefix = 'Proxy '
1683
    _username_prompt_prefix = 'Proxy '
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1684
1685
    def setUp(self):
1686
        super(TestProxyAuth, self).setUp()
1687
        # Override the contents to avoid false positives
1688
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1689
                                  ('b', 'not proxied contents of b\n'),
1690
                                  ('a-proxied', 'contents of a\n'),
1691
                                  ('b-proxied', 'contents of b\n'),
1692
                                  ])
1693
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1694
    def get_user_transport(self, user, password):
5570.3.10 by Vincent Ladeuil
Rework the http tests with overrideEnv.
1695
        self.overrideEnv('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.
1696
        return TestAuth.get_user_transport(self, user, password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1697
1698
    def test_empty_pass(self):
1699
        if self._testing_pycurl():
1700
            import pycurl
1701
            if pycurl.version_info()[1] < '7.16.0':
1702
                raise tests.KnownFailure(
1703
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1704
        super(TestProxyAuth, self).test_empty_pass()
1705
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1706
1707
class SampleSocket(object):
1708
    """A socket-like object for use in testing the HTTP request handler."""
1709
1710
    def __init__(self, socket_read_content):
1711
        """Constructs a sample socket.
1712
1713
        :param socket_read_content: a byte sequence
1714
        """
1715
        # Use plain python StringIO so we can monkey-patch the close method to
1716
        # not discard the contents.
1717
        from StringIO import StringIO
1718
        self.readfile = StringIO(socket_read_content)
1719
        self.writefile = StringIO()
1720
        self.writefile.close = lambda: None
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
1721
        self.close = lambda: None
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1722
1723
    def makefile(self, mode='r', bufsize=None):
1724
        if 'r' in mode:
1725
            return self.readfile
1726
        else:
1727
            return self.writefile
1728
1729
1730
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1731
5462.3.15 by Martin Pool
Turn variations into scenario lists
1732
    scenarios = multiply_scenarios(
1733
        vary_by_http_client_implementation(), 
1734
        vary_by_http_protocol_version(),
1735
        )
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1736
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1737
    def setUp(self):
1738
        super(SmartHTTPTunnellingTest, self).setUp()
1739
        # We use the VFS layer as part of HTTP tunnelling tests.
5570.3.6 by Vincent Ladeuil
Get rid of all _captureVar() calls, no test failures, pfew.
1740
        self.overrideEnv('BZR_NO_SMART_VFS', None)
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1741
        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.
1742
        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.
1743
1744
    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.
1745
        server = http_utils.HTTPServerWithSmarts(
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1746
            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.
1747
        server._url_protocol = self._url_protocol
1748
        return server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1749
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1750
    def test_open_bzrdir(self):
1751
        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.
1752
        url = self.http_server.get_url() + 'relpath'
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1753
        bd = bzrdir.BzrDir.open(url)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
1754
        self.addCleanup(bd.transport.disconnect)
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1755
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1756
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1757
    def test_bulk_data(self):
1758
        # We should be able to send and receive bulk data in a single message.
1759
        # The 'readv' command in the smart protocol both sends and receives
1760
        # bulk data, so we use that.
1761
        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.
1762
        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.
1763
        medium = http_transport.get_smart_medium()
1764
        # Since we provide the medium, the url below will be mostly ignored
1765
        # during the test, as long as the path is '/'.
1766
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1767
                                                  medium=medium)
1768
        self.assertEqual(
1769
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1770
1771
    def test_http_send_smart_request(self):
1772
1773
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1774
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1775
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
        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.
1777
        medium = http_transport.get_smart_medium()
1778
        response = medium.send_http_smart_request(post_body)
1779
        reply_body = response.read()
1780
        self.assertEqual(expected_reply_body, reply_body)
1781
1782
    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.
1783
        httpd = self.http_server.server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1784
1785
        socket = SampleSocket(
1786
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1787
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1788
            # for 1.0)
1789
            + 'Content-Length: 6\r\n'
1790
            '\r\n'
1791
            'hello\n')
1792
        # Beware: the ('localhost', 80) below is the
1793
        # client_address parameter, but we don't have one because
1794
        # we have defined a socket which is not bound to an
1795
        # address. The test framework never uses this client
1796
        # address, so far...
1797
        request_handler = http_utils.SmartRequestHandler(socket,
1798
                                                         ('localhost', 80),
1799
                                                         httpd)
1800
        response = socket.writefile.getvalue()
1801
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1802
        # 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.
1803
        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.
1804
        self.assertEndsWith(response, expected_end_of_response)
1805
1806
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1807
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1808
    """No smart server here request handler."""
1809
1810
    def do_POST(self):
1811
        self.send_error(403, "Forbidden")
1812
1813
1814
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1815
    """Test smart client behaviour against an http server without smarts."""
1816
1817
    _req_handler_class = ForbiddenRequestHandler
1818
1819
    def test_probe_smart_server(self):
1820
        """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.
1821
        t = self.get_readonly_transport()
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1822
        # No need to build a valid smart request here, the server will not even
1823
        # try to interpret it.
1824
        self.assertRaises(errors.SmartProtocolError,
5599.3.6 by John Arbash Meinel
Revert the medium check, since it isn't necessary, and vila is worried about confusing people.
1825
                          t.get_smart_medium().send_http_smart_request,
1826
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1827
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
1828
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1829
class Test_redirected_to(tests.TestCase):
1830
5462.3.15 by Martin Pool
Turn variations into scenario lists
1831
    scenarios = vary_by_http_client_implementation()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
1832
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1833
    def test_redirected_to_subdir(self):
1834
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1835
        r = t._redirected_to('http://www.example.com/foo',
1836
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1837
        self.assertIsInstance(r, type(t))
1838
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1839
        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.
1840
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1841
    def test_redirected_to_self_with_slash(self):
1842
        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.
1843
        r = t._redirected_to('http://www.example.com/foo',
1844
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1845
        self.assertIsInstance(r, type(t))
1846
        # Both transports share the some connection (one can argue that we
1847
        # should return the exact same transport here, but that seems
1848
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1849
        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
1850
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1851
    def test_redirected_to_host(self):
1852
        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.
1853
        r = t._redirected_to('http://www.example.com/foo',
1854
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1855
        self.assertIsInstance(r, type(t))
1856
1857
    def test_redirected_to_same_host_sibling_protocol(self):
1858
        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.
1859
        r = t._redirected_to('http://www.example.com/foo',
1860
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1861
        self.assertIsInstance(r, type(t))
1862
1863
    def test_redirected_to_same_host_different_protocol(self):
1864
        t = self._transport('http://www.example.com/foo')
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
1865
        r = t._redirected_to('http://www.example.com/foo',
1866
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1867
        self.assertNotEquals(type(r), type(t))
1868
1869
    def test_redirected_to_different_host_same_user(self):
1870
        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.
1871
        r = t._redirected_to('http://www.example.com/foo',
1872
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1873
        self.assertIsInstance(r, type(t))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1874
        self.assertEqual(t._user, r._user)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1875
1876
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1877
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1878
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1879
1880
    The only thing we care about here is how many bytes travel on the wire. But
1881
    since we want to measure it for a real http client, we have to send it
1882
    correct responses.
1883
1884
    We expect to receive a *single* request nothing more (and we won't even
1885
    check what request it is, we just measure the bytes read until an empty
1886
    line.
1887
    """
1888
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
1889
    def _handle_one_request(self):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1890
        tcs = self.server.test_case_server
1891
        requestline = self.rfile.readline()
1892
        headers = self.MessageClass(self.rfile, 0)
1893
        # We just read: the request, the headers, an empty line indicating the
1894
        # end of the headers.
1895
        bytes_read = len(requestline)
1896
        for line in headers.headers:
1897
            bytes_read += len(line)
1898
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1899
        if requestline.startswith('POST'):
1900
            # The body should be a single line (or we don't know where it ends
1901
            # and we don't want to issue a blocking read)
1902
            body = self.rfile.readline()
1903
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1904
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1905
1906
        # We set the bytes written *before* issuing the write, the client is
1907
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
1908
1909
        # Doing the oppposite may lead to test failure: we may be interrupted
1910
        # after the write but before updating the value. The client can then
1911
        # continue and read the value *before* we can update it. And yes,
1912
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1913
        tcs.bytes_written = len(tcs.canned_response)
1914
        self.wfile.write(tcs.canned_response)
1915
1916
1917
class ActivityServerMixin(object):
1918
1919
    def __init__(self, protocol_version):
1920
        super(ActivityServerMixin, self).__init__(
1921
            request_handler=PredefinedRequestHandler,
1922
            protocol_version=protocol_version)
1923
        # Bytes read and written by the server
1924
        self.bytes_read = 0
1925
        self.bytes_written = 0
1926
        self.canned_response = None
1927
1928
1929
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1930
    pass
1931
1932
1933
if tests.HTTPSServerFeature.available():
1934
    from bzrlib.tests import https_server
1935
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1936
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1937
1938
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
1939
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1940
    """Test socket activity reporting.
1941
1942
    We use a special purpose server to control the bytes sent and received and
1943
    be able to predict the activity on the client socket.
1944
    """
1945
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1946
    def setUp(self):
1947
        tests.TestCase.setUp(self)
1948
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
1949
        self.server.start_server()
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1950
        self.activities = {}
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1951
        def report_activity(t, bytes, direction):
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1952
            count = self.activities.get(direction, 0)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1953
            count += bytes
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1954
            self.activities[direction] = count
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1955
1956
        # We override at class level because constructors may propagate the
1957
        # bound method and render instance overriding ineffective (an
4031.3.1 by Frank Aspell
Fixing various typos
1958
        # alternative would be to define a specific ui factory instead...)
4986.2.6 by Martin Pool
Clean up test_http setUp methods
1959
        self.overrideAttr(self._transport, '_report_activity', report_activity)
1960
        self.addCleanup(self.server.stop_server)
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1961
1962
    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.
1963
        t = self._transport(self.server.get_url())
1964
        # FIXME: Needs cleanup -- vila 20100611
1965
        return t
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1966
1967
    def assertActivitiesMatch(self):
1968
        self.assertEqual(self.server.bytes_read,
1969
                         self.activities.get('write', 0), 'written bytes')
1970
        self.assertEqual(self.server.bytes_written,
1971
                         self.activities.get('read', 0), 'read bytes')
1972
1973
    def test_get(self):
1974
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1975
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1976
Server: Apache/2.0.54 (Fedora)\r
1977
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1978
ETag: "56691-23-38e9ae00"\r
1979
Accept-Ranges: bytes\r
1980
Content-Length: 35\r
1981
Connection: close\r
1982
Content-Type: text/plain; charset=UTF-8\r
1983
\r
1984
Bazaar-NG meta directory, format 1
1985
'''
1986
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1987
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
1988
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1989
        self.assertActivitiesMatch()
1990
1991
    def test_has(self):
1992
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1993
Server: SimpleHTTP/0.6 Python/2.5.2\r
1994
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
1995
Content-type: application/octet-stream\r
1996
Content-Length: 20\r
1997
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
1998
\r
1999
'''
2000
        t = self.get_transport()
2001
        self.assertTrue(t.has('foo/bar'))
2002
        self.assertActivitiesMatch()
2003
2004
    def test_readv(self):
2005
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
2006
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
2007
Server: Apache/2.0.54 (Fedora)\r
2008
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
2009
ETag: "238a3c-16ec2-805c5540"\r
2010
Accept-Ranges: bytes\r
2011
Content-Length: 1534\r
2012
Connection: close\r
2013
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
2014
\r
2015
\r
2016
--418470f848b63279b\r
2017
Content-type: text/plain; charset=UTF-8\r
2018
Content-range: bytes 0-254/93890\r
2019
\r
2020
mbp@sourcefrog.net-20050309040815-13242001617e4a06
2021
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
2022
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
2023
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
2024
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
2025
\r
2026
--418470f848b63279b\r
2027
Content-type: text/plain; charset=UTF-8\r
2028
Content-range: bytes 1000-2049/93890\r
2029
\r
2030
40-fd4ec249b6b139ab
2031
mbp@sourcefrog.net-20050311063625-07858525021f270b
2032
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
2033
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
2034
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
2035
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
2036
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
2037
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2038
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2039
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2040
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2041
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2042
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2043
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2044
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2045
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2046
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2047
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2048
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2049
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2050
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2051
mbp@source\r
2052
--418470f848b63279b--\r
2053
'''
2054
        t = self.get_transport()
2055
        # Remember that the request is ignored and that the ranges below
2056
        # doesn't have to match the canned response.
2057
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2058
        self.assertEqual(2, len(l))
2059
        self.assertActivitiesMatch()
2060
2061
    def test_post(self):
2062
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2063
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2064
Server: Apache/2.0.54 (Fedora)\r
2065
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2066
ETag: "56691-23-38e9ae00"\r
2067
Accept-Ranges: bytes\r
2068
Content-Length: 35\r
2069
Connection: close\r
2070
Content-Type: text/plain; charset=UTF-8\r
2071
\r
2072
lalala whatever as long as itsssss
2073
'''
2074
        t = self.get_transport()
2075
        # 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.
2076
        # PredefinedRequestHandler._handle_one_request
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2077
        code, f = t._post('abc def end-of-body\n')
2078
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2079
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2080
2081
2082
class TestActivity(tests.TestCase, TestActivityMixin):
2083
5462.3.15 by Martin Pool
Turn variations into scenario lists
2084
    scenarios = multiply_scenarios(
2085
        vary_by_http_activity(),
2086
        vary_by_http_protocol_version(),
2087
        )
5462.3.11 by Martin Pool
Delete test_http.load_tests, and just specify variations per test
2088
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2089
    def setUp(self):
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2090
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2091
2092
2093
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2094
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2095
    # Unlike TestActivity, we are really testing ReportingFileSocket and
2096
    # ReportingSocket, so we don't need all the parametrization. Since
2097
    # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2098
    # test them through their use by the transport than directly (that's a
2099
    # bit less clean but far more simpler and effective).
2100
    _activity_server = ActivityHTTPServer
2101
    _protocol_version = 'HTTP/1.1'
2102
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2103
    def setUp(self):
4986.2.6 by Martin Pool
Clean up test_http setUp methods
2104
        self._transport =_urllib.HttpTransport_urllib
2105
        TestActivityMixin.setUp(self)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2106
2107
    def assertActivitiesMatch(self):
2108
        # Nothing to check here
2109
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2110
2111
2112
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2113
    """Test authentication on the redirected http server."""
2114
5462.3.15 by Martin Pool
Turn variations into scenario lists
2115
    scenarios = vary_by_http_protocol_version()
5462.3.9 by Martin Pool
List variations within the test classes, rather than in load_tests
2116
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2117
    _auth_header = 'Authorization'
2118
    _password_prompt_prefix = ''
2119
    _username_prompt_prefix = ''
2120
    _auth_server = http_utils.HTTPBasicAuthServer
2121
    _transport = _urllib.HttpTransport_urllib
2122
2123
    def setUp(self):
2124
        super(TestAuthOnRedirected, self).setUp()
2125
        self.build_tree_contents([('a','a'),
2126
                                  ('1/',),
2127
                                  ('1/a', 'redirected once'),
2128
                                  ],)
2129
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2130
                                       self.new_server.port)
2131
        self.old_server.redirections = [
2132
            ('(.*)', 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.
2133
        self.old_transport = self.get_old_transport()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2134
        self.new_server.add_user('joe', 'foo')
5247.2.26 by Vincent Ladeuil
Fix http redirection socket leaks.
2135
        cleanup_http_redirection_connections(self)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2136
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.
2137
    def create_transport_readonly_server(self):
2138
        server = self._auth_server(protocol_version=self._protocol_version)
2139
        server._url_protocol = self._url_protocol
2140
        return server
2141
2142
    def get_a(self, t):
2143
        return t.get('a')
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2144
2145
    def test_auth_on_redirected_via_do_catching_redirections(self):
2146
        self.redirections = 0
2147
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.
2148
        def redirected(t, exception, redirection_notice):
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2149
            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.
2150
            redirected_t = t._redirected_to(exception.source, exception.target)
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2151
            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.
2152
            return redirected_t
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2153
2154
        stdout = tests.StringIOWrapper()
2155
        stderr = tests.StringIOWrapper()
2156
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2157
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2158
        self.assertEqual('redirected once',
2159
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2160
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2161
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2162
        # stdin should be empty
2163
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2164
        # stdout should be empty, stderr will contains the prompts
2165
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2166
2167
    def test_auth_on_redirected_via_following_redirections(self):
2168
        self.new_server.add_user('joe', 'foo')
2169
        stdout = tests.StringIOWrapper()
2170
        stderr = tests.StringIOWrapper()
2171
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2172
                                            stdout=stdout, stderr=stderr)
2173
        t = self.old_transport
2174
        req = RedirectedRequest('GET', t.abspath('a'))
2175
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2176
                                       self.new_server.port)
2177
        self.old_server.redirections = [
2178
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
5247.2.28 by Vincent Ladeuil
Some more cleanups spotted on windows.
2179
        self.assertEqual('redirected once', t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2180
        # stdin should be empty
2181
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2182
        # stdout should be empty, stderr will contains the prompts
2183
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2184
2185