/brz/remove-bazaar

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