|
58 | 58 | import errno
|
59 | 59 | import sys
|
60 | 60 | import unittest
|
| 61 | +import requests |
| 62 | +import timeit |
61 | 63 |
|
62 | 64 | import tuf
|
63 | 65 | import tuf.exceptions
|
@@ -1270,9 +1272,58 @@ def test_3(param_1, param2):
|
1270 | 1272 | # Checks if the file has been successfully downloaded
|
1271 | 1273 | self.assertTrue(os.path.exists(download_filepath))
|
1272 | 1274 |
|
1273 |
| - # Test: normal case. |
| 1275 | + # Define a simple custom download handler mimicking |
| 1276 | + # the tuf.download call stack: |
| 1277 | + # safe_download() |
| 1278 | + # _download_file() |
| 1279 | + # _download_fixed_amount_of_data() |
| 1280 | + # _check_downloaded_length() |
| 1281 | + def download_handler(url, required_length): |
| 1282 | + url = six.moves.urllib.parse.unquote(url).replace('\\', '/') |
| 1283 | + temp_file = tempfile.TemporaryFile() |
| 1284 | + |
| 1285 | + try: |
| 1286 | + session = requests.Session() |
| 1287 | + with session.get(url, stream=True, |
| 1288 | + timeout=tuf.settings.SOCKET_TIMEOUT) as response: |
| 1289 | + |
| 1290 | + # Check response status. |
| 1291 | + response.raise_for_status() |
| 1292 | + |
| 1293 | + # Download fixed amount of data |
| 1294 | + average_download_speed = 0 |
| 1295 | + number_of_bytes_received = 0 |
| 1296 | + |
| 1297 | + start_time = timeit.default_timer() |
| 1298 | + |
| 1299 | + for chunk in response.iter_content(chunk_size=tuf.settings.CHUNK_SIZE): |
| 1300 | + number_of_bytes_received += len(chunk) |
| 1301 | + temp_file.write(chunk) |
| 1302 | + if number_of_bytes_received >= required_length: |
| 1303 | + break |
| 1304 | + |
| 1305 | + stop_time = timeit.default_timer() |
| 1306 | + average_download_speed = number_of_bytes_received / (stop_time - start_time) |
| 1307 | + if average_download_speed < tuf.settings.MIN_AVERAGE_DOWNLOAD_SPEED: |
| 1308 | + break |
| 1309 | + |
| 1310 | + #Check downloaded length |
| 1311 | + if number_of_bytes_received != required_length: |
| 1312 | + if average_download_speed < tuf.settings.MIN_AVERAGE_DOWNLOAD_SPEED: |
| 1313 | + raise tuf.exceptions.SlowRetrievalError(average_download_speed) |
| 1314 | + |
| 1315 | + raise tuf.exceptions.DownloadLengthMismatchError(required_length, number_of_bytes_received) |
| 1316 | + |
| 1317 | + except Exception: |
| 1318 | + temp_file.close() |
| 1319 | + raise |
| 1320 | + |
| 1321 | + else: |
| 1322 | + return temp_file |
| 1323 | + |
| 1324 | + #Test passing a custom download function |
1274 | 1325 | self.repository_updater.download_target(targetinfo, destination_directory,
|
1275 |
| - custom_download_handler=tuf.download.safe_download) |
| 1326 | + custom_download_handler=download_handler) |
1276 | 1327 |
|
1277 | 1328 | # Checks if the file has been successfully downloaded
|
1278 | 1329 | self.assertTrue(os.path.exists(download_filepath))
|
|
0 commit comments