~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_http_response.py

  • Committer: Alexander Belchenko
  • Date: 2006-10-14 08:51:07 UTC
  • mto: (2080.1.1 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 2081.
  • Revision ID: bialix@ukr.net-20061014085107-8dff865674eed30a
win32 installer: make short info page instead of full GPL license text

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
"""Tests from HTTP response parsing.
18
 
 
19
 
The handle_response method read the response body of a GET request an returns
20
 
the corresponding RangeFile.
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,
33
 
 
34
 
- the expected pattern of use is either seek(offset)+read(size) or a single
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.
 
17
"""Tests from HTTP response parsing."""
 
18
 
 
19
from cStringIO import StringIO
 
20
import mimetools
 
21
 
 
22
from bzrlib import errors
 
23
from bzrlib.transport import http
 
24
from bzrlib.transport.http import response
 
25
from bzrlib.tests import TestCase
 
26
 
 
27
 
 
28
class TestResponseRange(TestCase):
 
29
    """Test the ResponseRange class."""
 
30
 
 
31
    def test_cmp(self):
 
32
        RR = response.ResponseRange
 
33
        r1 = RR(0, 10, 0)
 
34
        r2 = RR(15, 20, 10)
 
35
        self.assertTrue(r1 < r2)
 
36
        self.assertFalse(r1 > r2)
 
37
        self.assertTrue(r1 < 5)
 
38
        self.assertFalse(r2 < 5)
 
39
 
 
40
        self.assertEqual(RR(0, 10, 5), RR(0, 10, 5))
 
41
        self.assertNotEqual(RR(0, 10, 5), RR(0, 8, 5))
 
42
        self.assertNotEqual(RR(0, 10, 5), RR(0, 10, 6))
 
43
 
 
44
    def test_sort_list(self):
 
45
        """Ensure longer ranges are sorted after shorter ones"""
 
46
        RR = response.ResponseRange
 
47
        lst = [RR(3, 8, 0), 5, RR(3, 7, 0), 6]
 
48
        lst.sort()
 
49
        self.assertEqual([RR(3,7,0), RR(3,8,0), 5, 6], lst)
 
50
 
 
51
 
 
52
class TestRangeFile(TestCase):
 
53
    """Test RangeFile."""
 
54
 
 
55
    def setUp(self):
 
56
        content = "abcdefghijklmnopqrstuvwxyz"
 
57
        self.fp = response.RangeFile('foo', StringIO(content))
 
58
        self.fp._add_range(0,  9,   0)
 
59
        self.fp._add_range(20, 29, 10)
 
60
        self.fp._add_range(30, 39, 15)
 
61
 
 
62
    def test_valid_accesses(self):
 
63
        """Test so that valid accesses work to the file."""
 
64
        self.fp.seek(0, 0)
 
65
        self.assertEquals(self.fp.read(3), 'abc')
 
66
        self.assertEquals(self.fp.read(3), 'def')
 
67
        self.assertEquals(self.fp.tell(), 6)
 
68
        self.fp.seek(20, 0)
 
69
        self.assertEquals(self.fp.read(3), 'klm')
 
70
        self.assertEquals(self.fp.read(2), 'no')
 
71
        self.assertEquals(self.fp.tell(), 25)
 
72
        # should wrap over to 30-39 entity
 
73
        self.assertEquals(self.fp.read(3), 'pqr')
 
74
        self.fp.seek(3)
 
75
        self.assertEquals(self.fp.read(3), 'def')
 
76
        self.assertEquals(self.fp.tell(), 6)
 
77
 
 
78
    def test_invalid_accesses(self):
 
79
        """Test so that invalid accesses trigger errors."""
 
80
        self.fp.seek(9)
 
81
        self.assertRaises(errors.InvalidRange, self.fp.read, 2)
 
82
        self.fp.seek(39)
 
83
        self.assertRaises(errors.InvalidRange, self.fp.read, 2)
 
84
        self.fp.seek(19)
 
85
        self.assertRaises(errors.InvalidRange, self.fp.read, 2)
 
86
 
 
87
    def test__finish_ranges(self):
 
88
        """Test that after RangeFile._finish_ranges the list is sorted."""
 
89
        self.fp._add_range(1, 2, 3)
 
90
        self.fp._add_range(8, 9, 10)
 
91
        self.fp._add_range(3, 4, 5)
 
92
 
 
93
        # TODO: jam 20060706 If we switch to inserting
 
94
        #       in sorted order, remove this test
 
95
        self.assertNotEqual(self.fp._ranges, sorted(self.fp._ranges))
 
96
 
 
97
        self.fp._finish_ranges()
 
98
        self.assertEqual(self.fp._ranges, sorted(self.fp._ranges))
 
99
 
 
100
    def test_seek_and_tell(self):
 
101
        # Check for seeking before start
 
102
        self.fp.seek(-2, 0)
 
103
        self.assertEqual(0, self.fp.tell())
 
104
 
 
105
        self.fp.seek(5, 0)
 
106
        self.assertEqual(5, self.fp.tell())
 
107
 
 
108
        self.fp.seek(-2, 1)
 
109
        self.assertEqual(3, self.fp.tell())
 
110
 
 
111
        # TODO: jam 20060706 following tests will fail if this 
 
112
        #       is not true, and would be difficult to debug
 
113
        #       but it is a layering violation
 
114
        self.assertEqual(39, self.fp._len)
 
115
 
 
116
        self.fp.seek(0, 2)
 
117
        self.assertEqual(39, self.fp.tell())
 
118
 
 
119
        self.fp.seek(-10, 2)
 
120
        self.assertEqual(29, self.fp.tell())
 
121
 
 
122
        self.assertRaises(ValueError, self.fp.seek, 0, 4)
 
123
        self.assertRaises(ValueError, self.fp.seek, 0, -1)
 
124
 
 
125
 
 
126
class TestRegexes(TestCase):
 
127
 
 
128
    def assertRegexMatches(self, groups, text):
 
129
        """Check that the regex matches and returns the right values"""
 
130
        m = self.regex.match(text)
 
131
        self.assertNotEqual(None, m, "text %s did not match regex" % (text,))
 
132
 
 
133
        self.assertEqual(groups, m.groups())
 
134
 
 
135
    def test_range_re(self):
 
136
        """Test that we match valid ranges."""
 
137
        self.regex = response.HttpRangeResponse._CONTENT_RANGE_RE
 
138
        self.assertRegexMatches(('bytes', '1', '10', '11'),
 
139
                           'bytes 1-10/11')
 
140
        self.assertRegexMatches(('bytes', '1', '10', '11'),
 
141
                           '\tbytes  1-10/11   ')
 
142
        self.assertRegexMatches(('bytes', '2123', '4242', '1231'),
 
143
                           '\tbytes  2123-4242/1231   ')
 
144
        self.assertRegexMatches(('chars', '1', '2', '3'),
 
145
                           ' chars 1-2/3')
 
146
 
 
147
    def test_content_type_re(self):
 
148
        self.regex = response.HttpMultipartRangeResponse._CONTENT_TYPE_RE
 
149
        self.assertRegexMatches(('', 'xxyyzz'),
 
150
                                'multipart/byteranges; boundary = xxyyzz')
 
151
        self.assertRegexMatches(('', 'xxyyzz'),
 
152
                                'multipart/byteranges;boundary=xxyyzz')
 
153
        self.assertRegexMatches(('', 'xx yy zz'),
 
154
                                ' multipart/byteranges ; boundary= xx yy zz ')
 
155
        self.assertRegexMatches(('"', 'xx yy zz'),
 
156
                                ' multipart/byteranges ; boundary= "xx yy zz" ')
 
157
        self.assertEqual(None,
 
158
                         self.regex.match(
 
159
                             ' multipart/byteranges ; boundary= "xx yy zz '))
 
160
        self.assertEqual(None,
 
161
                         self.regex.match(
 
162
                             ' multipart/byteranges ; boundary= xx yy zz" '))
 
163
        self.assertEqual(None,
 
164
                self.regex.match('multipart byteranges;boundary=xx'))
 
165
 
 
166
 
 
167
simple_data = """
 
168
--xxyyzz\r
 
169
foo\r
 
170
Content-range: bytes 1-10/20\r
 
171
\r
 
172
1234567890
 
173
--xxyyzz\r
 
174
Content-Range: bytes 21-30/20\r
 
175
bar\r
 
176
\r
 
177
abcdefghij
 
178
--xxyyzz\r
 
179
content-range: bytes 41-50/20\r
 
180
\r
 
181
zyxwvutsrq
 
182
--xxyyzz\r
 
183
content-range: bytes 51-60/20\r
 
184
\r
 
185
xxyyzz fbd
38
186
"""
39
187
 
40
 
from cStringIO import StringIO
41
 
import httplib
42
 
 
43
 
from bzrlib import (
44
 
    errors,
45
 
    tests,
46
 
    )
47
 
from bzrlib.transport.http import (
48
 
    response,
49
 
    _urllib2_wrappers,
50
 
    )
51
 
 
52
 
 
53
 
class ReadSocket(object):
54
 
    """A socket-like object that can be given a predefined content."""
55
 
 
56
 
    def __init__(self, data):
57
 
        self.readfile = StringIO(data)
58
 
 
59
 
    def makefile(self, mode='r', bufsize=None):
60
 
        return self.readfile
61
 
 
62
 
class FakeHTTPConnection(_urllib2_wrappers.HTTPConnection):
63
 
 
64
 
    def __init__(self, sock):
65
 
        _urllib2_wrappers.HTTPConnection.__init__(self, 'localhost')
66
 
        # Set the socket to bypass the connection
67
 
        self.sock = sock
68
 
 
69
 
    def send(self, str):
70
 
        """Ignores the writes on the socket."""
71
 
        pass
72
 
 
73
 
 
74
 
class TestHTTPConnection(tests.TestCase):
75
 
 
76
 
    def test_cleanup_pipe(self):
77
 
        sock = ReadSocket("""HTTP/1.1 200 OK\r
78
 
Content-Type: text/plain; charset=UTF-8\r
79
 
Content-Length: 18
80
 
\r
81
 
0123456789
82
 
garbage""")
83
 
        conn = FakeHTTPConnection(sock)
84
 
        # Simulate the request sending so that the connection will be able to
85
 
        # read the response.
86
 
        conn.putrequest('GET', 'http://localhost/fictious')
87
 
        conn.endheaders()
88
 
        # Now, get the response
89
 
        resp = conn.getresponse()
90
 
        # Read part of the response
91
 
        self.assertEquals('0123456789\n', resp.read(11))
92
 
        # Override the thresold to force the warning emission
93
 
        conn._range_warning_thresold = 6 # There are 7 bytes pending
94
 
        conn.cleanup_pipe()
95
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
96
 
                              'Got a 200 response when asking')
97
 
 
98
 
 
99
 
class TestRangeFileMixin(object):
100
 
    """Tests for accessing the first range in a RangeFile."""
101
 
 
102
 
    # A simple string used to represent a file part (also called a range), in
103
 
    # which offsets are easy to calculate for test writers. It's used as a
104
 
    # building block with slight variations but basically 'a' is the first char
105
 
    # of the range and 'z' is the last.
106
 
    alpha = 'abcdefghijklmnopqrstuvwxyz'
107
 
 
108
 
    def test_can_read_at_first_access(self):
109
 
        """Test that the just created file can be read."""
110
 
        self.assertEquals(self.alpha, self._file.read())
111
 
 
112
 
    def test_seek_read(self):
113
 
        """Test seek/read inside the range."""
114
 
        f = self._file
115
 
        start = self.first_range_start
116
 
        # Before any use, tell() should be at the range start
117
 
        self.assertEquals(start, f.tell())
118
 
        cur = start # For an overall offset assertion
119
 
        f.seek(start + 3)
120
 
        cur += 3
121
 
        self.assertEquals('def', f.read(3))
122
 
        cur += len('def')
123
 
        f.seek(4, 1)
124
 
        cur += 4
125
 
        self.assertEquals('klmn', f.read(4))
126
 
        cur += len('klmn')
127
 
        # read(0) in the middle of a range
128
 
        self.assertEquals('', f.read(0))
129
 
        # seek in place
130
 
        here = f.tell()
131
 
        f.seek(0, 1)
132
 
        self.assertEquals(here, f.tell())
133
 
        self.assertEquals(cur, f.tell())
134
 
 
135
 
    def test_read_zero(self):
136
 
        f = self._file
137
 
        start = self.first_range_start
138
 
        self.assertEquals('', f.read(0))
139
 
        f.seek(10, 1)
140
 
        self.assertEquals('', f.read(0))
141
 
 
142
 
    def test_seek_at_range_end(self):
143
 
        f = self._file
144
 
        f.seek(26, 1)
145
 
 
146
 
    def test_read_at_range_end(self):
147
 
        """Test read behaviour at range end."""
148
 
        f = self._file
149
 
        self.assertEquals(self.alpha, f.read())
150
 
        self.assertEquals('', f.read(0))
151
 
        self.assertRaises(errors.InvalidRange, f.read, 1)
152
 
 
153
 
    def test_unbounded_read_after_seek(self):
154
 
        f = self._file
155
 
        f.seek(24, 1)
156
 
        # Should not cross ranges
157
 
        self.assertEquals('yz', f.read())
158
 
 
159
 
    def test_seek_backwards(self):
160
 
        f = self._file
161
 
        start = self.first_range_start
162
 
        f.seek(start)
163
 
        f.read(12)
164
 
        self.assertRaises(errors.InvalidRange, f.seek, start + 5)
165
 
 
166
 
    def test_seek_outside_single_range(self):
167
 
        f = self._file
168
 
        if f._size == -1 or f._boundary is not None:
169
 
            raise tests.TestNotApplicable('Needs a fully defined range')
170
 
        # Will seek past the range and then errors out
171
 
        self.assertRaises(errors.InvalidRange,
172
 
                          f.seek, self.first_range_start + 27)
173
 
 
174
 
    def test_read_past_end_of_range(self):
175
 
        f = self._file
176
 
        if f._size == -1:
177
 
            raise tests.TestNotApplicable("Can't check an unknown size")
178
 
        start = self.first_range_start
179
 
        f.seek(start + 20)
180
 
        self.assertRaises(errors.InvalidRange, f.read, 10)
181
 
 
182
 
    def test_seek_from_end(self):
183
 
       """Test seeking from the end of the file.
184
 
 
185
 
       The semantic is unclear in case of multiple ranges. Seeking from end
186
 
       exists only for the http transports, cannot be used if the file size is
187
 
       unknown and is not used in bzrlib itself. This test must be (and is)
188
 
       overridden by daughter classes.
189
 
 
190
 
       Reading from end makes sense only when a range has been requested from
191
 
       the end of the file (see HttpTransportBase._get() when using the
192
 
       'tail_amount' parameter). The HTTP response can only be a whole file or
193
 
       a single range.
194
 
       """
195
 
       f = self._file
196
 
       f.seek(-2, 2)
197
 
       self.assertEquals('yz', f.read())
198
 
 
199
 
 
200
 
class TestRangeFileSizeUnknown(tests.TestCase, TestRangeFileMixin):
201
 
    """Test a RangeFile for a whole file whose size is not known."""
202
 
 
203
 
    def setUp(self):
204
 
        super(TestRangeFileSizeUnknown, self).setUp()
205
 
        self._file = response.RangeFile('Whole_file_size_known',
206
 
                                        StringIO(self.alpha))
207
 
        # We define no range, relying on RangeFile to provide default values
208
 
        self.first_range_start = 0 # It's the whole file
209
 
 
210
 
    def test_seek_from_end(self):
211
 
        """See TestRangeFileMixin.test_seek_from_end.
212
 
 
213
 
        The end of the file can't be determined since the size is unknown.
214
 
        """
215
 
        self.assertRaises(errors.InvalidRange, self._file.seek, -1, 2)
216
 
 
217
 
    def test_read_at_range_end(self):
218
 
        """Test read behaviour at range end."""
219
 
        f = self._file
220
 
        self.assertEquals(self.alpha, f.read())
221
 
        self.assertEquals('', f.read(0))
222
 
        self.assertEquals('', f.read(1))
223
 
 
224
 
class TestRangeFileSizeKnown(tests.TestCase, TestRangeFileMixin):
225
 
    """Test a RangeFile for a whole file whose size is known."""
226
 
 
227
 
    def setUp(self):
228
 
        super(TestRangeFileSizeKnown, self).setUp()
229
 
        self._file = response.RangeFile('Whole_file_size_known',
230
 
                                        StringIO(self.alpha))
231
 
        self._file.set_range(0, len(self.alpha))
232
 
        self.first_range_start = 0 # It's the whole file
233
 
 
234
 
 
235
 
class TestRangeFileSingleRange(tests.TestCase, TestRangeFileMixin):
236
 
    """Test a RangeFile for a single range."""
237
 
 
238
 
    def setUp(self):
239
 
        super(TestRangeFileSingleRange, self).setUp()
240
 
        self._file = response.RangeFile('Single_range_file',
241
 
                                        StringIO(self.alpha))
242
 
        self.first_range_start = 15
243
 
        self._file.set_range(self.first_range_start, len(self.alpha))
244
 
 
245
 
 
246
 
    def test_read_before_range(self):
247
 
        # This can't occur under normal circumstances, we have to force it
248
 
        f = self._file
249
 
        f._pos = 0 # Force an invalid pos
 
188
 
 
189
class TestHelpers(TestCase):
 
190
    """Test the helper functions"""
 
191
 
 
192
    def test__parse_range(self):
 
193
        """Test that _parse_range acts reasonably."""
 
194
        content = StringIO('')
 
195
        parse_range = response.HttpRangeResponse._parse_range
 
196
        self.assertEqual((1,2), parse_range('bytes 1-2/3'))
 
197
        self.assertEqual((10,20), parse_range('bytes 10-20/2'))
 
198
 
 
199
        self.assertRaises(errors.InvalidHttpRange, parse_range, 'char 1-3/2')
 
200
        self.assertRaises(errors.InvalidHttpRange, parse_range, 'bytes a-3/2')
 
201
 
 
202
        try:
 
203
            parse_range('bytes x-10/3', path='http://foo/bar')
 
204
        except errors.InvalidHttpRange, e:
 
205
            self.assertContainsRe(str(e), 'http://foo/bar')
 
206
            self.assertContainsRe(str(e), 'bytes x-10/3')
 
207
        else:
 
208
            self.fail('Did not raise InvalidHttpRange')
 
209
 
 
210
    def test__parse_boundary_simple(self):
 
211
        """Test that _parse_boundary handles Content-type properly"""
 
212
        parse_boundary = response.HttpMultipartRangeResponse._parse_boundary
 
213
        m = parse_boundary(' multipart/byteranges; boundary=xxyyzz')
 
214
        self.assertNotEqual(None, m)
 
215
        # Check that the returned regex is capable of splitting simple_data
 
216
        matches = list(m.finditer(simple_data))
 
217
        self.assertEqual(4, len(matches))
 
218
 
 
219
        # match.group() should be the content-range entry
 
220
        # and match.end() should be the start of the content
 
221
        self.assertEqual(' bytes 1-10/20', matches[0].group(1))
 
222
        self.assertEqual(simple_data.find('1234567890'), matches[0].end())
 
223
        self.assertEqual(' bytes 21-30/20', matches[1].group(1))
 
224
        self.assertEqual(simple_data.find('abcdefghij'), matches[1].end())
 
225
        self.assertEqual(' bytes 41-50/20', matches[2].group(1))
 
226
        self.assertEqual(simple_data.find('zyxwvutsrq'), matches[2].end())
 
227
        self.assertEqual(' bytes 51-60/20', matches[3].group(1))
 
228
        self.assertEqual(simple_data.find('xxyyzz fbd'), matches[3].end())
 
229
 
 
230
    def test__parse_boundary_invalid(self):
 
231
        parse_boundary = response.HttpMultipartRangeResponse._parse_boundary
 
232
        try:
 
233
            parse_boundary(' multipart/bytes;boundary=xxyyzz',
 
234
                           path='http://foo/bar')
 
235
        except errors.InvalidHttpContentType, e:
 
236
            self.assertContainsRe(str(e), 'http://foo/bar')
 
237
            self.assertContainsRe(str(e), 'multipart/bytes;boundary=xxyyzz')
 
238
        else:
 
239
            self.fail('Did not raise InvalidHttpContentType')
 
240
 
 
241
 
 
242
class TestHttpRangeResponse(TestCase):
 
243
 
 
244
    def test_smoketest(self):
 
245
        """A basic test that HttpRangeResponse is reasonable."""
 
246
        content = StringIO('0123456789')
 
247
        f = response.HttpRangeResponse('http://foo', 'bytes 1-10/9', content)
 
248
        self.assertEqual([response.ResponseRange(1,10,0)], f._ranges)
 
249
 
 
250
        f.seek(0)
250
251
        self.assertRaises(errors.InvalidRange, f.read, 2)
251
 
 
252
 
class TestRangeFileMultipleRanges(tests.TestCase, TestRangeFileMixin):
253
 
    """Test a RangeFile for multiple ranges.
254
 
 
255
 
    The RangeFile used for the tests contains three ranges:
256
 
 
257
 
    - at offset 25: alpha
258
 
    - at offset 100: alpha
259
 
    - at offset 126: alpha.upper()
260
 
 
261
 
    The two last ranges are contiguous. This only rarely occurs (should not in
262
 
    fact) in real uses but may lead to hard to track bugs.
263
 
    """
264
 
 
265
 
    def setUp(self):
266
 
        super(TestRangeFileMultipleRanges, self).setUp()
267
 
 
268
 
        boundary = 'separation'
269
 
 
270
 
        content = ''
271
 
        self.first_range_start = 25
272
 
        file_size = 200 # big enough to encompass all ranges
273
 
        for (start, part) in [(self.first_range_start, self.alpha),
274
 
                              # Two contiguous ranges
275
 
                              (100, self.alpha),
276
 
                              (126, self.alpha.upper())]:
277
 
            content += self._multipart_byterange(part, start, boundary,
278
 
                                                 file_size)
279
 
        # Final boundary
280
 
        content += self._boundary_line(boundary)
281
 
 
282
 
        self._file = response.RangeFile('Multiple_ranges_file',
283
 
                                        StringIO(content))
284
 
        # Ranges are set by decoding the range headers, the RangeFile user is
285
 
        # supposed to call the following before using seek or read since it
286
 
        # requires knowing the *response* headers (in that case the boundary
287
 
        # which is part of the Content-Type header).
288
 
        self._file.set_boundary(boundary)
289
 
 
290
 
    def _boundary_line(self, boundary):
291
 
        """Helper to build the formatted boundary line."""
292
 
        return '--' + boundary + '\r\n'
293
 
 
294
 
    def _multipart_byterange(self, data, offset, boundary, file_size='*'):
295
 
        """Encode a part of a file as a multipart/byterange MIME type.
296
 
 
297
 
        When a range request is issued, the HTTP response body can be
298
 
        decomposed in parts, each one representing a range (start, size) in a
299
 
        file.
300
 
 
301
 
        :param data: The payload.
302
 
        :param offset: where data starts in the file
303
 
        :param boundary: used to separate the parts
304
 
        :param file_size: the size of the file containing the range (default to
305
 
            '*' meaning unknown)
306
 
 
307
 
        :return: a string containing the data encoded as it will appear in the
308
 
            HTTP response body.
309
 
        """
310
 
        bline = self._boundary_line(boundary)
311
 
        # Each range begins with a boundary line
312
 
        range = bline
313
 
        # A range is described by a set of headers, but only 'Content-Range' is
314
 
        # required for our implementation (TestHandleResponse below will
315
 
        # exercise ranges with multiple or missing headers')
316
 
        range += 'Content-Range: bytes %d-%d/%d\r\n' % (offset,
317
 
                                                        offset+len(data)-1,
318
 
                                                        file_size)
319
 
        range += '\r\n'
320
 
        # Finally the raw bytes
321
 
        range += data
322
 
        return range
323
 
 
324
 
    def test_read_all_ranges(self):
325
 
        f = self._file
326
 
        self.assertEquals(self.alpha, f.read()) # Read first range
327
 
        f.seek(100) # Trigger the second range recognition
328
 
        self.assertEquals(self.alpha, f.read()) # Read second range
329
 
        self.assertEquals(126, f.tell())
330
 
        f.seek(126) # Start of third range which is also the current pos !
331
 
        self.assertEquals('A', f.read(1))
332
 
        f.seek(10, 1)
333
 
        self.assertEquals('LMN', f.read(3))
334
 
 
335
 
    def test_seek_from_end(self):
336
 
        """See TestRangeFileMixin.test_seek_from_end."""
337
 
        # The actual implementation will seek from end for the first range only
338
 
        # and then fail. Since seeking from end is intended to be used for a
339
 
        # single range only anyway, this test just document the actual
340
 
        # behaviour.
341
 
        f = self._file
342
 
        f.seek(-2, 2)
343
 
        self.assertEquals('yz', f.read())
344
 
        self.assertRaises(errors.InvalidRange, f.seek, -2, 2)
345
 
 
346
 
    def test_seek_into_void(self):
347
 
        f = self._file
348
 
        start = self.first_range_start
349
 
        f.seek(start)
350
 
        # Seeking to a point between two ranges is possible (only once) but
351
 
        # reading there is forbidden
352
 
        f.seek(start + 40)
353
 
        # We crossed a range boundary, so now the file is positioned at the
354
 
        # start of the new range (i.e. trying to seek below 100 will error out)
355
 
        f.seek(100)
356
 
        f.seek(125)
357
 
 
358
 
    def test_seek_across_ranges(self):
359
 
        f = self._file
360
 
        start = self.first_range_start
361
 
        f.seek(126) # skip the two first ranges
362
 
        self.assertEquals('AB', f.read(2))
363
 
 
364
 
    def test_checked_read_dont_overflow_buffers(self):
365
 
        f = self._file
366
 
        start = self.first_range_start
367
 
        # We force a very low value to exercise all code paths in _checked_read
368
 
        f._discarded_buf_size = 8
369
 
        f.seek(126) # skip the two first ranges
370
 
        self.assertEquals('AB', f.read(2))
371
 
 
372
 
    def test_seek_twice_between_ranges(self):
373
 
        f = self._file
374
 
        start = self.first_range_start
375
 
        f.seek(start + 40) # Past the first range but before the second
376
 
        # Now the file is positioned at the second range start (100)
377
 
        self.assertRaises(errors.InvalidRange, f.seek, start + 41)
378
 
 
379
 
    def test_seek_at_range_end(self):
380
 
        """Test seek behavior at range end."""
381
 
        f = self._file
382
 
        f.seek(25 + 25)
383
 
        f.seek(100 + 25)
384
 
        f.seek(126 + 25)
385
 
 
386
 
    def test_read_at_range_end(self):
387
 
        f = self._file
388
 
        self.assertEquals(self.alpha, f.read())
389
 
        self.assertEquals(self.alpha, f.read())
390
 
        self.assertEquals(self.alpha.upper(), f.read())
391
 
        self.assertRaises(errors.InvalidHttpResponse, f.read, 1)
392
 
 
393
 
 
394
 
class TestRangeFileVarious(tests.TestCase):
395
 
    """Tests RangeFile aspects not covered elsewhere."""
396
 
 
397
 
    def test_seek_whence(self):
398
 
        """Test the seek whence parameter values."""
399
 
        f = response.RangeFile('foo', StringIO('abc'))
400
 
        f.set_range(0, 3)
401
 
        f.seek(0)
402
 
        f.seek(1, 1)
403
 
        f.seek(-1, 2)
404
 
        self.assertRaises(ValueError, f.seek, 0, 14)
405
 
 
406
 
    def test_range_syntax(self):
407
 
        """Test the Content-Range scanning."""
408
 
 
409
 
        f = response.RangeFile('foo', StringIO())
410
 
 
411
 
        def ok(expected, header_value):
412
 
            f.set_range_from_header(header_value)
413
 
            # Slightly peek under the covers to get the size
414
 
            self.assertEquals(expected, (f.tell(), f._size))
415
 
 
416
 
        ok((1, 10), 'bytes 1-10/11')
417
 
        ok((1, 10), 'bytes 1-10/*')
418
 
        ok((12, 2), '\tbytes 12-13/*')
419
 
        ok((28, 1), '  bytes 28-28/*')
420
 
        ok((2123, 2120), 'bytes  2123-4242/12310')
421
 
        ok((1, 10), 'bytes 1-10/ttt') # We don't check total (ttt)
422
 
 
423
 
        def nok(header_value):
424
 
            self.assertRaises(errors.InvalidHttpRange,
425
 
                              f.set_range_from_header, header_value)
426
 
 
427
 
        nok('bytes 10-2/3')
428
 
        nok('chars 1-2/3')
429
 
        nok('bytes xx-yyy/zzz')
430
 
        nok('bytes xx-12/zzz')
431
 
        nok('bytes 11-yy/zzz')
432
 
        nok('bytes10-2/3')
 
252
        f.seek(1)
 
253
        self.assertEqual('012345', f.read(6))
 
254
 
 
255
    def test_invalid(self):
 
256
        try:
 
257
            f = response.HttpRangeResponse('http://foo', 'bytes x-10/9',
 
258
                                           StringIO('0123456789'))
 
259
        except errors.InvalidHttpRange, e:
 
260
            self.assertContainsRe(str(e), 'http://foo')
 
261
            self.assertContainsRe(str(e), 'bytes x-10/9')
 
262
        else:
 
263
            self.fail('Failed to raise InvalidHttpRange')
 
264
 
 
265
 
 
266
class TestHttpMultipartRangeResponse(TestCase):
 
267
    """Test the handling of multipart range responses"""
 
268
 
 
269
    def test_simple(self):
 
270
        content = StringIO(simple_data)
 
271
        multi = response.HttpMultipartRangeResponse('http://foo',
 
272
                    'multipart/byteranges; boundary = xxyyzz', content)
 
273
 
 
274
        self.assertEqual(4, len(multi._ranges))
 
275
 
 
276
        multi.seek(1)
 
277
        self.assertEqual('1234567890', multi.read(10))
 
278
        multi.seek(21)
 
279
        self.assertEqual('abcdefghij', multi.read(10))
 
280
        multi.seek(41)
 
281
        self.assertEqual('zyxwvutsrq', multi.read(10))
 
282
        multi.seek(51)
 
283
        self.assertEqual('xxyyzz fbd', multi.read(10))
 
284
        # TODO: jam 20060706 Currently RangeFile does not support
 
285
        #       reading across ranges. Consider adding it.
 
286
        multi.seek(41)
 
287
        # self.assertEqual('zyxwvutsrqxxyyzz fbd', multi.read(20))
 
288
        self.assertRaises(errors.InvalidRange, multi.read, 20)
 
289
 
 
290
        multi.seek(21)
 
291
        self.assertRaises(errors.InvalidRange, multi.read, 11)
 
292
        multi.seek(31)
 
293
        self.assertRaises(errors.InvalidRange, multi.read, 10)
 
294
 
 
295
    def test_invalid(self):
 
296
        content = StringIO('')
 
297
        try:
 
298
            response.HttpMultipartRangeResponse('http://foo',
 
299
                        'multipart/byte;boundary=invalid', content)
 
300
        except errors.InvalidHttpContentType, e:
 
301
            self.assertContainsRe(str(e), 'http://foo')
 
302
            self.assertContainsRe(str(e), 'multipart/byte;')
433
303
 
434
304
 
435
305
# Taken from real request responses
447
317
""")
448
318
 
449
319
 
 
320
_missing_response = (404, """HTTP/1.1 404 Not Found\r
 
321
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
 
322
Server: Apache/2.0.54 (Fedora)\r
 
323
Content-Length: 336\r
 
324
Connection: close\r
 
325
Content-Type: text/html; charset=iso-8859-1\r
 
326
\r
 
327
""", """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 
328
<html><head>
 
329
<title>404 Not Found</title>
 
330
</head><body>
 
331
<h1>Not Found</h1>
 
332
<p>The requested URL /branches/bzr/jam-integration/.bzr/repository/format was not found on this server.</p>
 
333
<hr>
 
334
<address>Apache/2.0.54 (Fedora) Server at bzr.arbash-meinel.com Port 80</address>
 
335
</body></html>
 
336
""")
 
337
 
 
338
 
450
339
_single_range_response = (206, """HTTP/1.1 206 Partial Content\r
451
340
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
452
341
Server: Apache/2.0.54 (Fedora)\r
462
351
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
463
352
 
464
353
 
465
 
_single_range_no_content_type = (206, """HTTP/1.1 206 Partial Content\r
466
 
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
467
 
Server: Apache/2.0.54 (Fedora)\r
468
 
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
469
 
ETag: "238a3c-16ec2-805c5540"\r
470
 
Accept-Ranges: bytes\r
471
 
Content-Length: 100\r
472
 
Content-Range: bytes 100-199/93890\r
473
 
Connection: close\r
474
 
\r
475
 
""", """mbp@sourcefrog.net-20050309040815-13242001617e4a06
476
 
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
477
 
 
478
 
 
479
354
_multipart_range_response = (206, """HTTP/1.1 206 Partial Content\r
480
355
Date: Tue, 11 Jul 2006 04:49:48 GMT\r
481
356
Server: Apache/2.0.54 (Fedora)\r
525
400
--418470f848b63279b--\r
526
401
""")
527
402
 
528
 
 
529
403
_multipart_squid_range_response = (206, """HTTP/1.0 206 Partial Content\r
530
404
Date: Thu, 31 Aug 2006 21:16:22 GMT\r
531
405
Server: Apache/2.2.2 (Unix) DAV/2\r
558
432
""")
559
433
 
560
434
 
 
435
_redirect_response = (206, """HTTP/1.1 301 Moved Permanently\r
 
436
Date: Tue, 18 Jul 2006 20:29:22 GMT\r
 
437
Server: Apache/2.0.54 (Ubuntu) PHP/4.4.0-3ubuntu1 mod_ssl/2.0.54 OpenSSL/0.9.7g\r
 
438
Location: http://bazaar-vcs.org/bzr/bzr.dev/.bzr/repository/inventory.knit\r
 
439
Content-Length: 272\r
 
440
Keep-Alive: timeout=15, max=100\r
 
441
Connection: Keep-Alive\r
 
442
Content-Type: text/html; charset=iso-8859-1\r
 
443
\r
 
444
HTTP/1.1 206 Partial Content\r
 
445
Date: Tue, 18 Jul 2006 20:29:23 GMT\r
 
446
Server: Apache/2.0.54 (Ubuntu) PHP/4.4.0-3ubuntu1 mod_ssl/2.0.54 OpenSSL/0.9.7g\r
 
447
Last-Modified: Tue, 18 Jul 2006 20:24:59 GMT\r
 
448
ETag: "be8213-83958c-f0d3dcc0"\r
 
449
Accept-Ranges: bytes\r
 
450
Content-Length: 425\r
 
451
Content-Range: bytes 8623075-8623499/8623500\r
 
452
Keep-Alive: timeout=15, max=100\r
 
453
Connection: Keep-Alive\r
 
454
Content-Type: text/plain; charset=UTF-8\r
 
455
\r
 
456
""", """this data intentionally removed, 
 
457
this is not meant to be tested by
 
458
handle_response, just _extract_headers
 
459
""")
 
460
 
 
461
 
561
462
# This is made up
562
 
_full_text_response_no_content_type = (200, """HTTP/1.1 200 OK\r
563
 
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
564
 
Server: Apache/2.0.54 (Fedora)\r
565
 
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
566
 
ETag: "56691-23-38e9ae00"\r
567
 
Accept-Ranges: bytes\r
568
 
Content-Length: 35\r
569
 
Connection: close\r
570
 
\r
571
 
""", """Bazaar-NG meta directory, format 1
572
 
""")
573
 
 
574
 
 
575
 
_full_text_response_no_content_length = (200, """HTTP/1.1 200 OK\r
576
 
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
577
 
Server: Apache/2.0.54 (Fedora)\r
578
 
Last-Modified: Sun, 23 Apr 2006 19:35:20 GMT\r
579
 
ETag: "56691-23-38e9ae00"\r
580
 
Accept-Ranges: bytes\r
581
 
Connection: close\r
582
 
Content-Type: text/plain; charset=UTF-8\r
583
 
\r
584
 
""", """Bazaar-NG meta directory, format 1
585
 
""")
586
 
 
587
 
 
588
 
_single_range_no_content_range = (206, """HTTP/1.1 206 Partial Content\r
589
 
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
590
 
Server: Apache/2.0.54 (Fedora)\r
591
 
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
592
 
ETag: "238a3c-16ec2-805c5540"\r
593
 
Accept-Ranges: bytes\r
594
 
Content-Length: 100\r
595
 
Connection: close\r
596
 
\r
597
 
""", """mbp@sourcefrog.net-20050309040815-13242001617e4a06
598
 
mbp@sourcefrog.net-20050309040929-eee0eb3e6d1e762""")
599
 
 
600
 
 
601
 
_single_range_response_truncated = (206, """HTTP/1.1 206 Partial Content\r
602
 
Date: Tue, 11 Jul 2006 04:45:22 GMT\r
603
 
Server: Apache/2.0.54 (Fedora)\r
604
 
Last-Modified: Thu, 06 Jul 2006 20:22:05 GMT\r
605
 
ETag: "238a3c-16ec2-805c5540"\r
606
 
Accept-Ranges: bytes\r
607
 
Content-Length: 100\r
608
 
Content-Range: bytes 100-199/93890\r
609
 
Connection: close\r
610
 
Content-Type: text/plain; charset=UTF-8\r
611
 
\r
612
 
""", """mbp@sourcefrog.net-20050309040815-13242001617e4a06""")
613
 
 
614
 
 
615
463
_invalid_response = (444, """HTTP/1.1 444 Bad Response\r
616
464
Date: Tue, 11 Jul 2006 04:32:56 GMT\r
617
465
Connection: close\r
628
476
""")
629
477
 
630
478
 
631
 
_multipart_no_content_range = (206, """HTTP/1.0 206 Partial Content\r
632
 
Content-Type: multipart/byteranges; boundary=THIS_SEPARATES\r
633
 
Content-Length: 598\r
634
 
\r
635
 
""",
636
 
"""\r
637
 
--THIS_SEPARATES\r
638
 
Content-Type: text/plain\r
639
 
\r
640
 
# bzr knit index 8
641
 
--THIS_SEPARATES\r
642
 
""")
643
 
 
644
 
 
645
 
_multipart_no_boundary = (206, """HTTP/1.0 206 Partial Content\r
646
 
Content-Type: multipart/byteranges; boundary=THIS_SEPARATES\r
647
 
Content-Length: 598\r
648
 
\r
649
 
""",
650
 
"""\r
651
 
--THIS_SEPARATES\r
652
 
Content-Type: text/plain\r
653
 
Content-Range: bytes 0-18/18672\r
654
 
\r
655
 
# bzr knit index 8
656
 
 
657
 
The range ended at the line above, this text is garbage instead of a boundary
658
 
line
659
 
""")
660
 
 
661
 
 
662
 
class TestHandleResponse(tests.TestCase):
663
 
 
664
 
    def _build_HTTPMessage(self, raw_headers):
665
 
        status_and_headers = StringIO(raw_headers)
666
 
        # Get rid of the status line
667
 
        status_and_headers.readline()
668
 
        msg = httplib.HTTPMessage(status_and_headers)
669
 
        return msg
670
 
 
 
479
# This should be in test_http.py, but the headers we
 
480
# want to parse are here
 
481
class TestExtractHeader(TestCase):
 
482
    
 
483
    def use_response(self, response):
 
484
        self.headers = http._extract_headers(response[1], 'http://foo')
 
485
 
 
486
    def check_header(self, header, value):
 
487
        self.assertEqual(value, self.headers[header])
 
488
        
 
489
    def test_full_text(self):
 
490
        self.use_response(_full_text_response)
 
491
 
 
492
        self.check_header('Date', 'Tue, 11 Jul 2006 04:32:56 GMT')
 
493
        self.check_header('date', 'Tue, 11 Jul 2006 04:32:56 GMT')
 
494
        self.check_header('Content-Length', '35')
 
495
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
496
        self.check_header('content-type', 'text/plain; charset=UTF-8')
 
497
 
 
498
    def test_missing_response(self):
 
499
        self.use_response(_missing_response)
 
500
 
 
501
        self.check_header('Content-Length', '336')
 
502
        self.check_header('Content-Type', 'text/html; charset=iso-8859-1')
 
503
 
 
504
    def test_single_range(self):
 
505
        self.use_response(_single_range_response)
 
506
 
 
507
        self.check_header('Content-Length', '100')
 
508
        self.check_header('Content-Range', 'bytes 100-199/93890')
 
509
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
510
 
 
511
    def test_multi_range(self):
 
512
        self.use_response(_multipart_range_response)
 
513
 
 
514
        self.check_header('Content-Length', '1534')
 
515
        self.check_header('Content-Type',
 
516
                          'multipart/byteranges; boundary=418470f848b63279b')
 
517
 
 
518
    def test_multi_squid_range(self):
 
519
        self.use_response(_multipart_squid_range_response)
 
520
 
 
521
        self.check_header('Content-Length', '598')
 
522
        self.check_header('Content-Type',
 
523
                          'multipart/byteranges; '\
 
524
                          'boundary="squid/2.5.STABLE12:C99323425AD4FE26F726261FA6C24196"')
 
525
 
 
526
    def test_redirect(self):
 
527
        """We default to returning the last group of headers in the file."""
 
528
        self.use_response(_redirect_response)
 
529
        self.check_header('Content-Range', 'bytes 8623075-8623499/8623500')
 
530
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
531
 
 
532
    def test_empty(self):
 
533
        self.assertRaises(errors.InvalidHttpResponse,
 
534
            http._extract_headers, '', 'bad url')
 
535
 
 
536
    def test_no_opening_http(self):
 
537
        # Remove the HTTP line from the header
 
538
        first, txt = _full_text_response[1].split('\r\n', 1)
 
539
        self.assertRaises(errors.InvalidHttpResponse,
 
540
            http._extract_headers, txt, 'missing HTTTP')
 
541
 
 
542
    def test_trailing_whitespace(self):
 
543
        # Test that we ignore bogus whitespace on the end
 
544
        code, txt, body = _full_text_response
 
545
        txt += '\r\n\n\n\n\n'
 
546
        self.use_response((code, txt, body))
 
547
 
 
548
        self.check_header('Date', 'Tue, 11 Jul 2006 04:32:56 GMT')
 
549
        self.check_header('Content-Length', '35')
 
550
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
551
 
 
552
    def test_trailing_non_http(self):
 
553
        # Test that we ignore bogus stuff on the end
 
554
        code, txt, body = _full_text_response
 
555
        txt = txt + 'Foo: Bar\r\nBaz: Bling\r\n\r\n'
 
556
        self.use_response((code, txt, body))
 
557
 
 
558
        self.check_header('Date', 'Tue, 11 Jul 2006 04:32:56 GMT')
 
559
        self.check_header('Content-Length', '35')
 
560
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
561
        self.assertRaises(KeyError, self.headers.__getitem__, 'Foo')
 
562
 
 
563
    def test_extra_whitespace(self):
 
564
        # Test that we read an HTTP response, even with extra whitespace
 
565
        code, txt, body = _redirect_response
 
566
        # Find the second HTTP location
 
567
        loc = txt.find('HTTP', 5)
 
568
        txt = txt[:loc] + '\r\n\n' + txt[loc:]
 
569
        self.use_response((code, txt, body))
 
570
        self.check_header('Content-Range', 'bytes 8623075-8623499/8623500')
 
571
        self.check_header('Content-Type', 'text/plain; charset=UTF-8')
 
572
 
 
573
 
 
574
class TestHandleResponse(TestCase):
 
575
    
671
576
    def get_response(self, a_response):
672
577
        """Process a supplied response, and return the result."""
673
 
        code, raw_headers, body = a_response
674
 
        msg = self._build_HTTPMessage(raw_headers)
675
 
        return response.handle_response('http://foo', code, msg,
 
578
        headers = http._extract_headers(a_response[1], 'http://foo')
 
579
        return response.handle_response('http://foo', a_response[0], headers,
676
580
                                        StringIO(a_response[2]))
677
581
 
678
582
    def test_full_text(self):
680
584
        # It is a StringIO from the original data
681
585
        self.assertEqual(_full_text_response[2], out.read())
682
586
 
 
587
    def test_missing_response(self):
 
588
        self.assertRaises(errors.NoSuchFile,
 
589
            self.get_response, _missing_response)
 
590
 
683
591
    def test_single_range(self):
684
592
        out = self.get_response(_single_range_response)
 
593
        self.assertIsInstance(out, response.HttpRangeResponse)
 
594
 
 
595
        self.assertRaises(errors.InvalidRange, out.read, 20)
685
596
 
686
597
        out.seek(100)
687
598
        self.assertEqual(_single_range_response[2], out.read(100))
688
599
 
689
 
    def test_single_range_no_content(self):
690
 
        out = self.get_response(_single_range_no_content_type)
691
 
 
692
 
        out.seek(100)
693
 
        self.assertEqual(_single_range_no_content_type[2], out.read(100))
694
 
 
695
 
    def test_single_range_truncated(self):
696
 
        out = self.get_response(_single_range_response_truncated)
697
 
        # Content-Range declares 100 but only 51 present
698
 
        self.assertRaises(errors.ShortReadvError, out.seek, out.tell() + 51)
699
 
 
700
600
    def test_multi_range(self):
701
601
        out = self.get_response(_multipart_range_response)
 
602
        self.assertIsInstance(out, response.HttpMultipartRangeResponse)
702
603
 
703
604
        # Just make sure we can read the right contents
704
605
        out.seek(0)
709
610
 
710
611
    def test_multi_squid_range(self):
711
612
        out = self.get_response(_multipart_squid_range_response)
 
613
        self.assertIsInstance(out, response.HttpMultipartRangeResponse)
712
614
 
713
615
        # Just make sure we can read the right contents
714
616
        out.seek(0)
719
621
 
720
622
    def test_invalid_response(self):
721
623
        self.assertRaises(errors.InvalidHttpResponse,
722
 
                          self.get_response, _invalid_response)
 
624
            self.get_response, _invalid_response)
723
625
 
724
626
    def test_full_text_no_content_type(self):
725
627
        # We should not require Content-Type for a full response
726
 
        code, raw_headers, body = _full_text_response_no_content_type
727
 
        msg = self._build_HTTPMessage(raw_headers)
728
 
        out = response.handle_response('http://foo', code, msg, StringIO(body))
729
 
        self.assertEqual(body, out.read())
730
 
 
731
 
    def test_full_text_no_content_length(self):
732
 
        code, raw_headers, body = _full_text_response_no_content_length
733
 
        msg = self._build_HTTPMessage(raw_headers)
734
 
        out = response.handle_response('http://foo', code, msg, StringIO(body))
735
 
        self.assertEqual(body, out.read())
 
628
        a_response = _full_text_response
 
629
        headers = http._extract_headers(a_response[1], 'http://foo')
 
630
        del headers['Content-Type']
 
631
        out = response.handle_response('http://foo', a_response[0], headers,
 
632
                                        StringIO(a_response[2]))
 
633
        self.assertEqual(_full_text_response[2], out.read())
 
634
 
 
635
    def test_missing_no_content_type(self):
 
636
        # Without Content-Type we should still raise NoSuchFile on a 404
 
637
        a_response = _missing_response
 
638
        headers = http._extract_headers(a_response[1], 'http://missing')
 
639
        del headers['Content-Type']
 
640
        self.assertRaises(errors.NoSuchFile,
 
641
            response.handle_response, 'http://missing', a_response[0], headers,
 
642
                                      StringIO(a_response[2]))
 
643
 
 
644
    def test_missing_content_type(self):
 
645
        a_response = _single_range_response
 
646
        headers = http._extract_headers(a_response[1], 'http://nocontent')
 
647
        del headers['Content-Type']
 
648
        self.assertRaises(errors.InvalidHttpContentType,
 
649
            response.handle_response, 'http://nocontent', a_response[0],
 
650
                                      headers, StringIO(a_response[2]))
736
651
 
737
652
    def test_missing_content_range(self):
738
 
        code, raw_headers, body = _single_range_no_content_range
739
 
        msg = self._build_HTTPMessage(raw_headers)
740
 
        self.assertRaises(errors.InvalidHttpResponse,
741
 
                          response.handle_response,
742
 
                          'http://bogus', code, msg, StringIO(body))
743
 
 
744
 
    def test_multipart_no_content_range(self):
745
 
        code, raw_headers, body = _multipart_no_content_range
746
 
        msg = self._build_HTTPMessage(raw_headers)
747
 
        self.assertRaises(errors.InvalidHttpResponse,
748
 
                          response.handle_response,
749
 
                          'http://bogus', code, msg, StringIO(body))
750
 
 
751
 
    def test_multipart_no_boundary(self):
752
 
        out = self.get_response(_multipart_no_boundary)
753
 
        out.read()  # Read the whole range
754
 
        # Fail to find the boundary line
755
 
        self.assertRaises(errors.InvalidHttpResponse, out.seek, 1, 1)
 
653
        a_response = _single_range_response
 
654
        headers = http._extract_headers(a_response[1], 'http://nocontent')
 
655
        del headers['Content-Range']
 
656
        self.assertRaises(errors.InvalidHttpResponse,
 
657
            response.handle_response, 'http://nocontent', a_response[0],
 
658
                                      headers, StringIO(a_response[2]))