File size: 27,192 Bytes
065fee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import http.client
import io

from unittest import mock
import pytest  # type: ignore

from google.resumable_media import _download
from google.resumable_media import common


EXAMPLE_URL = (
    "https://www.googleapis.com/download/storage/v1/b/{BUCKET}/o/{OBJECT}?alt=media"
)


class TestDownloadBase(object):
    def test_constructor_defaults(self):
        download = _download.DownloadBase(EXAMPLE_URL)
        assert download.media_url == EXAMPLE_URL
        assert download._stream is None
        assert download.start is None
        assert download.end is None
        assert download._headers == {}
        assert not download._finished
        _check_retry_strategy(download)

    def test_constructor_explicit(self):
        start = 11
        end = 10001
        headers = {"foof": "barf"}
        download = _download.DownloadBase(
            EXAMPLE_URL,
            stream=mock.sentinel.stream,
            start=start,
            end=end,
            headers=headers,
        )
        assert download.media_url == EXAMPLE_URL
        assert download._stream is mock.sentinel.stream
        assert download.start == start
        assert download.end == end
        assert download._headers is headers
        assert not download._finished
        _check_retry_strategy(download)

    def test_finished_property(self):
        download = _download.DownloadBase(EXAMPLE_URL)
        # Default value of @property.
        assert not download.finished

        # Make sure we cannot set it on public @property.
        with pytest.raises(AttributeError):
            download.finished = False

        # Set it privately and then check the @property.
        download._finished = True
        assert download.finished

    def test__get_status_code(self):
        with pytest.raises(NotImplementedError) as exc_info:
            _download.DownloadBase._get_status_code(None)

        exc_info.match("virtual")

    def test__get_headers(self):
        with pytest.raises(NotImplementedError) as exc_info:
            _download.DownloadBase._get_headers(None)

        exc_info.match("virtual")

    def test__get_body(self):
        with pytest.raises(NotImplementedError) as exc_info:
            _download.DownloadBase._get_body(None)

        exc_info.match("virtual")


class TestDownload(object):
    def test__prepare_request_already_finished(self):
        download = _download.Download(EXAMPLE_URL)
        download._finished = True
        with pytest.raises(ValueError):
            download._prepare_request()

    def test__prepare_request(self):
        download1 = _download.Download(EXAMPLE_URL)
        method1, url1, payload1, headers1 = download1._prepare_request()
        assert method1 == "GET"
        assert url1 == EXAMPLE_URL
        assert payload1 is None
        assert headers1 == {}

        download2 = _download.Download(EXAMPLE_URL, start=53)
        method2, url2, payload2, headers2 = download2._prepare_request()
        assert method2 == "GET"
        assert url2 == EXAMPLE_URL
        assert payload2 is None
        assert headers2 == {"range": "bytes=53-"}

    def test__prepare_request_with_headers(self):
        headers = {"spoonge": "borb"}
        download = _download.Download(EXAMPLE_URL, start=11, end=111, headers=headers)
        method, url, payload, new_headers = download._prepare_request()
        assert method == "GET"
        assert url == EXAMPLE_URL
        assert payload is None
        assert new_headers is headers
        assert headers == {"range": "bytes=11-111", "spoonge": "borb"}

    def test__process_response(self):
        download = _download.Download(EXAMPLE_URL)
        _fix_up_virtual(download)

        # Make sure **not finished** before.
        assert not download.finished
        response = mock.Mock(status_code=int(http.client.OK), spec=["status_code"])
        ret_val = download._process_response(response)
        assert ret_val is None
        # Make sure **finished** after.
        assert download.finished

    def test__process_response_bad_status(self):
        download = _download.Download(EXAMPLE_URL)
        _fix_up_virtual(download)

        # Make sure **not finished** before.
        assert not download.finished
        response = mock.Mock(
            status_code=int(http.client.NOT_FOUND), spec=["status_code"]
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 5
        assert error.args[1] == response.status_code
        assert error.args[3] == http.client.OK
        assert error.args[4] == http.client.PARTIAL_CONTENT
        # Make sure **finished** even after a failure.
        assert download.finished

    def test_consume(self):
        download = _download.Download(EXAMPLE_URL)
        with pytest.raises(NotImplementedError) as exc_info:
            download.consume(None)

        exc_info.match("virtual")


class TestChunkedDownload(object):
    def test_constructor_defaults(self):
        chunk_size = 256
        stream = mock.sentinel.stream
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        assert download.media_url == EXAMPLE_URL
        assert download.chunk_size == chunk_size
        assert download.start == 0
        assert download.end is None
        assert download._headers == {}
        assert not download._finished
        _check_retry_strategy(download)
        assert download._stream is stream
        assert download._bytes_downloaded == 0
        assert download._total_bytes is None
        assert not download._invalid

    def test_constructor_bad_start(self):
        with pytest.raises(ValueError):
            _download.ChunkedDownload(EXAMPLE_URL, 256, None, start=-11)

    def test_bytes_downloaded_property(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 256, None)
        # Default value of @property.
        assert download.bytes_downloaded == 0

        # Make sure we cannot set it on public @property.
        with pytest.raises(AttributeError):
            download.bytes_downloaded = 1024

        # Set it privately and then check the @property.
        download._bytes_downloaded = 128
        assert download.bytes_downloaded == 128

    def test_total_bytes_property(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 256, None)
        # Default value of @property.
        assert download.total_bytes is None

        # Make sure we cannot set it on public @property.
        with pytest.raises(AttributeError):
            download.total_bytes = 65536

        # Set it privately and then check the @property.
        download._total_bytes = 8192
        assert download.total_bytes == 8192

    def test__get_byte_range(self):
        chunk_size = 512
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, None)
        curr_start, curr_end = download._get_byte_range()
        assert curr_start == 0
        assert curr_end == chunk_size - 1

    def test__get_byte_range_with_end(self):
        chunk_size = 512
        start = 1024
        end = 1151
        download = _download.ChunkedDownload(
            EXAMPLE_URL, chunk_size, None, start=start, end=end
        )
        curr_start, curr_end = download._get_byte_range()
        assert curr_start == start
        assert curr_end == end
        # Make sure this is less than the chunk size.
        actual_size = curr_end - curr_start + 1
        assert actual_size < chunk_size

    def test__get_byte_range_with_total_bytes(self):
        chunk_size = 512
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, None)
        total_bytes = 207
        download._total_bytes = total_bytes
        curr_start, curr_end = download._get_byte_range()
        assert curr_start == 0
        assert curr_end == total_bytes - 1
        # Make sure this is less than the chunk size.
        actual_size = curr_end - curr_start + 1
        assert actual_size < chunk_size

    @staticmethod
    def _response_content_range(start_byte, end_byte, total_bytes):
        return "bytes {:d}-{:d}/{:d}".format(start_byte, end_byte, total_bytes)

    def _response_headers(self, start_byte, end_byte, total_bytes):
        content_length = end_byte - start_byte + 1
        resp_range = self._response_content_range(start_byte, end_byte, total_bytes)
        return {
            "content-length": "{:d}".format(content_length),
            "content-range": resp_range,
        }

    def _mock_response(
        self, start_byte, end_byte, total_bytes, content=None, status_code=None
    ):
        response_headers = self._response_headers(start_byte, end_byte, total_bytes)
        return mock.Mock(
            content=content,
            headers=response_headers,
            status_code=status_code,
            spec=["content", "headers", "status_code"],
        )

    def test__prepare_request_already_finished(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 64, None)
        download._finished = True
        with pytest.raises(ValueError) as exc_info:
            download._prepare_request()

        assert exc_info.match("Download has finished.")

    def test__prepare_request_invalid(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 64, None)
        download._invalid = True
        with pytest.raises(ValueError) as exc_info:
            download._prepare_request()

        assert exc_info.match("Download is invalid and cannot be re-used.")

    def test__prepare_request(self):
        chunk_size = 2048
        download1 = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, None)
        method1, url1, payload1, headers1 = download1._prepare_request()
        assert method1 == "GET"
        assert url1 == EXAMPLE_URL
        assert payload1 is None
        assert headers1 == {"range": "bytes=0-2047"}

        download2 = _download.ChunkedDownload(
            EXAMPLE_URL, chunk_size, None, start=19991
        )
        download2._total_bytes = 20101
        method2, url2, payload2, headers2 = download2._prepare_request()
        assert method2 == "GET"
        assert url2 == EXAMPLE_URL
        assert payload2 is None
        assert headers2 == {"range": "bytes=19991-20100"}

    def test__prepare_request_with_headers(self):
        chunk_size = 2048
        headers = {"patrizio": "Starf-ish"}
        download = _download.ChunkedDownload(
            EXAMPLE_URL, chunk_size, None, headers=headers
        )
        method, url, payload, new_headers = download._prepare_request()
        assert method == "GET"
        assert url == EXAMPLE_URL
        assert payload is None
        assert new_headers is headers
        expected = {"patrizio": "Starf-ish", "range": "bytes=0-2047"}
        assert headers == expected

    def test__make_invalid(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 512, None)
        assert not download.invalid
        download._make_invalid()
        assert download.invalid

    def test__process_response(self):
        data = b"1234xyztL" * 37  # 9 * 37 == 33
        chunk_size = len(data)
        stream = io.BytesIO()
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        already = 22
        download._bytes_downloaded = already
        total_bytes = 4444

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == already
        assert download.total_bytes is None
        # Actually call the method to update.
        response = self._mock_response(
            already,
            already + chunk_size - 1,
            total_bytes,
            content=data,
            status_code=int(http.client.PARTIAL_CONTENT),
        )
        download._process_response(response)
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == already + chunk_size
        assert download.total_bytes == total_bytes
        assert stream.getvalue() == data

    def test__process_response_transfer_encoding(self):
        data = b"1234xyztL" * 37
        chunk_size = len(data)
        stream = io.BytesIO()
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        already = 22
        download._bytes_downloaded = already
        total_bytes = 4444

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == already
        assert download.total_bytes is None
        assert not download.invalid
        # Actually call the method to update.
        response = self._mock_response(
            already,
            already + chunk_size - 1,
            total_bytes,
            content=data,
            status_code=int(http.client.PARTIAL_CONTENT),
        )
        response.headers["transfer-encoding"] = "chunked"
        del response.headers["content-length"]
        download._process_response(response)
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == already + chunk_size
        assert download.total_bytes == total_bytes
        assert stream.getvalue() == data

    def test__process_response_bad_status(self):
        chunk_size = 384
        stream = mock.Mock(spec=["write"])
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        total_bytes = 300

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        # Actually call the method to update.
        response = self._mock_response(
            0, total_bytes - 1, total_bytes, status_code=int(http.client.NOT_FOUND)
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 5
        assert error.args[1] == response.status_code
        assert error.args[3] == http.client.OK
        assert error.args[4] == http.client.PARTIAL_CONTENT
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert download.invalid
        stream.write.assert_not_called()

    def test__process_response_missing_content_length(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 256, None)
        _fix_up_virtual(download)

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert not download.invalid
        # Actually call the method to update.
        response = mock.Mock(
            headers={"content-range": "bytes 0-99/99"},
            status_code=int(http.client.PARTIAL_CONTENT),
            content=b"DEADBEEF",
            spec=["headers", "status_code", "content"],
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 2
        assert error.args[1] == "content-length"
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert download.invalid

    def test__process_response_bad_content_range(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 256, None)
        _fix_up_virtual(download)

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert not download.invalid
        # Actually call the method to update.
        data = b"stuff"
        headers = {
            "content-length": "{:d}".format(len(data)),
            "content-range": "kites x-y/58",
        }
        response = mock.Mock(
            content=data,
            headers=headers,
            status_code=int(http.client.PARTIAL_CONTENT),
            spec=["content", "headers", "status_code"],
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 3
        assert error.args[1] == headers["content-range"]
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert download.invalid

    def test__process_response_body_wrong_length(self):
        chunk_size = 10
        stream = mock.Mock(spec=["write"])
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        total_bytes = 100

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        # Actually call the method to update.
        data = b"not 10"
        response = self._mock_response(
            0,
            chunk_size - 1,
            total_bytes,
            content=data,
            status_code=int(http.client.PARTIAL_CONTENT),
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 5
        assert error.args[2] == chunk_size
        assert error.args[4] == len(data)
        # Check internal state after.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        assert download.invalid
        stream.write.assert_not_called()

    def test__process_response_when_finished(self):
        chunk_size = 256
        stream = io.BytesIO()
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        total_bytes = 200

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None
        # Actually call the method to update.
        data = b"abcd" * 50  # 4 * 50 == 200
        response = self._mock_response(
            0,
            total_bytes - 1,
            total_bytes,
            content=data,
            status_code=int(http.client.OK),
        )
        download._process_response(response)
        # Check internal state after.
        assert download.finished
        assert download.bytes_downloaded == total_bytes
        assert total_bytes < chunk_size
        assert download.total_bytes == total_bytes
        assert stream.getvalue() == data

    def test__process_response_when_reaching_end(self):
        chunk_size = 8192
        end = 65000
        stream = io.BytesIO()
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream, end=end)
        _fix_up_virtual(download)

        download._bytes_downloaded = 7 * chunk_size
        download._total_bytes = 8 * chunk_size

        # Check internal state before.
        assert not download.finished
        assert download.bytes_downloaded == 7 * chunk_size
        assert download.total_bytes == 8 * chunk_size
        # Actually call the method to update.
        expected_size = end - 7 * chunk_size + 1
        data = b"B" * expected_size
        response = self._mock_response(
            7 * chunk_size,
            end,
            8 * chunk_size,
            content=data,
            status_code=int(http.client.PARTIAL_CONTENT),
        )
        download._process_response(response)
        # Check internal state after.
        assert download.finished
        assert download.bytes_downloaded == end + 1
        assert download.bytes_downloaded < download.total_bytes
        assert download.total_bytes == 8 * chunk_size
        assert stream.getvalue() == data

    def test__process_response_when_content_range_is_zero(self):
        chunk_size = 10
        stream = mock.Mock(spec=["write"])
        download = _download.ChunkedDownload(EXAMPLE_URL, chunk_size, stream)
        _fix_up_virtual(download)

        content_range = _download._ZERO_CONTENT_RANGE_HEADER
        headers = {"content-range": content_range}
        status_code = http.client.REQUESTED_RANGE_NOT_SATISFIABLE
        response = mock.Mock(
            headers=headers, status_code=status_code, spec=["headers", "status_code"]
        )
        download._process_response(response)
        stream.write.assert_not_called()
        assert download.finished
        assert download.bytes_downloaded == 0
        assert download.total_bytes is None

    def test_consume_next_chunk(self):
        download = _download.ChunkedDownload(EXAMPLE_URL, 256, None)
        with pytest.raises(NotImplementedError) as exc_info:
            download.consume_next_chunk(None)

        exc_info.match("virtual")


class Test__add_bytes_range(object):
    def test_do_nothing(self):
        headers = {}
        ret_val = _download.add_bytes_range(None, None, headers)
        assert ret_val is None
        assert headers == {}

    def test_both_vals(self):
        headers = {}
        ret_val = _download.add_bytes_range(17, 1997, headers)
        assert ret_val is None
        assert headers == {"range": "bytes=17-1997"}

    def test_end_only(self):
        headers = {}
        ret_val = _download.add_bytes_range(None, 909, headers)
        assert ret_val is None
        assert headers == {"range": "bytes=0-909"}

    def test_start_only(self):
        headers = {}
        ret_val = _download.add_bytes_range(3735928559, None, headers)
        assert ret_val is None
        assert headers == {"range": "bytes=3735928559-"}

    def test_start_as_offset(self):
        headers = {}
        ret_val = _download.add_bytes_range(-123454321, None, headers)
        assert ret_val is None
        assert headers == {"range": "bytes=-123454321"}


class Test_get_range_info(object):
    @staticmethod
    def _make_response(content_range):
        headers = {"content-range": content_range}
        return mock.Mock(headers=headers, spec=["headers"])

    def _success_helper(self, **kwargs):
        content_range = "Bytes 7-11/42"
        response = self._make_response(content_range)
        start_byte, end_byte, total_bytes = _download.get_range_info(
            response, _get_headers, **kwargs
        )
        assert start_byte == 7
        assert end_byte == 11
        assert total_bytes == 42

    def test_success(self):
        self._success_helper()

    def test_success_with_callback(self):
        callback = mock.Mock(spec=[])
        self._success_helper(callback=callback)
        callback.assert_not_called()

    def _failure_helper(self, **kwargs):
        content_range = "nope x-6/y"
        response = self._make_response(content_range)
        with pytest.raises(common.InvalidResponse) as exc_info:
            _download.get_range_info(response, _get_headers, **kwargs)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 3
        assert error.args[1] == content_range

    def test_failure(self):
        self._failure_helper()

    def test_failure_with_callback(self):
        callback = mock.Mock(spec=[])
        self._failure_helper(callback=callback)
        callback.assert_called_once_with()

    def _missing_header_helper(self, **kwargs):
        response = mock.Mock(headers={}, spec=["headers"])
        with pytest.raises(common.InvalidResponse) as exc_info:
            _download.get_range_info(response, _get_headers, **kwargs)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 2
        assert error.args[1] == "content-range"

    def test_missing_header(self):
        self._missing_header_helper()

    def test_missing_header_with_callback(self):
        callback = mock.Mock(spec=[])
        self._missing_header_helper(callback=callback)
        callback.assert_called_once_with()


class Test__check_for_zero_content_range(object):
    @staticmethod
    def _make_response(content_range, status_code):
        headers = {"content-range": content_range}
        return mock.Mock(
            headers=headers, status_code=status_code, spec=["headers", "status_code"]
        )

    def test_status_code_416_and_test_content_range_zero_both(self):
        content_range = _download._ZERO_CONTENT_RANGE_HEADER
        status_code = http.client.REQUESTED_RANGE_NOT_SATISFIABLE
        response = self._make_response(content_range, status_code)
        assert _download._check_for_zero_content_range(
            response, _get_status_code, _get_headers
        )

    def test_status_code_416_only(self):
        content_range = "bytes 2-5/3"
        status_code = http.client.REQUESTED_RANGE_NOT_SATISFIABLE
        response = self._make_response(content_range, status_code)
        assert not _download._check_for_zero_content_range(
            response, _get_status_code, _get_headers
        )

    def test_content_range_zero_only(self):
        content_range = _download._ZERO_CONTENT_RANGE_HEADER
        status_code = http.client.OK
        response = self._make_response(content_range, status_code)
        assert not _download._check_for_zero_content_range(
            response, _get_status_code, _get_headers
        )


def _get_status_code(response):
    return response.status_code


def _get_headers(response):
    return response.headers


def _get_body(response):
    return response.content


def _fix_up_virtual(download):
    download._get_status_code = _get_status_code
    download._get_headers = _get_headers
    download._get_body = _get_body


def _check_retry_strategy(download):
    retry_strategy = download._retry_strategy
    assert isinstance(retry_strategy, common.RetryStrategy)
    assert retry_strategy.max_sleep == common.MAX_SLEEP
    assert retry_strategy.max_cumulative_retry == common.MAX_CUMULATIVE_RETRY
    assert retry_strategy.max_retries is None