~bzr-pqm/bzr/bzr.dev

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