|
1 | 1 | from datetime import datetime
|
2 |
| -from github3.utils import timestamp_parameter |
| 2 | +from github3.utils import stream_response_to_file, timestamp_parameter |
3 | 3 |
|
| 4 | +import io |
| 5 | +import mock |
4 | 6 | import pytest
|
| 7 | +import requests |
5 | 8 |
|
6 | 9 |
|
7 | 10 | class TestTimestampConverter:
|
@@ -38,3 +41,46 @@ def test_none_handling(self):
|
38 | 41 |
|
39 | 42 | def test_invalid_type_handling(self):
|
40 | 43 | pytest.raises(ValueError, timestamp_parameter, 1)
|
| 44 | + |
| 45 | + |
| 46 | +@pytest.fixture |
| 47 | +def mocked_open(): |
| 48 | + return mock.mock_open() |
| 49 | + |
| 50 | + |
| 51 | +@pytest.fixture |
| 52 | +def response(): |
| 53 | + r = requests.Response() |
| 54 | + r.raw = io.BytesIO(b'fake data') |
| 55 | + r.headers.update({'content-disposition': 'filename=a_file_name'}) |
| 56 | + return r |
| 57 | + |
| 58 | + |
| 59 | +class OpenFile: |
| 60 | + def __init__(self): |
| 61 | + self.data = b'' |
| 62 | + self.written_to = False |
| 63 | + |
| 64 | + def write(self, data): |
| 65 | + self.written_to = True |
| 66 | + self.data += data |
| 67 | + |
| 68 | + |
| 69 | +class TestStreamingDownloads: |
| 70 | + def test_opens_a_new_file(self, mocked_open, response): |
| 71 | + with mock.patch('github3.utils.open', mocked_open, create=True): |
| 72 | + stream_response_to_file(response, 'some_file') |
| 73 | + |
| 74 | + mocked_open.assert_called_once_with('some_file', 'wb') |
| 75 | + |
| 76 | + def test_uses_existing_file(self, response): |
| 77 | + fd = OpenFile() |
| 78 | + stream_response_to_file(response, fd) |
| 79 | + assert fd.written_to is True |
| 80 | + assert fd.data == b'fake data' |
| 81 | + |
| 82 | + def test_finds_filename_in_headers(self, mocked_open, response): |
| 83 | + with mock.patch('github3.utils.open', mocked_open, create=True): |
| 84 | + stream_response_to_file(response) |
| 85 | + |
| 86 | + mocked_open.assert_called_once_with('a_file_name', 'wb') |
0 commit comments