Skip to content

Commit 6e1628d

Browse files
committed
Fix urlopen() for Python 2 in runqemu.py
`get_metadata_from_url()` previousl fell back to urllib.urlopen() on HTTPErrors, due to its overly wide `except` (never catch `Exception`!), which leads to unnecessarily long and confusing backtraces. Other places did not have a Python 2 fallback at all. Directly import the `urlopen` function from the respective module to simplify the code. Also drop the unused `urllib.parse` import.
1 parent 77544b4 commit 6e1628d

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

src/tox_lsr/test_scripts/runqemu.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
import traceback
1818

1919
try:
20-
import urllib.parse
21-
import urllib.request
20+
from urllib.request import urlopen
2221
except ImportError:
23-
import urllib
22+
# Python 2
23+
from urllib import urlopen
2424
from contextlib import contextmanager
2525

2626
import yaml
@@ -149,12 +149,8 @@ def origurl(path):
149149

150150
def get_metadata_from_url(url, metadata_key):
151151
"""Get metadata from given url."""
152-
try:
153-
with urllib.request.urlopen(url) as url_response: # nosec
154-
return url_response.getheader(metadata_key)
155-
except Exception:
156-
with urllib.urlopen(url) as url_response: # nosec
157-
return url_response.getheader(metadata_key)
152+
with urlopen(url) as url_response: # nosec
153+
return url_response.getheader(metadata_key)
158154

159155

160156
def get_inventory_script(inventory):
@@ -164,7 +160,7 @@ def get_inventory_script(inventory):
164160
os.environ["TOX_WORK_DIR"], "standard-inventory-qcow2"
165161
)
166162
try:
167-
with urllib.request.urlopen( # nosec
163+
with urlopen( # nosec
168164
inventory # nosec
169165
) as url_response: # nosec
170166
with open(inventory_tempfile, "wb") as inf:
@@ -211,7 +207,7 @@ def fetch_image(url, cache, label):
211207

212208
image_tempfile = tempfile.NamedTemporaryFile(dir=cache, delete=False)
213209
try:
214-
request = urllib.request.urlopen(url) # nosec
210+
request = urlopen(url) # nosec
215211
shutil.copyfileobj(request, image_tempfile)
216212
request.close()
217213
except Exception: # pylint: disable=broad-except
@@ -292,7 +288,7 @@ def centoshtml2image(url, desiredarch):
292288
logging.error("Could not determine CentOS version from %s", url)
293289
return ""
294290

295-
page = urllib.request.urlopen(url) # nosec
291+
page = urlopen(url) # nosec
296292
tree = BeautifulSoup(page.read(), "html.parser")
297293
imagelist = [
298294
td.a["href"]

0 commit comments

Comments
 (0)