| 1 |
# Copyright 2021, New York University and the TUF contributors |
| 2 |
# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 3 |
|
| 4 |
"""Unit test for Urllib3Fetcher.""" |
| 5 |
|
| 6 |
import io |
| 7 |
import logging |
| 8 |
import math |
| 9 |
import os |
| 10 |
import sys |
| 11 |
import tempfile |
| 12 |
import unittest |
| 13 |
from typing import ClassVar |
| 14 |
from unittest.mock import Mock, patch |
| 15 |
|
| 16 |
import urllib3 |
| 17 |
|
| 18 |
from tests import utils |
| 19 |
from tuf.api import exceptions |
| 20 |
from tuf.ngclient import Urllib3Fetcher |
| 21 |
|
| 22 |
logger = logging.getLogger(__name__) |
| 23 |
|
| 24 |
|
| 25 |
class TestFetcher(unittest.TestCase): |
| 26 |
"""Test Urllib3Fetcher class.""" |
| 27 |
|
| 28 |
server_process_handler: ClassVar[utils.TestServerProcess] |
| 29 |
|
| 30 |
@classmethod |
| 31 |
def setUpClass(cls) -> None: |
| 32 |
""" |
| 33 |
Create a temporary file and launch a simple server in the |
| 34 |
current working directory. |
| 35 |
""" |
| 36 |
cls.server_process_handler = utils.TestServerProcess(log=logger) |
| 37 |
|
| 38 |
cls.file_contents = b"junk data" |
| 39 |
cls.file_length = len(cls.file_contents) |
| 40 |
with tempfile.NamedTemporaryFile( |
| 41 |
dir=os.getcwd(), delete=False |
| 42 |
) as cls.target_file: |
| 43 |
cls.target_file.write(cls.file_contents) |
| 44 |
|
| 45 |
cls.url_prefix = ( |
| 46 |
f"http://{utils.TEST_HOST_ADDRESS}:" |
| 47 |
f"{cls.server_process_handler.port!s}" |
| 48 |
) |
| 49 |
target_filename = os.path.basename(cls.target_file.name) |
| 50 |
cls.url = f"{cls.url_prefix}/{target_filename}" |
| 51 |
|
| 52 |
@classmethod |
| 53 |
def tearDownClass(cls) -> None: |
| 54 |
# Stop server process and perform clean up. |
| 55 |
cls.server_process_handler.clean() |
| 56 |
os.remove(cls.target_file.name) |
| 57 |
|
| 58 |
def setUp(self) -> None: |
| 59 |
# Instantiate a concrete instance of FetcherInterface |
| 60 |
self.fetcher = Urllib3Fetcher() |
| 61 |
|
| 62 |
# Simple fetch. |
| 63 |
def test_fetch(self) -> None: |
| 64 |
with tempfile.TemporaryFile() as temp_file: |
| 65 |
for chunk in self.fetcher.fetch(self.url): |
| 66 |
temp_file.write(chunk) |
| 67 |
|
| 68 |
temp_file.seek(0) |
| 69 |
self.assertEqual(self.file_contents, temp_file.read()) |
| 70 |
|
| 71 |
# URL data downloaded in more than one chunk |
| 72 |
def test_fetch_in_chunks(self) -> None: |
| 73 |
# Set a smaller chunk size to ensure that the file will be downloaded |
| 74 |
# in more than one chunk |
| 75 |
self.fetcher.chunk_size = 4 |
| 76 |
|
| 77 |
# expected_chunks_count: 3 (depends on length of self.file_length) |
| 78 |
expected_chunks_count = math.ceil( |
| 79 |
self.file_length / self.fetcher.chunk_size |
| 80 |
) |
| 81 |
self.assertEqual(expected_chunks_count, 3) |
| 82 |
|
| 83 |
chunks_count = 0 |
| 84 |
with tempfile.TemporaryFile() as temp_file: |
| 85 |
for chunk in self.fetcher.fetch(self.url): |
| 86 |
temp_file.write(chunk) |
| 87 |
chunks_count += 1 |
| 88 |
|
| 89 |
temp_file.seek(0) |
| 90 |
self.assertEqual(self.file_contents, temp_file.read()) |
| 91 |
# Check that we calculate chunks as expected |
| 92 |
self.assertEqual(chunks_count, expected_chunks_count) |
| 93 |
|
| 94 |
# Incorrect URL parsing |
| 95 |
def test_url_parsing(self) -> None: |
| 96 |
with self.assertRaises(exceptions.DownloadError): |
| 97 |
self.fetcher.fetch("http://invalid/") |
| 98 |
|
| 99 |
# File not found error |
| 100 |
def test_http_error(self) -> None: |
| 101 |
with self.assertRaises(exceptions.DownloadHTTPError) as cm: |
| 102 |
self.url = f"{self.url_prefix}/non-existing-path" |
| 103 |
self.fetcher.fetch(self.url) |
| 104 |
self.assertEqual(cm.exception.status_code, 404) |
| 105 |
|
| 106 |
# Response read timeout error |
| 107 |
@patch.object(urllib3.PoolManager, "request") |
| 108 |
def test_response_read_timeout(self, mock_session_get: Mock) -> None: |
| 109 |
mock_response = Mock() |
| 110 |
mock_response.status = 200 |
| 111 |
attr = { |
| 112 |
"stream.side_effect": urllib3.exceptions.MaxRetryError( |
| 113 |
urllib3.connectionpool.ConnectionPool("localhost"), |
| 114 |
"", |
| 115 |
urllib3.exceptions.TimeoutError(), |
| 116 |
) |
| 117 |
} |
| 118 |
mock_response.configure_mock(**attr) |
| 119 |
mock_session_get.return_value = mock_response |
| 120 |
|
| 121 |
with self.assertRaises(exceptions.SlowRetrievalError): |
| 122 |
next(self.fetcher.fetch(self.url)) |
| 123 |
mock_response.stream.assert_called_once() |
| 124 |
|
| 125 |
# Read/connect session timeout error |
| 126 |
@patch.object( |
| 127 |
urllib3.PoolManager, |
| 128 |
"request", |
| 129 |
side_effect=urllib3.exceptions.MaxRetryError( |
| 130 |
urllib3.connectionpool.ConnectionPool("localhost"), |
| 131 |
"", |
| 132 |
urllib3.exceptions.TimeoutError(), |
| 133 |
), |
| 134 |
) |
| 135 |
def test_session_get_timeout(self, mock_session_get: Mock) -> None: |
| 136 |
with self.assertRaises(exceptions.SlowRetrievalError): |
| 137 |
self.fetcher.fetch(self.url) |
| 138 |
mock_session_get.assert_called_once() |
| 139 |
|
| 140 |
# Simple bytes download |
| 141 |
def test_download_bytes(self) -> None: |
| 142 |
data = self.fetcher.download_bytes(self.url, self.file_length) |
| 143 |
self.assertEqual(self.file_contents, data) |
| 144 |
|
| 145 |
# Download file smaller than required max_length |
| 146 |
def test_download_bytes_upper_length(self) -> None: |
| 147 |
data = self.fetcher.download_bytes(self.url, self.file_length + 4) |
| 148 |
self.assertEqual(self.file_contents, data) |
| 149 |
|
| 150 |
# Download a file bigger than expected |
| 151 |
def test_download_bytes_length_mismatch(self) -> None: |
| 152 |
with self.assertRaises(exceptions.DownloadLengthMismatchError): |
| 153 |
self.fetcher.download_bytes(self.url, self.file_length - 4) |
| 154 |
|
| 155 |
# Simple file download |
| 156 |
def test_download_file(self) -> None: |
| 157 |
with self.fetcher.download_file( |
| 158 |
self.url, self.file_length |
| 159 |
) as temp_file: |
| 160 |
temp_file.seek(0, io.SEEK_END) |
| 161 |
self.assertEqual(self.file_length, temp_file.tell()) |
| 162 |
|
| 163 |
# Download file smaller than required max_length |
| 164 |
def test_download_file_upper_length(self) -> None: |
| 165 |
with self.fetcher.download_file( |
| 166 |
self.url, self.file_length + 4 |
| 167 |
) as temp_file: |
| 168 |
temp_file.seek(0, io.SEEK_END) |
| 169 |
self.assertEqual(self.file_length, temp_file.tell()) |
| 170 |
|
| 171 |
# Download a file bigger than expected |
| 172 |
def test_download_file_length_mismatch(self) -> None: |
| 173 |
with ( |
| 174 |
self.assertRaises(exceptions.DownloadLengthMismatchError), |
| 175 |
self.fetcher.download_file(self.url, self.file_length - 4), |
| 176 |
): |
| 177 |
pass # we never get here as download_file() raises |
| 178 |
|
| 179 |
|
| 180 |
# Run unit test. |
| 181 |
if __name__ == "__main__": |
| 182 |
utils.configure_test_logging(sys.argv) |
| 183 |
unittest.main() |