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