/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1
# Copyright (C) 2006-2010, 2012, 2013, 2016 Canonical Ltd
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
2
#
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.
7
#
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.
12
#
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
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
16
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
17
"""Tests from HTTP response parsing.
18
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
19
The handle_response method read the response body of a GET request an returns
20
the corresponding RangeFile.
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
21
22
There are four different kinds of RangeFile:
23
- a whole file whose size is unknown, seen as a simple byte stream,
24
- a whole file whose size is known, we can't read past its end,
25
- a single range file, a part of a file with a start and a size,
26
- a multiple range file, several consecutive parts with known start offset
27
  and size.
28
29
Some properties are common to all kinds:
30
- seek can only be forward (its really a socket underneath),
31
- read can't cross ranges,
32
- successive ranges are taken into account transparently,
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
33
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
34
- the expected pattern of use is either seek(offset)+read(size) or a single
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
35
  read with no size specified. For multiple range files, multiple read() will
36
  return the corresponding ranges, trying to read further will raise
37
  InvalidHttpResponse.
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
38
"""
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
39
6791.2.3 by Jelmer Vernooij
Fix more imports.
40
try:
41
    import http.client as http_client
7295.1.1 by Matthew Fuller
Fix with py2.7 + future
42
except ImportError:  # python < 3 without future
43
    import httplib as http_client
44
45
try:
7067.8.2 by Jelmer Vernooij
Fix some http response tests.
46
    parse_headers = http_client.parse_headers
7295.1.1 by Matthew Fuller
Fix with py2.7 + future
47
except AttributeError:  # python 2
7067.8.2 by Jelmer Vernooij
Fix some http response tests.
48
    parse_headers = http_client.HTTPMessage
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
49
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
50
from .. import (
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
51
    errors,
52
    tests,
53
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
54
from ..sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
55
    BytesIO,
7296.2.9 by Jelmer Vernooij
Fix python3 compatibility.
56
    PY3,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
57
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
58
from ..transport.http import (
3104.3.4 by Vincent Ladeuil
Add test.
59
    response,
7296.2.1 by Jelmer Vernooij
Integrate _urllib2_wrappers.
60
    HTTPConnection,
3104.3.4 by Vincent Ladeuil
Add test.
61
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
62
from .file_utils import (
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
63
    FakeReadFile,
64
    )
3104.3.4 by Vincent Ladeuil
Add test.
65
66
67
class ReadSocket(object):
68
    """A socket-like object that can be given a predefined content."""
69
70
    def __init__(self, data):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
71
        self.readfile = BytesIO(data)
3104.3.4 by Vincent Ladeuil
Add test.
72
73
    def makefile(self, mode='r', bufsize=None):
74
        return self.readfile
75
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
76
7296.2.1 by Jelmer Vernooij
Integrate _urllib2_wrappers.
77
class FakeHTTPConnection(HTTPConnection):
3104.3.4 by Vincent Ladeuil
Add test.
78
79
    def __init__(self, sock):
7296.2.1 by Jelmer Vernooij
Integrate _urllib2_wrappers.
80
        HTTPConnection.__init__(self, 'localhost')
3104.3.4 by Vincent Ladeuil
Add test.
81
        # Set the socket to bypass the connection
82
        self.sock = sock
83
84
    def send(self, str):
85
        """Ignores the writes on the socket."""
86
        pass
87
88
6575.1.2 by Vincent Ladeuil
TDD backwards, works here ;)
89
class TestResponseFileIter(tests.TestCase):
90
91
    def test_iter_empty(self):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
92
        f = response.ResponseFile('empty', BytesIO())
6575.1.3 by Vincent Ladeuil
Simpler.
93
        self.assertEqual([], list(f))
6575.1.2 by Vincent Ladeuil
TDD backwards, works here ;)
94
95
    def test_iter_many(self):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
96
        f = response.ResponseFile('many', BytesIO(b'0\n1\nboo!\n'))
6973.11.6 by Jelmer Vernooij
Fix more http tests.
97
        self.assertEqual([b'0\n', b'1\n', b'boo!\n'], list(f))
6575.1.2 by Vincent Ladeuil
TDD backwards, works here ;)
98
99
3104.3.4 by Vincent Ladeuil
Add test.
100
class TestHTTPConnection(tests.TestCase):
101
102
    def test_cleanup_pipe(self):
6973.11.6 by Jelmer Vernooij
Fix more http tests.
103
        sock = ReadSocket(b"""HTTP/1.1 200 OK\r
3104.3.4 by Vincent Ladeuil
Add test.
104
Content-Type: text/plain; charset=UTF-8\r
105
Content-Length: 18
106
\r
107
0123456789
108
garbage""")
109
        conn = FakeHTTPConnection(sock)
110
        # Simulate the request sending so that the connection will be able to
111
        # read the response.
112
        conn.putrequest('GET', 'http://localhost/fictious')
113
        conn.endheaders()
114
        # Now, get the response
115
        resp = conn.getresponse()
116
        # Read part of the response
6973.11.6 by Jelmer Vernooij
Fix more http tests.
117
        self.assertEqual(b'0123456789\n', resp.read(11))
3104.3.4 by Vincent Ladeuil
Add test.
118
        # Override the thresold to force the warning emission
7143.15.2 by Jelmer Vernooij
Run autopep8.
119
        conn._range_warning_thresold = 6  # There are 7 bytes pending
3104.3.4 by Vincent Ladeuil
Add test.
120
        conn.cleanup_pipe()
4794.1.15 by Robert Collins
Review feedback.
121
        self.assertContainsRe(self.get_log(), 'Got a 200 response when asking')
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
122
123
124
class TestRangeFileMixin(object):
125
    """Tests for accessing the first range in a RangeFile."""
126
127
    # A simple string used to represent a file part (also called a range), in
128
    # which offsets are easy to calculate for test writers. It's used as a
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
129
    # building block with slight variations but basically 'a' is the first char
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
130
    # of the range and 'z' is the last.
6973.11.6 by Jelmer Vernooij
Fix more http tests.
131
    alpha = b'abcdefghijklmnopqrstuvwxyz'
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
132
133
    def test_can_read_at_first_access(self):
134
        """Test that the just created file can be read."""
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
135
        self.assertEqual(self.alpha, self._file.read())
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
136
137
    def test_seek_read(self):
138
        """Test seek/read inside the range."""
139
        f = self._file
140
        start = self.first_range_start
141
        # Before any use, tell() should be at the range start
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
142
        self.assertEqual(start, f.tell())
7143.15.2 by Jelmer Vernooij
Run autopep8.
143
        cur = start  # For an overall offset assertion
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
144
        f.seek(start + 3)
145
        cur += 3
6973.11.6 by Jelmer Vernooij
Fix more http tests.
146
        self.assertEqual(b'def', f.read(3))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
147
        cur += len('def')
148
        f.seek(4, 1)
149
        cur += 4
6973.11.6 by Jelmer Vernooij
Fix more http tests.
150
        self.assertEqual(b'klmn', f.read(4))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
151
        cur += len('klmn')
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
152
        # read(0) in the middle of a range
6973.11.6 by Jelmer Vernooij
Fix more http tests.
153
        self.assertEqual(b'', f.read(0))
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
154
        # seek in place
155
        here = f.tell()
156
        f.seek(0, 1)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
157
        self.assertEqual(here, f.tell())
158
        self.assertEqual(cur, f.tell())
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
159
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
160
    def test_read_zero(self):
161
        f = self._file
6973.11.6 by Jelmer Vernooij
Fix more http tests.
162
        self.assertEqual(b'', f.read(0))
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
163
        f.seek(10, 1)
6973.11.6 by Jelmer Vernooij
Fix more http tests.
164
        self.assertEqual(b'', f.read(0))
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
165
166
    def test_seek_at_range_end(self):
167
        f = self._file
168
        f.seek(26, 1)
169
170
    def test_read_at_range_end(self):
171
        """Test read behaviour at range end."""
172
        f = self._file
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
173
        self.assertEqual(self.alpha, f.read())
6973.11.6 by Jelmer Vernooij
Fix more http tests.
174
        self.assertEqual(b'', f.read(0))
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
175
        self.assertRaises(errors.InvalidRange, f.read, 1)
176
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
177
    def test_unbounded_read_after_seek(self):
178
        f = self._file
179
        f.seek(24, 1)
180
        # Should not cross ranges
6973.11.6 by Jelmer Vernooij
Fix more http tests.
181
        self.assertEqual(b'yz', f.read())
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
182
183
    def test_seek_backwards(self):
184
        f = self._file
185
        start = self.first_range_start
186
        f.seek(start)
187
        f.read(12)
188
        self.assertRaises(errors.InvalidRange, f.seek, start + 5)
189
190
    def test_seek_outside_single_range(self):
191
        f = self._file
192
        if f._size == -1 or f._boundary is not None:
193
            raise tests.TestNotApplicable('Needs a fully defined range')
194
        # Will seek past the range and then errors out
195
        self.assertRaises(errors.InvalidRange,
196
                          f.seek, self.first_range_start + 27)
197
198
    def test_read_past_end_of_range(self):
199
        f = self._file
200
        if f._size == -1:
201
            raise tests.TestNotApplicable("Can't check an unknown size")
202
        start = self.first_range_start
203
        f.seek(start + 20)
204
        self.assertRaises(errors.InvalidRange, f.read, 10)
205
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
206
    def test_seek_from_end(self):
7143.15.2 by Jelmer Vernooij
Run autopep8.
207
        """Test seeking from the end of the file.
208
209
        The semantic is unclear in case of multiple ranges. Seeking from end
210
        exists only for the http transports, cannot be used if the file size is
211
        unknown and is not used in breezy itself. This test must be (and is)
212
        overridden by daughter classes.
213
214
        Reading from end makes sense only when a range has been requested from
215
        the end of the file (see HttpTransportBase._get() when using the
216
        'tail_amount' parameter). The HTTP response can only be a whole file or
217
        a single range.
218
        """
219
        f = self._file
220
        f.seek(-2, 2)
221
        self.assertEqual(b'yz', f.read())
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
222
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
223
224
class TestRangeFileSizeUnknown(tests.TestCase, TestRangeFileMixin):
225
    """Test a RangeFile for a whole file whose size is not known."""
226
227
    def setUp(self):
228
        super(TestRangeFileSizeUnknown, self).setUp()
229
        self._file = response.RangeFile('Whole_file_size_known',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
230
                                        BytesIO(self.alpha))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
231
        # We define no range, relying on RangeFile to provide default values
7143.15.2 by Jelmer Vernooij
Run autopep8.
232
        self.first_range_start = 0  # It's the whole file
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
233
234
    def test_seek_from_end(self):
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
235
        """See TestRangeFileMixin.test_seek_from_end.
236
237
        The end of the file can't be determined since the size is unknown.
238
        """
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
239
        self.assertRaises(errors.InvalidRange, self._file.seek, -1, 2)
240
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
241
    def test_read_at_range_end(self):
242
        """Test read behaviour at range end."""
243
        f = self._file
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
244
        self.assertEqual(self.alpha, f.read())
6973.11.6 by Jelmer Vernooij
Fix more http tests.
245
        self.assertEqual(b'', f.read(0))
246
        self.assertEqual(b'', f.read(1))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
247
3537.1.1 by Vincent Ladeuil
Fix some more PEP8isms and delete useless import
248
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
249
class TestRangeFileSizeKnown(tests.TestCase, TestRangeFileMixin):
250
    """Test a RangeFile for a whole file whose size is known."""
251
252
    def setUp(self):
253
        super(TestRangeFileSizeKnown, self).setUp()
254
        self._file = response.RangeFile('Whole_file_size_known',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
255
                                        BytesIO(self.alpha))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
256
        self._file.set_range(0, len(self.alpha))
7143.15.2 by Jelmer Vernooij
Run autopep8.
257
        self.first_range_start = 0  # It's the whole file
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
258
259
260
class TestRangeFileSingleRange(tests.TestCase, TestRangeFileMixin):
261
    """Test a RangeFile for a single range."""
262
263
    def setUp(self):
264
        super(TestRangeFileSingleRange, self).setUp()
265
        self._file = response.RangeFile('Single_range_file',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
266
                                        BytesIO(self.alpha))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
267
        self.first_range_start = 15
268
        self._file.set_range(self.first_range_start, len(self.alpha))
269
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
270
    def test_read_before_range(self):
271
        # This can't occur under normal circumstances, we have to force it
272
        f = self._file
7143.15.2 by Jelmer Vernooij
Run autopep8.
273
        f._pos = 0  # Force an invalid pos
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
274
        self.assertRaises(errors.InvalidRange, f.read, 2)
275
3537.1.1 by Vincent Ladeuil
Fix some more PEP8isms and delete useless import
276
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
277
class TestRangeFileMultipleRanges(tests.TestCase, TestRangeFileMixin):
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
278
    """Test a RangeFile for multiple ranges.
279
280
    The RangeFile used for the tests contains three ranges:
281
282
    - at offset 25: alpha
283
    - at offset 100: alpha
284
    - at offset 126: alpha.upper()
285
286
    The two last ranges are contiguous. This only rarely occurs (should not in
287
    fact) in real uses but may lead to hard to track bugs.
288
    """
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
289
290
    # The following is used to represent the boundary paramter defined
291
    # in HTTP response headers and the boundary lines that separate
292
    # multipart content.
293
6973.11.6 by Jelmer Vernooij
Fix more http tests.
294
    boundary = b"separation"
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
295
296
    def setUp(self):
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
297
        super(TestRangeFileMultipleRanges, self).setUp()
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
298
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
299
        boundary = self.boundary
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
300
6973.11.6 by Jelmer Vernooij
Fix more http tests.
301
        content = b''
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
302
        self.first_range_start = 25
7143.15.2 by Jelmer Vernooij
Run autopep8.
303
        file_size = 200  # big enough to encompass all ranges
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
304
        for (start, part) in [(self.first_range_start, self.alpha),
305
                              # Two contiguous ranges
306
                              (100, self.alpha),
307
                              (126, self.alpha.upper())]:
308
            content += self._multipart_byterange(part, start, boundary,
309
                                                 file_size)
310
        # Final boundary
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
311
        content += self._boundary_line()
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
312
313
        self._file = response.RangeFile('Multiple_ranges_file',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
314
                                        BytesIO(content))
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
315
        self.set_file_boundary()
316
317
    def _boundary_line(self):
318
        """Helper to build the formatted boundary line."""
6973.11.6 by Jelmer Vernooij
Fix more http tests.
319
        return b'--' + self.boundary + b'\r\n'
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
320
321
    def set_file_boundary(self):
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
322
        # Ranges are set by decoding the range headers, the RangeFile user is
323
        # supposed to call the following before using seek or read since it
324
        # requires knowing the *response* headers (in that case the boundary
325
        # which is part of the Content-Type header).
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
326
        self._file.set_boundary(self.boundary)
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
327
6973.11.6 by Jelmer Vernooij
Fix more http tests.
328
    def _multipart_byterange(self, data, offset, boundary, file_size=b'*'):
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
329
        """Encode a part of a file as a multipart/byterange MIME type.
330
331
        When a range request is issued, the HTTP response body can be
332
        decomposed in parts, each one representing a range (start, size) in a
333
        file.
334
335
        :param data: The payload.
336
        :param offset: where data starts in the file
337
        :param boundary: used to separate the parts
338
        :param file_size: the size of the file containing the range (default to
339
            '*' meaning unknown)
340
341
        :return: a string containing the data encoded as it will appear in the
342
            HTTP response body.
343
        """
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
344
        bline = self._boundary_line()
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
345
        # Each range begins with a boundary line
346
        range = bline
347
        # A range is described by a set of headers, but only 'Content-Range' is
348
        # required for our implementation (TestHandleResponse below will
349
        # exercise ranges with multiple or missing headers')
6973.11.6 by Jelmer Vernooij
Fix more http tests.
350
        if isinstance(file_size, int):
351
            file_size = b'%d' % file_size
352
        range += b'Content-Range: bytes %d-%d/%s\r\n' % (offset,
7143.15.2 by Jelmer Vernooij
Run autopep8.
353
                                                         offset +
354
                                                         len(data) - 1,
6973.11.6 by Jelmer Vernooij
Fix more http tests.
355
                                                         file_size)
356
        range += b'\r\n'
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
357
        # Finally the raw bytes
358
        range += data
359
        return range
360
361
    def test_read_all_ranges(self):
362
        f = self._file
7143.15.2 by Jelmer Vernooij
Run autopep8.
363
        self.assertEqual(self.alpha, f.read())  # Read first range
364
        f.seek(100)  # Trigger the second range recognition
365
        self.assertEqual(self.alpha, f.read())  # Read second range
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
366
        self.assertEqual(126, f.tell())
7143.15.2 by Jelmer Vernooij
Run autopep8.
367
        f.seek(126)  # Start of third range which is also the current pos !
6973.11.6 by Jelmer Vernooij
Fix more http tests.
368
        self.assertEqual(b'A', f.read(1))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
369
        f.seek(10, 1)
6973.11.6 by Jelmer Vernooij
Fix more http tests.
370
        self.assertEqual(b'LMN', f.read(3))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
371
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
372
    def test_seek_from_end(self):
373
        """See TestRangeFileMixin.test_seek_from_end."""
374
        # The actual implementation will seek from end for the first range only
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
375
        # and then fail. Since seeking from end is intended to be used for a
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
376
        # single range only anyway, this test just document the actual
377
        # behaviour.
378
        f = self._file
379
        f.seek(-2, 2)
6973.11.6 by Jelmer Vernooij
Fix more http tests.
380
        self.assertEqual(b'yz', f.read())
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
381
        self.assertRaises(errors.InvalidRange, f.seek, -2, 2)
382
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
383
    def test_seek_into_void(self):
384
        f = self._file
385
        start = self.first_range_start
386
        f.seek(start)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
387
        # Seeking to a point between two ranges is possible (only once) but
388
        # reading there is forbidden
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
389
        f.seek(start + 40)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
390
        # We crossed a range boundary, so now the file is positioned at the
391
        # start of the new range (i.e. trying to seek below 100 will error out)
392
        f.seek(100)
3059.2.7 by Vincent Ladeuil
Allow pycurl users to watch the blinkenlights and fix a bug when ranges are contiguous.
393
        f.seek(125)
394
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
395
    def test_seek_across_ranges(self):
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
396
        f = self._file
7143.15.2 by Jelmer Vernooij
Run autopep8.
397
        f.seek(126)  # skip the two first ranges
6973.11.6 by Jelmer Vernooij
Fix more http tests.
398
        self.assertEqual(b'AB', f.read(2))
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
399
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
400
    def test_checked_read_dont_overflow_buffers(self):
401
        f = self._file
402
        # We force a very low value to exercise all code paths in _checked_read
403
        f._discarded_buf_size = 8
7143.15.2 by Jelmer Vernooij
Run autopep8.
404
        f.seek(126)  # skip the two first ranges
6973.11.6 by Jelmer Vernooij
Fix more http tests.
405
        self.assertEqual(b'AB', f.read(2))
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
406
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
407
    def test_seek_twice_between_ranges(self):
408
        f = self._file
409
        start = self.first_range_start
7143.15.2 by Jelmer Vernooij
Run autopep8.
410
        f.seek(start + 40)  # Past the first range but before the second
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
411
        # Now the file is positioned at the second range start (100)
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
412
        self.assertRaises(errors.InvalidRange, f.seek, start + 41)
413
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
414
    def test_seek_at_range_end(self):
415
        """Test seek behavior at range end."""
416
        f = self._file
417
        f.seek(25 + 25)
418
        f.seek(100 + 25)
419
        f.seek(126 + 25)
420
421
    def test_read_at_range_end(self):
422
        f = self._file
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
423
        self.assertEqual(self.alpha, f.read())
424
        self.assertEqual(self.alpha, f.read())
425
        self.assertEqual(self.alpha.upper(), f.read())
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
426
        self.assertRaises(errors.InvalidHttpResponse, f.read, 1)
427
3537.1.1 by Vincent Ladeuil
Fix some more PEP8isms and delete useless import
428
3535.1.1 by Adrian Wilkins
Made the behaviour of the existing multi-range test more like the real thing by
429
class TestRangeFileMultipleRangesQuotedBoundaries(TestRangeFileMultipleRanges):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
430
    """Perform the same tests as TestRangeFileMultipleRanges, but uses
3535.1.1 by Adrian Wilkins
Made the behaviour of the existing multi-range test more like the real thing by
431
    an angle-bracket quoted boundary string like IIS 6.0 and 7.0
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
432
    (but not IIS 5, which breaks the RFC in a different way
433
    by using square brackets, not angle brackets)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
434
435
    This reveals a bug caused by
436
437
    - The bad implementation of RFC 822 unquoting in Python (angles are not
438
      quotes), coupled with
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
439
440
    - The bad implementation of RFC 2046 in IIS (angles are not permitted chars
441
      in boundary lines).
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
442
3535.1.1 by Adrian Wilkins
Made the behaviour of the existing multi-range test more like the real thing by
443
    """
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
444
    # The boundary as it appears in boundary lines
445
    # IIS 6 and 7 use this value
6973.11.6 by Jelmer Vernooij
Fix more http tests.
446
    _boundary_trimmed = b"q1w2e3r4t5y6u7i8o9p0zaxscdvfbgnhmjklkl"
447
    boundary = b'<' + _boundary_trimmed + b'>'
3535.1.4 by adwi2
Changes as suggested by Mr Ladeuil.
448
449
    def set_file_boundary(self):
450
        # Emulate broken rfc822.unquote() here by removing angles
451
        self._file.set_boundary(self._boundary_trimmed)
3537.1.1 by Vincent Ladeuil
Fix some more PEP8isms and delete useless import
452
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
453
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
454
class TestRangeFileVarious(tests.TestCase):
455
    """Tests RangeFile aspects not covered elsewhere."""
456
457
    def test_seek_whence(self):
458
        """Test the seek whence parameter values."""
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
459
        f = response.RangeFile('foo', BytesIO(b'abc'))
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
460
        f.set_range(0, 3)
461
        f.seek(0)
462
        f.seek(1, 1)
463
        f.seek(-1, 2)
464
        self.assertRaises(ValueError, f.seek, 0, 14)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
465
466
    def test_range_syntax(self):
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
467
        """Test the Content-Range scanning."""
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
468
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
469
        f = response.RangeFile('foo', BytesIO())
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
470
471
        def ok(expected, header_value):
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
472
            f.set_range_from_header(header_value)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
473
            # Slightly peek under the covers to get the size
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
474
            self.assertEqual(expected, (f.tell(), f._size))
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
475
476
        ok((1, 10), 'bytes 1-10/11')
477
        ok((1, 10), 'bytes 1-10/*')
478
        ok((12, 2), '\tbytes 12-13/*')
479
        ok((28, 1), '  bytes 28-28/*')
480
        ok((2123, 2120), 'bytes  2123-4242/12310')
7143.15.2 by Jelmer Vernooij
Run autopep8.
481
        ok((1, 10), 'bytes 1-10/ttt')  # We don't check total (ttt)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
482
483
        def nok(header_value):
484
            self.assertRaises(errors.InvalidHttpRange,
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
485
                              f.set_range_from_header, header_value)
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
486
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
487
        nok('bytes 10-2/3')
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
488
        nok('chars 1-2/3')
489
        nok('bytes xx-yyy/zzz')
490
        nok('bytes xx-12/zzz')
491
        nok('bytes 11-yy/zzz')
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
492
        nok('bytes10-2/3')
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
493
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
494
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
495
# Taken from real request responses
6973.11.6 by Jelmer Vernooij
Fix more http tests.
496
_full_text_response = (200, b"""HTTP/1.1 200 OK\r
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
497
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
498
Server: Apache/2.0.54 (Fedora)\r
499
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
500
ETag: "56691-23-38e9ae00"\r
501
Accept-Ranges: bytes\r
502
Content-Length: 35\r
503
Connection: close\r
504
Content-Type: text/plain; charset=UTF-8\r
505
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
506
""", b"""Bazaar-NG meta directory, format 1
1786.1.25 by John Arbash Meinel
Test that we can extract headers properly.
507
""")
508
509
6973.11.6 by Jelmer Vernooij
Fix more http tests.
510
_single_range_response = (206, b"""HTTP/1.1 206 Partial Content\r
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
511
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
512
Server: Apache/2.0.54 (Fedora)\r
513
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
514
ETag: "238a3c-16ec2-805c5540"\r
515
Accept-Ranges: bytes\r
516
Content-Length: 100\r
1786.1.26 by John Arbash Meinel
Update and test handle_response.
517
Content-Range: bytes 100-199/93890\r
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
518
Connection: close\r
519
Content-Type: text/plain; charset=UTF-8\r
520
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
521
""", b"""mbp@sourcefrog.net-20050309040815-13242001617e4a06
1786.1.26 by John Arbash Meinel
Update and test handle_response.
522
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
523
524
6973.11.6 by Jelmer Vernooij
Fix more http tests.
525
_single_range_no_content_type = (206, b"""HTTP/1.1 206 Partial Content\r
2070.1.1 by John Arbash Meinel
Fix bug #62473 by not requiring content-type in range responses
526
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
527
Server: Apache/2.0.54 (Fedora)\r
528
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
529
ETag: "238a3c-16ec2-805c5540"\r
530
Accept-Ranges: bytes\r
531
Content-Length: 100\r
532
Content-Range: bytes 100-199/93890\r
533
Connection: close\r
534
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
535
""", b"""mbp@sourcefrog.net-20050309040815-13242001617e4a06
2070.1.1 by John Arbash Meinel
Fix bug #62473 by not requiring content-type in range responses
536
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
537
538
6973.11.6 by Jelmer Vernooij
Fix more http tests.
539
_multipart_range_response = (206, b"""HTTP/1.1 206 Partial Content\r
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
540
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
541
Server: Apache/2.0.54 (Fedora)\r
542
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
543
ETag: "238a3c-16ec2-805c5540"\r
544
Accept-Ranges: bytes\r
545
Content-Length: 1534\r
546
Connection: close\r
547
Content-Type: multipart/byteranges; boundary=418470f848b63279b\r
548
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
549
\r""", b"""--418470f848b63279b\r
1786.1.21 by John Arbash Meinel
(broken) Work on factoring out handle_response so we can test with fake headers.
550
Content-type: text/plain; charset=UTF-8\r
551
Content-range: bytes 0-254/93890\r
552
\r
553
mbp@sourcefrog.net-20050309040815-13242001617e4a06
554
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e7627
555
mbp@sourcefrog.net-20050309040957-6cad07f466bb0bb8
556
mbp@sourcefrog.net-20050309041501-c840e09071de3b67
557
mbp@sourcefrog.net-20050309044615-c24a3250be83220a
558
\r
559
--418470f848b63279b\r
560
Content-type: text/plain; charset=UTF-8\r
561
Content-range: bytes 1000-2049/93890\r
562
\r
563
40-fd4ec249b6b139ab
564
mbp@sourcefrog.net-20050311063625-07858525021f270b
565
mbp@sourcefrog.net-20050311231934-aa3776aff5200bb9
566
mbp@sourcefrog.net-20050311231953-73aeb3a131c3699a
567
mbp@sourcefrog.net-20050311232353-f5e33da490872c6a
568
mbp@sourcefrog.net-20050312071639-0a8f59a34a024ff0
569
mbp@sourcefrog.net-20050312073432-b2c16a55e0d6e9fb
570
mbp@sourcefrog.net-20050312073831-a47c3335ece1920f
571
mbp@sourcefrog.net-20050312085412-13373aa129ccbad3
572
mbp@sourcefrog.net-20050313052251-2bf004cb96b39933
573
mbp@sourcefrog.net-20050313052856-3edd84094687cb11
574
mbp@sourcefrog.net-20050313053233-e30a4f28aef48f9d
575
mbp@sourcefrog.net-20050313053853-7c64085594ff3072
576
mbp@sourcefrog.net-20050313054757-a86c3f5871069e22
577
mbp@sourcefrog.net-20050313061422-418f1f73b94879b9
578
mbp@sourcefrog.net-20050313120651-497bd231b19df600
579
mbp@sourcefrog.net-20050314024931-eae0170ef25a5d1a
580
mbp@sourcefrog.net-20050314025438-d52099f915fe65fc
581
mbp@sourcefrog.net-20050314025539-637a636692c055cf
582
mbp@sourcefrog.net-20050314025737-55eb441f430ab4ba
583
mbp@sourcefrog.net-20050314025901-d74aa93bb7ee8f62
584
mbp@source\r
1979.1.1 by John Arbash Meinel
Fix bug #57723, parse boundary="" correctly, since Squid uses it
585
--418470f848b63279b--\r
586
""")
587
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
588
6973.11.6 by Jelmer Vernooij
Fix more http tests.
589
_multipart_squid_range_response = (206, b"""HTTP/1.0 206 Partial Content\r
1979.1.1 by John Arbash Meinel
Fix bug #57723, parse boundary="" correctly, since Squid uses it
590
Date: Thu, 31 Aug 2006 21:16:22 GMT\r
591
Server: Apache/2.2.2 (Unix) DAV/2\r
592
Last-Modified: Thu, 31 Aug 2006 17:57:06 GMT\r
593
Accept-Ranges: bytes\r
594
Content-Type: multipart/byteranges; boundary="squid/2.5.STABLE12:C99323425AD4FE26F726261FA6C24196"\r
595
Content-Length: 598\r
596
X-Cache: MISS from localhost.localdomain\r
597
X-Cache-Lookup: HIT from localhost.localdomain:3128\r
598
Proxy-Connection: keep-alive\r
599
\r
600
""",
7143.15.2 by Jelmer Vernooij
Run autopep8.
601
                                   b"""\r
1979.1.1 by John Arbash Meinel
Fix bug #57723, parse boundary="" correctly, since Squid uses it
602
--squid/2.5.STABLE12:C99323425AD4FE26F726261FA6C24196\r
603
Content-Type: text/plain\r
604
Content-Range: bytes 0-99/18672\r
605
\r
606
# bzr knit index 8
607
608
scott@netsplit.com-20050708230047-47c7868f276b939f fulltext 0 863  :
609
scott@netsp\r
610
--squid/2.5.STABLE12:C99323425AD4FE26F726261FA6C24196\r
611
Content-Type: text/plain\r
612
Content-Range: bytes 300-499/18672\r
613
\r
614
com-20050708231537-2b124b835395399a :
615
scott@netsplit.com-20050820234126-551311dbb7435b51 line-delta 1803 479 .scott@netsplit.com-20050820232911-dc4322a084eadf7e :
616
scott@netsplit.com-20050821213706-c86\r
617
--squid/2.5.STABLE12:C99323425AD4FE26F726261FA6C24196--\r
1786.1.25 by John Arbash Meinel
Test that we can extract headers properly.
618
""")
619
620
1786.1.26 by John Arbash Meinel
Update and test handle_response.
621
# This is made up
6973.11.6 by Jelmer Vernooij
Fix more http tests.
622
_full_text_response_no_content_type = (200, b"""HTTP/1.1 200 OK\r
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
623
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
624
Server: Apache/2.0.54 (Fedora)\r
625
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
626
ETag: "56691-23-38e9ae00"\r
627
Accept-Ranges: bytes\r
628
Content-Length: 35\r
629
Connection: close\r
630
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
631
""", b"""Bazaar-NG meta directory, format 1
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
632
""")
633
634
6973.11.6 by Jelmer Vernooij
Fix more http tests.
635
_full_text_response_no_content_length = (200, b"""HTTP/1.1 200 OK\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
636
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
637
Server: Apache/2.0.54 (Fedora)\r
638
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
639
ETag: "56691-23-38e9ae00"\r
640
Accept-Ranges: bytes\r
641
Connection: close\r
642
Content-Type: text/plain; charset=UTF-8\r
643
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
644
""", b"""Bazaar-NG meta directory, format 1
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
645
""")
646
647
6973.11.6 by Jelmer Vernooij
Fix more http tests.
648
_single_range_no_content_range = (206, b"""HTTP/1.1 206 Partial Content\r
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
649
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
650
Server: Apache/2.0.54 (Fedora)\r
651
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
652
ETag: "238a3c-16ec2-805c5540"\r
653
Accept-Ranges: bytes\r
654
Content-Length: 100\r
655
Connection: close\r
656
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
657
""", b"""mbp@sourcefrog.net-20050309040815-13242001617e4a06
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
658
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
659
660
6973.11.6 by Jelmer Vernooij
Fix more http tests.
661
_single_range_response_truncated = (206, b"""HTTP/1.1 206 Partial Content\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
662
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
663
Server: Apache/2.0.54 (Fedora)\r
664
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
665
ETag: "238a3c-16ec2-805c5540"\r
666
Accept-Ranges: bytes\r
667
Content-Length: 100\r
668
Content-Range: bytes 100-199/93890\r
669
Connection: close\r
670
Content-Type: text/plain; charset=UTF-8\r
671
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
672
""", b"""mbp@sourcefrog.net-20050309040815-13242001617e4a06""")
673
674
675
_invalid_response = (444, b"""HTTP/1.1 444 Bad Response\r
1786.1.26 by John Arbash Meinel
Update and test handle_response.
676
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
677
Connection: close\r
678
Content-Type: text/html; charset=iso-8859-1\r
679
\r
6973.11.6 by Jelmer Vernooij
Fix more http tests.
680
""", b"""<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1786.1.26 by John Arbash Meinel
Update and test handle_response.
681
<html><head>
682
<title>404 Not Found</title>
683
</head><body>
684
<h1>Not Found</h1>
685
<p>I don't know what I'm doing</p>
686
<hr>
687
</body></html>
688
""")
689
690
6973.11.6 by Jelmer Vernooij
Fix more http tests.
691
_multipart_no_content_range = (206, b"""HTTP/1.0 206 Partial Content\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
692
Content-Type: multipart/byteranges; boundary=THIS_SEPARATES\r
693
Content-Length: 598\r
694
\r
695
""",
7143.15.2 by Jelmer Vernooij
Run autopep8.
696
                               b"""\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
697
--THIS_SEPARATES\r
698
Content-Type: text/plain\r
699
\r
700
# bzr knit index 8
701
--THIS_SEPARATES\r
702
""")
703
704
6973.11.6 by Jelmer Vernooij
Fix more http tests.
705
_multipart_no_boundary = (206, b"""HTTP/1.0 206 Partial Content\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
706
Content-Type: multipart/byteranges; boundary=THIS_SEPARATES\r
707
Content-Length: 598\r
708
\r
709
""",
7143.15.2 by Jelmer Vernooij
Run autopep8.
710
                          b"""\r
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
711
--THIS_SEPARATES\r
712
Content-Type: text/plain\r
713
Content-Range: bytes 0-18/18672\r
714
\r
715
# bzr knit index 8
716
717
The range ended at the line above, this text is garbage instead of a boundary
718
line
719
""")
720
721
3059.2.12 by Vincent Ladeuil
Spiv review feedback.
722
class TestHandleResponse(tests.TestCase):
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
723
724
    def _build_HTTPMessage(self, raw_headers):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
725
        status_and_headers = BytesIO(raw_headers)
3059.2.11 by Vincent Ladeuil
Fix typos mentioned by spiv.
726
        # Get rid of the status line
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
727
        status_and_headers.readline()
7067.8.2 by Jelmer Vernooij
Fix some http response tests.
728
        msg = parse_headers(status_and_headers)
7296.2.9 by Jelmer Vernooij
Fix python3 compatibility.
729
        if PY3:
730
            return msg.get
731
        else:
732
            return msg.getheader
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
733
1786.1.26 by John Arbash Meinel
Update and test handle_response.
734
    def get_response(self, a_response):
735
        """Process a supplied response, and return the result."""
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
736
        code, raw_headers, body = a_response
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
737
        getheader = self._build_HTTPMessage(raw_headers)
738
        return response.handle_response(
739
            'http://foo', code, getheader, BytesIO(a_response[2]))
1786.1.26 by John Arbash Meinel
Update and test handle_response.
740
741
    def test_full_text(self):
742
        out = self.get_response(_full_text_response)
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
743
        # It is a BytesIO from the original data
1786.1.26 by John Arbash Meinel
Update and test handle_response.
744
        self.assertEqual(_full_text_response[2], out.read())
745
746
    def test_single_range(self):
747
        out = self.get_response(_single_range_response)
748
749
        out.seek(100)
750
        self.assertEqual(_single_range_response[2], out.read(100))
751
2070.1.1 by John Arbash Meinel
Fix bug #62473 by not requiring content-type in range responses
752
    def test_single_range_no_content(self):
753
        out = self.get_response(_single_range_no_content_type)
754
755
        out.seek(100)
756
        self.assertEqual(_single_range_no_content_type[2], out.read(100))
757
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
758
    def test_single_range_truncated(self):
759
        out = self.get_response(_single_range_response_truncated)
760
        # Content-Range declares 100 but only 51 present
761
        self.assertRaises(errors.ShortReadvError, out.seek, out.tell() + 51)
762
1786.1.26 by John Arbash Meinel
Update and test handle_response.
763
    def test_multi_range(self):
764
        out = self.get_response(_multipart_range_response)
765
766
        # Just make sure we can read the right contents
767
        out.seek(0)
768
        out.read(255)
769
770
        out.seek(1000)
771
        out.read(1050)
772
1979.1.1 by John Arbash Meinel
Fix bug #57723, parse boundary="" correctly, since Squid uses it
773
    def test_multi_squid_range(self):
774
        out = self.get_response(_multipart_squid_range_response)
775
776
        # Just make sure we can read the right contents
777
        out.seek(0)
778
        out.read(100)
779
780
        out.seek(300)
781
        out.read(200)
782
1786.1.26 by John Arbash Meinel
Update and test handle_response.
783
    def test_invalid_response(self):
784
        self.assertRaises(errors.InvalidHttpResponse,
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
785
                          self.get_response, _invalid_response)
1786.1.26 by John Arbash Meinel
Update and test handle_response.
786
787
    def test_full_text_no_content_type(self):
788
        # We should not require Content-Type for a full response
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
789
        code, raw_headers, body = _full_text_response_no_content_type
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
790
        getheader = self._build_HTTPMessage(raw_headers)
791
        out = response.handle_response(
792
            'http://foo', code, getheader, BytesIO(body))
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
793
        self.assertEqual(body, out.read())
1786.1.26 by John Arbash Meinel
Update and test handle_response.
794
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
795
    def test_full_text_no_content_length(self):
796
        code, raw_headers, body = _full_text_response_no_content_length
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
797
        getheader = self._build_HTTPMessage(raw_headers)
798
        out = response.handle_response(
799
            'http://foo', code, getheader, BytesIO(body))
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
800
        self.assertEqual(body, out.read())
801
1786.1.26 by John Arbash Meinel
Update and test handle_response.
802
    def test_missing_content_range(self):
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
803
        code, raw_headers, body = _single_range_no_content_range
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
804
        getheader = self._build_HTTPMessage(raw_headers)
1786.1.26 by John Arbash Meinel
Update and test handle_response.
805
        self.assertRaises(errors.InvalidHttpResponse,
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
806
                          response.handle_response,
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
807
                          'http://bogus', code, getheader, BytesIO(body))
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
808
809
    def test_multipart_no_content_range(self):
810
        code, raw_headers, body = _multipart_no_content_range
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
811
        getheader = self._build_HTTPMessage(raw_headers)
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
812
        self.assertRaises(errors.InvalidHttpResponse,
813
                          response.handle_response,
7296.2.5 by Jelmer Vernooij
More avoidance of urllib2-specific things.
814
                          'http://bogus', code, getheader, BytesIO(body))
3059.2.14 by Vincent Ladeuil
Complete coverage by adding tests for more invalid inputs. Fix a
815
816
    def test_multipart_no_boundary(self):
817
        out = self.get_response(_multipart_no_boundary)
818
        out.read()  # Read the whole range
819
        # Fail to find the boundary line
820
        self.assertRaises(errors.InvalidHttpResponse, out.seek, 1, 1)
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
821
822
823
class TestRangeFileSizeReadLimited(tests.TestCase):
824
    """Test RangeFile _max_read_size functionality which limits the size of
825
    read blocks to prevent MemoryError messages in socket.recv.
826
    """
827
828
    def setUp(self):
6552.1.3 by Vincent Ladeuil
Use super() instead of calling <base>.setup(self), as the original fix illustrated a too-easy-to-fall-into trap.
829
        super(TestRangeFileSizeReadLimited, self).setUp()
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
830
        # create a test datablock larger than _max_read_size.
831
        chunk_size = response.RangeFile._max_read_size
6973.11.6 by Jelmer Vernooij
Fix more http tests.
832
        test_pattern = b'0123456789ABCDEF'
7143.15.2 by Jelmer Vernooij
Run autopep8.
833
        self.test_data = test_pattern * (3 * chunk_size // len(test_pattern))
3408.6.1 by Eric Holmberg
Fix for Bug #215426 in which bzr can cause a MemoryError in socket.recv while
834
        self.test_data_len = len(self.test_data)
835
836
    def test_max_read_size(self):
837
        """Read data in blocks and verify that the reads are not larger than
838
           the maximum read size.
839
        """
840
        # retrieve data in large blocks from response.RangeFile object
841
        mock_read_file = FakeReadFile(self.test_data)
842
        range_file = response.RangeFile('test_max_read_size', mock_read_file)
843
        response_data = range_file.read(self.test_data_len)
844
845
        # verify read size was equal to the maximum read size
846
        self.assertTrue(mock_read_file.get_max_read_size() > 0)
847
        self.assertEqual(mock_read_file.get_max_read_size(),
848
                         response.RangeFile._max_read_size)
849
        self.assertEqual(mock_read_file.get_read_count(), 3)
850
851
        # report error if the data wasn't equal (we only report the size due
852
        # to the length of the data)
853
        if response_data != self.test_data:
854
            message = "Data not equal.  Expected %d bytes, received %d."
855
            self.fail(message % (len(response_data), self.test_data_len))