/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
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1340
class TestHTTPSilentRedirections(http_utils.TestCaseWithRedirectedWebserver):
1341
    """Test redirections.
1342
1343
    http implementations do not redirect silently anymore (they
1344
    do not redirect at all in fact). The mechanism is still in
1345
    place at the _urllib2_wrappers.Request level and these tests
1346
    exercise it.
1347
1348
    For the pycurl implementation
1349
    the redirection have been deleted as we may deprecate pycurl
1350
    and I have no place to keep a working implementation.
1351
    -- vila 20070212
1352
    """
1353
1354
    def setUp(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1355
        if (features.pycurl.available()
1356
            and self._transport == PyCurlTransport):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1357
            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.
1358
                "pycurl doesn't redirect silently anymore")
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1359
        super(TestHTTPSilentRedirections, self).setUp()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1360
        install_redirected_request(self)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1361
        self.build_tree_contents([('a','a'),
1362
                                  ('1/',),
1363
                                  ('1/a', 'redirected once'),
1364
                                  ('2/',),
1365
                                  ('2/a', 'redirected twice'),
1366
                                  ('3/',),
1367
                                  ('3/a', 'redirected thrice'),
1368
                                  ('4/',),
1369
                                  ('4/a', 'redirected 4 times'),
1370
                                  ('5/',),
1371
                                  ('5/a', 'redirected 5 times'),
1372
                                  ],)
1373
1374
    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.
1375
        t = self.get_old_transport()
1376
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1377
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1378
                                       self.new_server.port)
1379
        self.old_server.redirections = \
1380
            [('(.*)', 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.
1381
        self.assertEqual('redirected once', t._perform(req).read())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1382
1383
    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.
1384
        t = self.get_old_transport()
1385
        req = RedirectedRequest('GET', t._remote_path('a'))
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1386
        old_prefix = 'http://%s:%s' % (self.old_server.host,
1387
                                       self.old_server.port)
1388
        new_prefix = 'http://%s:%s' % (self.new_server.host,
1389
                                       self.new_server.port)
3111.1.20 by Vincent Ladeuil
Make all the test pass. Looks like we are HTTP/1.1 compliant.
1390
        self.old_server.redirections = [
1391
            ('/1(.*)', r'%s/2\1' % (old_prefix), 302),
1392
            ('/2(.*)', r'%s/3\1' % (old_prefix), 303),
1393
            ('/3(.*)', r'%s/4\1' % (old_prefix), 307),
1394
            ('/4(.*)', r'%s/5\1' % (new_prefix), 301),
1395
            ('(/[^/]+)', r'%s/1\1' % (old_prefix), 301),
1396
            ]
5247.3.29 by Vincent Ladeuil
Fix a bunch 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
        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.
1398
1399
1400
class TestDoCatchRedirections(http_utils.TestCaseWithRedirectedWebserver):
1401
    """Test transport.do_catching_redirections."""
1402
1403
    def setUp(self):
1404
        super(TestDoCatchRedirections, self).setUp()
1405
        self.build_tree_contents([('a', '0123456789'),],)
1406
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1407
        self.old_transport = self.get_old_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1408
5247.3.31 by Vincent Ladeuil
Cleanup some imports in http_utils.py.
1409
    def get_a(self, t):
1410
        return t.get('a')
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1411
1412
    def test_no_redirection(self):
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1413
        t = self.get_new_transport()
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1414
1415
        # We use None for redirected so that we fail if redirected
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1416
        self.assertEqual('0123456789',
1417
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1418
                self.get_a, t, None).read())
1419
1420
    def test_one_redirection(self):
1421
        self.redirections = 0
1422
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1423
        def redirected(t, exception, redirection_notice):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1424
            self.redirections += 1
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
1425
            redirected_t = t._redirected_to(exception.source, exception.target)
1426
            return redirected_t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1427
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1428
        self.assertEqual('0123456789',
1429
                         transport.do_catching_redirections(
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1430
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1431
        self.assertEqual(1, self.redirections)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1432
1433
    def test_redirection_loop(self):
1434
1435
        def redirected(transport, exception, redirection_notice):
1436
            # By using the redirected url as a base dir for the
1437
            # *old* transport, we create a loop: a => a/a =>
1438
            # a/a/a
1439
            return self.old_transport.clone(exception.target)
1440
1441
        self.assertRaises(errors.TooManyRedirections,
1442
                          transport.do_catching_redirections,
1443
                          self.get_a, self.old_transport, redirected)
1444
1445
1446
class TestAuth(http_utils.TestCaseWithWebserver):
1447
    """Test authentication scheme"""
1448
1449
    _auth_header = 'Authorization'
1450
    _password_prompt_prefix = ''
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1451
    _username_prompt_prefix = ''
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1452
    # Set by load_tests
1453
    _auth_server = None
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1454
1455
    def setUp(self):
1456
        super(TestAuth, self).setUp()
1457
        self.server = self.get_readonly_server()
1458
        self.build_tree_contents([('a', 'contents of a\n'),
1459
                                  ('b', 'contents of b\n'),])
1460
1461
    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.
1462
        server = self._auth_server(protocol_version=self._protocol_version)
1463
        server._url_protocol = self._url_protocol
1464
        return server
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1465
1466
    def _testing_pycurl(self):
4913.2.11 by John Arbash Meinel
Convert a bunch more features over to ModuleAvailableFeature
1467
        # TODO: This is duplicated for lots of the classes in this file
1468
        return (features.pycurl.available()
1469
                and self._transport == PyCurlTransport)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1470
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1471
    def get_user_url(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1472
        """Build an url embedding user and password"""
1473
        url = '%s://' % self.server._url_protocol
1474
        if user is not None:
1475
            url += user
1476
            if password is not None:
1477
                url += ':' + password
1478
            url += '@'
1479
        url += '%s:%s/' % (self.server.host, self.server.port)
1480
        return url
1481
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1482
    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.
1483
        t = transport.get_transport(self.get_user_url(user, password))
1484
        return t
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1485
1486
    def test_no_user(self):
1487
        self.server.add_user('joe', 'foo')
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1488
        t = self.get_user_transport(None, None)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1489
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1490
        # Only one 'Authentication Required' error should occur
1491
        self.assertEqual(1, self.server.auth_required_errors)
1492
1493
    def test_empty_pass(self):
1494
        self.server.add_user('joe', '')
1495
        t = self.get_user_transport('joe', '')
1496
        self.assertEqual('contents of a\n', t.get('a').read())
1497
        # Only one 'Authentication Required' error should occur
1498
        self.assertEqual(1, self.server.auth_required_errors)
1499
1500
    def test_user_pass(self):
1501
        self.server.add_user('joe', 'foo')
1502
        t = self.get_user_transport('joe', 'foo')
1503
        self.assertEqual('contents of a\n', t.get('a').read())
1504
        # Only one 'Authentication Required' error should occur
1505
        self.assertEqual(1, self.server.auth_required_errors)
1506
1507
    def test_unknown_user(self):
1508
        self.server.add_user('joe', 'foo')
1509
        t = self.get_user_transport('bill', 'foo')
1510
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1511
        # Two 'Authentication Required' errors should occur (the
1512
        # initial 'who are you' and 'I don't know you, who are
1513
        # you').
1514
        self.assertEqual(2, self.server.auth_required_errors)
1515
1516
    def test_wrong_pass(self):
1517
        self.server.add_user('joe', 'foo')
1518
        t = self.get_user_transport('joe', 'bar')
1519
        self.assertRaises(errors.InvalidHttpResponse, t.get, 'a')
1520
        # Two 'Authentication Required' errors should occur (the
1521
        # initial 'who are you' and 'this is not you, who are you')
1522
        self.assertEqual(2, self.server.auth_required_errors)
1523
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1524
    def test_prompt_for_username(self):
1525
        if self._testing_pycurl():
1526
            raise tests.TestNotApplicable(
1527
                'pycurl cannot prompt, it handles auth by embedding'
1528
                ' user:pass in urls only')
1529
1530
        self.server.add_user('joe', 'foo')
1531
        t = self.get_user_transport(None, None)
1532
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1533
        stderr = tests.StringIOWrapper()
1534
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
1535
                                            stdout=stdout, stderr=stderr)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1536
        self.assertEqual('contents of a\n',t.get('a').read())
1537
        # stdin should be empty
1538
        self.assertEqual('', ui.ui_factory.stdin.readline())
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1539
        stderr.seek(0)
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1540
        expected_prompt = self._expected_username_prompt(t._unqualified_scheme)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1541
        self.assertEqual(expected_prompt, stderr.read(len(expected_prompt)))
1542
        self.assertEqual('', stdout.getvalue())
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1543
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1544
                                    stderr.readline())
4284.1.2 by Vincent Ladeuil
Delete spurious space.
1545
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1546
    def test_prompt_for_password(self):
1547
        if self._testing_pycurl():
1548
            raise tests.TestNotApplicable(
1549
                'pycurl cannot prompt, it handles auth by embedding'
1550
                ' user:pass in urls only')
1551
1552
        self.server.add_user('joe', 'foo')
1553
        t = self.get_user_transport('joe', None)
1554
        stdout = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1555
        stderr = tests.StringIOWrapper()
1556
        ui.ui_factory = tests.TestUIFactory(stdin='foo\n',
1557
                                            stdout=stdout, stderr=stderr)
1558
        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.
1559
        # stdin should be empty
1560
        self.assertEqual('', ui.ui_factory.stdin.readline())
1561
        self._check_password_prompt(t._unqualified_scheme, 'joe',
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
1562
                                    stderr.getvalue())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1563
        self.assertEqual('', stdout.getvalue())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1564
        # And we shouldn't prompt again for a different request
1565
        # against the same transport.
1566
        self.assertEqual('contents of b\n',t.get('b').read())
1567
        t2 = t.clone()
1568
        # And neither against a clone
1569
        self.assertEqual('contents of b\n',t2.get('b').read())
1570
        # Only one 'Authentication Required' error should occur
1571
        self.assertEqual(1, self.server.auth_required_errors)
1572
1573
    def _check_password_prompt(self, scheme, user, actual_prompt):
1574
        expected_prompt = (self._password_prompt_prefix
1575
                           + ("%s %s@%s:%d, Realm: '%s' password: "
1576
                              % (scheme.upper(),
1577
                                 user, self.server.host, self.server.port,
1578
                                 self.server.auth_realm)))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1579
        self.assertEqual(expected_prompt, actual_prompt)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1580
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1581
    def _expected_username_prompt(self, scheme):
1582
        return (self._username_prompt_prefix
1583
                + "%s %s:%d, Realm: '%s' username: " % (scheme.upper(),
1584
                                 self.server.host, self.server.port,
1585
                                 self.server.auth_realm))
1586
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1587
    def test_no_prompt_for_password_when_using_auth_config(self):
1588
        if self._testing_pycurl():
1589
            raise tests.TestNotApplicable(
1590
                'pycurl does not support authentication.conf'
1591
                ' since it cannot prompt')
1592
1593
        user =' joe'
1594
        password = 'foo'
1595
        stdin_content = 'bar\n'  # Not the right password
1596
        self.server.add_user(user, password)
1597
        t = self.get_user_transport(user, None)
1598
        ui.ui_factory = tests.TestUIFactory(stdin=stdin_content,
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
1599
                                            stderr=tests.StringIOWrapper())
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1600
        # Create a minimal config file with the right password
1601
        conf = config.AuthenticationConfig()
1602
        conf._get_config().update(
1603
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1604
                          'user': user, 'password': password}})
1605
        conf._save()
1606
        # Issue a request to the server to connect
1607
        self.assertEqual('contents of a\n',t.get('a').read())
1608
        # stdin should have  been left untouched
1609
        self.assertEqual(stdin_content, ui.ui_factory.stdin.readline())
1610
        # Only one 'Authentication Required' error should occur
1611
        self.assertEqual(1, self.server.auth_required_errors)
1612
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1613
    def test_user_from_auth_conf(self):
1614
        if self._testing_pycurl():
1615
            raise tests.TestNotApplicable(
1616
                'pycurl does not support authentication.conf')
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1617
        user = 'joe'
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1618
        password = 'foo'
1619
        self.server.add_user(user, password)
1620
        # Create a minimal config file with the right password
1621
        conf = config.AuthenticationConfig()
1622
        conf._get_config().update(
1623
            {'httptest': {'scheme': 'http', 'port': self.server.port,
1624
                          'user': user, 'password': password}})
1625
        conf._save()
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1626
        t = self.get_user_transport(None, None)
3910.2.2 by Vincent Ladeuil
Fix bug #300347 by allowing querying authentication.conf if no
1627
        # Issue a request to the server to connect
3910.2.3 by Ben Jansen
Made tweaks requested by John Arbash Meinel.
1628
        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
1629
        # Only one 'Authentication Required' error should occur
1630
        self.assertEqual(1, self.server.auth_required_errors)
1631
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1632
    def test_changing_nonce(self):
4307.4.2 by Vincent Ladeuil
Handle servers proposing several authentication schemes.
1633
        if self._auth_server not in (http_utils.HTTPDigestAuthServer,
1634
                                     http_utils.ProxyDigestAuthServer):
1635
            raise tests.TestNotApplicable('HTTP/proxy auth digest only test')
3111.1.26 by Vincent Ladeuil
Re-add a test lost in refactoring.
1636
        if self._testing_pycurl():
1637
            raise tests.KnownFailure(
1638
                'pycurl does not handle a nonce change')
1639
        self.server.add_user('joe', 'foo')
1640
        t = self.get_user_transport('joe', 'foo')
1641
        self.assertEqual('contents of a\n', t.get('a').read())
1642
        self.assertEqual('contents of b\n', t.get('b').read())
1643
        # Only one 'Authentication Required' error should have
1644
        # occured so far
1645
        self.assertEqual(1, self.server.auth_required_errors)
1646
        # The server invalidates the current nonce
1647
        self.server.auth_nonce = self.server.auth_nonce + '. No, now!'
1648
        self.assertEqual('contents of a\n', t.get('a').read())
1649
        # Two 'Authentication Required' errors should occur (the
1650
        # initial 'who are you' and a second 'who are you' with the new nonce)
1651
        self.assertEqual(2, self.server.auth_required_errors)
1652
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1653
1654
1655
class TestProxyAuth(TestAuth):
1656
    """Test proxy authentication schemes."""
1657
1658
    _auth_header = 'Proxy-authorization'
4222.3.12 by Jelmer Vernooij
Check that the HTTP transport prompts for usernames.
1659
    _password_prompt_prefix = 'Proxy '
1660
    _username_prompt_prefix = 'Proxy '
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1661
1662
    def setUp(self):
1663
        super(TestProxyAuth, self).setUp()
1664
        self._old_env = {}
1665
        self.addCleanup(self._restore_env)
1666
        # Override the contents to avoid false positives
1667
        self.build_tree_contents([('a', 'not proxied contents of a\n'),
1668
                                  ('b', 'not proxied contents of b\n'),
1669
                                  ('a-proxied', 'contents of a\n'),
1670
                                  ('b-proxied', 'contents of b\n'),
1671
                                  ])
1672
3910.2.4 by Vincent Ladeuil
Fixed as per John's review.
1673
    def get_user_transport(self, user, password):
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1674
        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.
1675
        return TestAuth.get_user_transport(self, user, password)
3111.1.19 by Vincent Ladeuil
Merge back test_http_implementations.pc into test_http.py.
1676
1677
    def _install_env(self, env):
1678
        for name, value in env.iteritems():
1679
            self._old_env[name] = osutils.set_or_unset_env(name, value)
1680
1681
    def _restore_env(self):
1682
        for name, value in self._old_env.iteritems():
1683
            osutils.set_or_unset_env(name, value)
1684
1685
    def test_empty_pass(self):
1686
        if self._testing_pycurl():
1687
            import pycurl
1688
            if pycurl.version_info()[1] < '7.16.0':
1689
                raise tests.KnownFailure(
1690
                    'pycurl < 7.16.0 does not handle empty proxy passwords')
1691
        super(TestProxyAuth, self).test_empty_pass()
1692
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1693
1694
class SampleSocket(object):
1695
    """A socket-like object for use in testing the HTTP request handler."""
1696
1697
    def __init__(self, socket_read_content):
1698
        """Constructs a sample socket.
1699
1700
        :param socket_read_content: a byte sequence
1701
        """
1702
        # Use plain python StringIO so we can monkey-patch the close method to
1703
        # not discard the contents.
1704
        from StringIO import StringIO
1705
        self.readfile = StringIO(socket_read_content)
1706
        self.writefile = StringIO()
1707
        self.writefile.close = lambda: None
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
1708
        self.close = lambda: None
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1709
1710
    def makefile(self, mode='r', bufsize=None):
1711
        if 'r' in mode:
1712
            return self.readfile
1713
        else:
1714
            return self.writefile
1715
1716
1717
class SmartHTTPTunnellingTest(tests.TestCaseWithTransport):
1718
1719
    def setUp(self):
1720
        super(SmartHTTPTunnellingTest, self).setUp()
1721
        # We use the VFS layer as part of HTTP tunnelling tests.
1722
        self._captureVar('BZR_NO_SMART_VFS', None)
1723
        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.
1724
        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.
1725
1726
    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.
1727
        server = http_utils.HTTPServerWithSmarts(
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1728
            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.
1729
        server._url_protocol = self._url_protocol
1730
        return server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1731
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1732
    def test_open_bzrdir(self):
1733
        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.
1734
        url = self.http_server.get_url() + 'relpath'
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
1735
        bd = bzrdir.BzrDir.open(url)
1736
        self.assertIsInstance(bd, _mod_remote.RemoteBzrDir)
1737
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1738
    def test_bulk_data(self):
1739
        # We should be able to send and receive bulk data in a single message.
1740
        # The 'readv' command in the smart protocol both sends and receives
1741
        # bulk data, so we use that.
1742
        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.
1743
        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.
1744
        medium = http_transport.get_smart_medium()
1745
        # Since we provide the medium, the url below will be mostly ignored
1746
        # during the test, as long as the path is '/'.
1747
        remote_transport = remote.RemoteTransport('bzr://fake_host/',
1748
                                                  medium=medium)
1749
        self.assertEqual(
1750
            [(0, "c")], list(remote_transport.readv("data-file", [(0,1)])))
1751
1752
    def test_http_send_smart_request(self):
1753
1754
        post_body = 'hello\n'
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
1755
        expected_reply_body = 'ok\x012\n'
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1756
5247.3.29 by Vincent Ladeuil
Fix a bunch 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
        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.
1758
        medium = http_transport.get_smart_medium()
1759
        response = medium.send_http_smart_request(post_body)
1760
        reply_body = response.read()
1761
        self.assertEqual(expected_reply_body, reply_body)
1762
1763
    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.
1764
        httpd = self.http_server.server
3111.1.25 by Vincent Ladeuil
Fix the smart server failing test and use it against protocol combinations.
1765
1766
        socket = SampleSocket(
1767
            'POST /.bzr/smart %s \r\n' % self._protocol_version
1768
            # HTTP/1.1 posts must have a Content-Length (but it doesn't hurt
1769
            # for 1.0)
1770
            + 'Content-Length: 6\r\n'
1771
            '\r\n'
1772
            'hello\n')
1773
        # Beware: the ('localhost', 80) below is the
1774
        # client_address parameter, but we don't have one because
1775
        # we have defined a socket which is not bound to an
1776
        # address. The test framework never uses this client
1777
        # address, so far...
1778
        request_handler = http_utils.SmartRequestHandler(socket,
1779
                                                         ('localhost', 80),
1780
                                                         httpd)
1781
        response = socket.writefile.getvalue()
1782
        self.assertStartsWith(response, '%s 200 ' % self._protocol_version)
1783
        # 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.
1784
        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.
1785
        self.assertEndsWith(response, expected_end_of_response)
1786
1787
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1788
class ForbiddenRequestHandler(http_server.TestingHTTPRequestHandler):
1789
    """No smart server here request handler."""
1790
1791
    def do_POST(self):
1792
        self.send_error(403, "Forbidden")
1793
1794
1795
class SmartClientAgainstNotSmartServer(TestSpecificRequestHandler):
1796
    """Test smart client behaviour against an http server without smarts."""
1797
1798
    _req_handler_class = ForbiddenRequestHandler
1799
1800
    def test_probe_smart_server(self):
1801
        """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.
1802
        t = self.get_readonly_transport()
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1803
        # No need to build a valid smart request here, the server will not even
1804
        # try to interpret it.
1805
        self.assertRaises(errors.SmartProtocolError,
3734.3.1 by Vincent Ladeuil
Fix SmartHTTPMedium refactoring related test.
1806
                          t.get_smart_medium().send_http_smart_request,
1807
                          'whatever')
3430.3.4 by Vincent Ladeuil
Of course we can write tests !
1808
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
1809
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1810
class Test_redirected_to(tests.TestCase):
1811
1812
    def test_redirected_to_subdir(self):
1813
        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.
1814
        r = t._redirected_to('http://www.example.com/foo',
1815
                             'http://www.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1816
        self.assertIsInstance(r, type(t))
1817
        # Both transports share the some connection
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1818
        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.
1819
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1820
    def test_redirected_to_self_with_slash(self):
1821
        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.
1822
        r = t._redirected_to('http://www.example.com/foo',
1823
                             'http://www.example.com/foo/')
3878.4.3 by Vincent Ladeuil
Fix bug #303959 by returning a transport based on the same url
1824
        self.assertIsInstance(r, type(t))
1825
        # Both transports share the some connection (one can argue that we
1826
        # should return the exact same transport here, but that seems
1827
        # overkill).
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1828
        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
1829
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1830
    def test_redirected_to_host(self):
1831
        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.
1832
        r = t._redirected_to('http://www.example.com/foo',
1833
                             'http://foo.example.com/foo/subdir')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1834
        self.assertIsInstance(r, type(t))
1835
1836
    def test_redirected_to_same_host_sibling_protocol(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
                             'https://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1840
        self.assertIsInstance(r, type(t))
1841
1842
    def test_redirected_to_same_host_different_protocol(self):
1843
        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.
1844
        r = t._redirected_to('http://www.example.com/foo',
1845
                             'ftp://www.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1846
        self.assertNotEquals(type(r), type(t))
1847
1848
    def test_redirected_to_different_host_same_user(self):
1849
        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.
1850
        r = t._redirected_to('http://www.example.com/foo',
1851
                             'https://foo.example.com/foo')
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
1852
        self.assertIsInstance(r, type(t))
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
1853
        self.assertEqual(t._user, r._user)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1854
1855
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1856
class PredefinedRequestHandler(http_server.TestingHTTPRequestHandler):
1857
    """Request handler for a unique and pre-defined request.
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1858
1859
    The only thing we care about here is how many bytes travel on the wire. But
1860
    since we want to measure it for a real http client, we have to send it
1861
    correct responses.
1862
1863
    We expect to receive a *single* request nothing more (and we won't even
1864
    check what request it is, we just measure the bytes read until an empty
1865
    line.
1866
    """
1867
4731.2.3 by Vincent Ladeuil
Reduce the leaking http tests from ~200 to ~5.
1868
    def _handle_one_request(self):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1869
        tcs = self.server.test_case_server
1870
        requestline = self.rfile.readline()
1871
        headers = self.MessageClass(self.rfile, 0)
1872
        # We just read: the request, the headers, an empty line indicating the
1873
        # end of the headers.
1874
        bytes_read = len(requestline)
1875
        for line in headers.headers:
1876
            bytes_read += len(line)
1877
        bytes_read += len('\r\n')
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1878
        if requestline.startswith('POST'):
1879
            # The body should be a single line (or we don't know where it ends
1880
            # and we don't want to issue a blocking read)
1881
            body = self.rfile.readline()
1882
            bytes_read += len(body)
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1883
        tcs.bytes_read = bytes_read
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1884
1885
        # We set the bytes written *before* issuing the write, the client is
1886
        # supposed to consume every produced byte *before* checking that value.
3945.1.7 by Vincent Ladeuil
Test against https.
1887
1888
        # Doing the oppposite may lead to test failure: we may be interrupted
1889
        # after the write but before updating the value. The client can then
1890
        # continue and read the value *before* we can update it. And yes,
1891
        # this has been observed -- vila 20090129
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1892
        tcs.bytes_written = len(tcs.canned_response)
1893
        self.wfile.write(tcs.canned_response)
1894
1895
1896
class ActivityServerMixin(object):
1897
1898
    def __init__(self, protocol_version):
1899
        super(ActivityServerMixin, self).__init__(
1900
            request_handler=PredefinedRequestHandler,
1901
            protocol_version=protocol_version)
1902
        # Bytes read and written by the server
1903
        self.bytes_read = 0
1904
        self.bytes_written = 0
1905
        self.canned_response = None
1906
1907
1908
class ActivityHTTPServer(ActivityServerMixin, http_server.HttpServer):
1909
    pass
1910
1911
1912
if tests.HTTPSServerFeature.available():
1913
    from bzrlib.tests import https_server
1914
    class ActivityHTTPSServer(ActivityServerMixin, https_server.HTTPSServer):
1915
        pass
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1916
1917
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
1918
class TestActivityMixin(object):
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1919
    """Test socket activity reporting.
1920
1921
    We use a special purpose server to control the bytes sent and received and
1922
    be able to predict the activity on the client socket.
1923
    """
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1924
    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.
1925
        t = self._transport(self.server.get_url())
1926
        # FIXME: Needs cleanup -- vila 20100611
1927
        return t
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1928
1929
    def assertActivitiesMatch(self):
1930
        self.assertEqual(self.server.bytes_read,
1931
                         self.activities.get('write', 0), 'written bytes')
1932
        self.assertEqual(self.server.bytes_written,
1933
                         self.activities.get('read', 0), 'read bytes')
1934
1935
    def test_get(self):
1936
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1937
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
1938
Server: Apache/2.0.54 (Fedora)\r
1939
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
1940
ETag: "56691-23-38e9ae00"\r
1941
Accept-Ranges: bytes\r
1942
Content-Length: 35\r
1943
Connection: close\r
1944
Content-Type: text/plain; charset=UTF-8\r
1945
\r
1946
Bazaar-NG meta directory, format 1
1947
'''
1948
        t = self.get_transport()
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
1949
        self.assertEqual('Bazaar-NG meta directory, format 1\n',
1950
                         t.get('foo/bar').read())
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
1951
        self.assertActivitiesMatch()
1952
1953
    def test_has(self):
1954
        self.server.canned_response = '''HTTP/1.1 200 OK\r
1955
Server: SimpleHTTP/0.6 Python/2.5.2\r
1956
Date: Thu, 29 Jan 2009 20:21:47 GMT\r
1957
Content-type: application/octet-stream\r
1958
Content-Length: 20\r
1959
Last-Modified: Thu, 29 Jan 2009 20:21:47 GMT\r
1960
\r
1961
'''
1962
        t = self.get_transport()
1963
        self.assertTrue(t.has('foo/bar'))
1964
        self.assertActivitiesMatch()
1965
1966
    def test_readv(self):
1967
        self.server.canned_response = '''HTTP/1.1 206 Partial Content\r
1968
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
1969
Server: Apache/2.0.54 (Fedora)\r
1970
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
1971
ETag: "238a3c-16ec2-805c5540"\r
1972
Accept-Ranges: bytes\r
1973
Content-Length: 1534\r
1974
Connection: close\r
1975
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
1976
\r
1977
\r
1978
--418470f848b63279b\r
1979
Content-type: text/plain; charset=UTF-8\r
1980
Content-range: bytes 0-254/93890\r
1981
\r
1982
mbp@sourcefrog.net-20050309040815-13242001617e4a06
1983
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
1984
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
1985
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
1986
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
1987
\r
1988
--418470f848b63279b\r
1989
Content-type: text/plain; charset=UTF-8\r
1990
Content-range: bytes 1000-2049/93890\r
1991
\r
1992
40-fd4ec249b6b139ab
1993
mbp@sourcefrog.net-20050311063625-07858525021f270b
1994
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
1995
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
1996
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
1997
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
1998
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
1999
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
2000
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
2001
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
2002
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
2003
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
2004
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
2005
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
2006
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
2007
mbp@sourcefrog.net-20050313120651-497bd231b19df600
2008
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
2009
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
2010
mbp@sourcefrog.net-20050314025539-637a636692c055cf
2011
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
2012
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
2013
mbp@source\r
2014
--418470f848b63279b--\r
2015
'''
2016
        t = self.get_transport()
2017
        # Remember that the request is ignored and that the ranges below
2018
        # doesn't have to match the canned response.
2019
        l = list(t.readv('/foo/bar', ((0, 255), (1000, 1050))))
2020
        self.assertEqual(2, len(l))
2021
        self.assertActivitiesMatch()
2022
2023
    def test_post(self):
2024
        self.server.canned_response = '''HTTP/1.1 200 OK\r
2025
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
2026
Server: Apache/2.0.54 (Fedora)\r
2027
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
2028
ETag: "56691-23-38e9ae00"\r
2029
Accept-Ranges: bytes\r
2030
Content-Length: 35\r
2031
Connection: close\r
2032
Content-Type: text/plain; charset=UTF-8\r
2033
\r
2034
lalala whatever as long as itsssss
2035
'''
2036
        t = self.get_transport()
2037
        # 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.
2038
        # PredefinedRequestHandler._handle_one_request
3945.1.8 by Vincent Ladeuil
Add more tests, fix pycurl double handling, revert previous tracking.
2039
        code, f = t._post('abc def end-of-body\n')
2040
        self.assertEqual('lalala whatever as long as itsssss\n', f.read())
2041
        self.assertActivitiesMatch()
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2042
2043
2044
class TestActivity(tests.TestCase, TestActivityMixin):
2045
2046
    def setUp(self):
2047
        tests.TestCase.setUp(self)
2048
        self.server = self._activity_server(self._protocol_version)
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2049
        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.
2050
        self.addCleanup(self.server.stop_server)
2051
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2052
        self.activities = {}
2053
        def report_activity(t, bytes, direction):
2054
            count = self.activities.get(direction, 0)
2055
            count += bytes
2056
            self.activities[direction] = count
2057
        # We override at class level because constructors may propagate the
2058
        # bound method and render instance overriding ineffective (an
2059
        # 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.
2060
        self.overrideAttr(self._transport, '_report_activity', report_activity)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2061
2062
2063
class TestNoReportActivity(tests.TestCase, TestActivityMixin):
2064
2065
    def setUp(self):
2066
        tests.TestCase.setUp(self)
2067
        # Unlike TestActivity, we are really testing ReportingFileSocket and
2068
        # ReportingSocket, so we don't need all the parametrization. Since
2069
        # ReportingFileSocket and ReportingSocket are wrappers, it's easier to
2070
        # test them through their use by the transport than directly (that's a
2071
        # bit less clean but far more simpler and effective).
2072
        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.
2073
        self._transport = _urllib.HttpTransport_urllib
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2074
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
2075
        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.
2076
        self.addCleanup(self.server.stop_server)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2077
2078
        # We override at class level because constructors may propagate the
2079
        # bound method and render instance overriding ineffective (an
2080
        # 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.
2081
        self.overrideAttr(self._transport, '_report_activity', None)
4776.2.1 by Vincent Ladeuil
Support no activity report on http sockets.
2082
2083
    def assertActivitiesMatch(self):
2084
        # Nothing to check here
2085
        pass
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2086
2087
2088
class TestAuthOnRedirected(http_utils.TestCaseWithRedirectedWebserver):
2089
    """Test authentication on the redirected http server."""
2090
2091
    _auth_header = 'Authorization'
2092
    _password_prompt_prefix = ''
2093
    _username_prompt_prefix = ''
2094
    _auth_server = http_utils.HTTPBasicAuthServer
2095
    _transport = _urllib.HttpTransport_urllib
2096
2097
    def setUp(self):
2098
        super(TestAuthOnRedirected, self).setUp()
2099
        self.build_tree_contents([('a','a'),
2100
                                  ('1/',),
2101
                                  ('1/a', 'redirected once'),
2102
                                  ],)
2103
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2104
                                       self.new_server.port)
2105
        self.old_server.redirections = [
2106
            ('(.*)', 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.
2107
        self.old_transport = self.get_old_transport()
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2108
        self.new_server.add_user('joe', 'foo')
2109
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2110
    def create_transport_readonly_server(self):
2111
        server = self._auth_server(protocol_version=self._protocol_version)
2112
        server._url_protocol = self._url_protocol
2113
        return server
2114
2115
    def get_a(self, t):
2116
        return t.get('a')
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2117
2118
    def test_auth_on_redirected_via_do_catching_redirections(self):
2119
        self.redirections = 0
2120
5247.3.29 by Vincent Ladeuil
Fix a bunch of tests that were building transport objects explicitely instead of relying on self.get_transport() leading to many wrong http implementation objects being tested.
2121
        def redirected(t, exception, redirection_notice):
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2122
            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.
2123
            redirected_t = t._redirected_to(exception.source, exception.target)
2124
            return redirected_t
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2125
2126
        stdout = tests.StringIOWrapper()
2127
        stderr = tests.StringIOWrapper()
2128
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2129
                                            stdout=stdout, stderr=stderr)
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2130
        self.assertEqual('redirected once',
2131
                         transport.do_catching_redirections(
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2132
                self.get_a, self.old_transport, redirected).read())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2133
        self.assertEqual(1, self.redirections)
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2134
        # stdin should be empty
2135
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2136
        # stdout should be empty, stderr will contains the prompts
2137
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2138
2139
    def test_auth_on_redirected_via_following_redirections(self):
2140
        self.new_server.add_user('joe', 'foo')
2141
        stdout = tests.StringIOWrapper()
2142
        stderr = tests.StringIOWrapper()
2143
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n',
2144
                                            stdout=stdout, stderr=stderr)
2145
        t = self.old_transport
2146
        req = RedirectedRequest('GET', t.abspath('a'))
2147
        new_prefix = 'http://%s:%s' % (self.new_server.host,
2148
                                       self.new_server.port)
2149
        self.old_server.redirections = [
2150
            ('(.*)', r'%s/1\1' % (new_prefix), 301),]
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2151
        self.assertEqual('redirected once',t._perform(req).read())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2152
        # stdin should be empty
2153
        self.assertEqual('', ui.ui_factory.stdin.readline())
4795.4.6 by Vincent Ladeuil
Fixed as per John's review.
2154
        # stdout should be empty, stderr will contains the prompts
2155
        self.assertEqual('', stdout.getvalue())
4795.4.5 by Vincent Ladeuil
Make sure all redirection code paths can handle authentication.
2156
2157