Skip to content

Commit 783a85b

Browse files
authored
Don't obfuscate URLError (#8)
1 parent 48c868d commit 783a85b

2 files changed

Lines changed: 36 additions & 4 deletions

File tree

ml_datasets/test/test_util.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
from urllib.error import HTTPError, URLError
3+
from ml_datasets.util import get_file
4+
5+
6+
def test_get_file_domain_resolution_fails():
7+
with pytest.raises(
8+
URLError, match=r"test_non_existent_file.*(not known|getaddrinfo failed)"
9+
):
10+
get_file(
11+
"non_existent_file.txt",
12+
"http://test_notexist.wth/test_non_existent_file.txt"
13+
)
14+
15+
16+
def test_get_file_404_file_not_found():
17+
with pytest.raises(HTTPError, match="test_non_existent_file.*404.*Not Found") as e:
18+
get_file(
19+
"non_existent_file.txt",
20+
"http://google.com/test_non_existent_file.txt"
21+
)
22+
assert e.value.code == 404
23+
# Suppress pytest.PytestUnraisableExceptionWarning:
24+
# Exception ignored while calling deallocator
25+
# This questionable design quirk comes from urllib.request.urlretrieve,
26+
# so we shouldn't shim around it.
27+
e.value.close()

ml_datasets/util.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,20 @@ def dl_progress(count, block_size, total_size):
3737
else:
3838
progbar.update(block_size)
3939

40-
error_msg = "URL fetch failure on {}: {} -- {}"
4140
if not os.path.exists(fpath):
4241
try:
4342
try:
4443
urlretrieve(origin, fpath, dl_progress)
45-
except URLError as e:
46-
raise Exception(error_msg.format(origin, e.errno, e.reason))
44+
# Enrich download exceptions with full file name
45+
# HTTPError is a subclass of URLError, so it must be caught first
4746
except HTTPError as e:
48-
raise Exception(error_msg.format(origin, e.code, e.msg))
47+
error_msg = "URL fetch failure on {} : {} -- {}"
48+
e.msg = error_msg.format(origin, e.code, e.msg)
49+
raise
50+
except URLError as e:
51+
error_msg = "URL fetch failure on {} -- {}"
52+
e.reason = error_msg.format(origin, e.reason)
53+
raise
4954
except (Exception, KeyboardInterrupt):
5055
if os.path.exists(fpath):
5156
os.remove(fpath)

0 commit comments

Comments
 (0)