Skip to content

Commit ca6f280

Browse files
committed
Implement a custom_download_handler in test_updater
Add a test implementation of a custom_download_handler mimicking the tuf.download call stack. Signed-off-by: Teodora Sechkova <[email protected]>
1 parent aa3a635 commit ca6f280

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed

tests/test_updater.py

+53-2
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@
5858
import errno
5959
import sys
6060
import unittest
61+
import requests
62+
import timeit
6163

6264
import tuf
6365
import tuf.exceptions
@@ -1270,9 +1272,58 @@ def test_3(param_1, param2):
12701272
# Checks if the file has been successfully downloaded
12711273
self.assertTrue(os.path.exists(download_filepath))
12721274

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
12741325
self.repository_updater.download_target(targetinfo, destination_directory,
1275-
custom_download_handler=tuf.download.safe_download)
1326+
custom_download_handler=download_handler)
12761327

12771328
# Checks if the file has been successfully downloaded
12781329
self.assertTrue(os.path.exists(download_filepath))

0 commit comments

Comments
 (0)