/brz/remove-bazaar

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