/brz/remove-bazaar

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