~bzr-pqm/bzr/bzr.dev

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