[PATCH 05/11] tests/functional: Implement fetch_asset() method for downloading assets

Thomas Huth posted 11 patches 2 months ago
Maintainers: "Alex Bennée" <alex.bennee@linaro.org>, "Philippe Mathieu-Daudé" <philmd@linaro.org>, Thomas Huth <thuth@redhat.com>, Wainer dos Santos Moschetta <wainersm@redhat.com>, Beraldo Leal <bleal@redhat.com>, Paolo Bonzini <pbonzini@redhat.com>, Antony Pavlov <antonynpavlov@gmail.com>, Peter Maydell <peter.maydell@linaro.org>, Michael Rolnik <mrolnik@gmail.com>, Song Gao <gaosong@loongson.cn>, Huacai Chen <chenhuacai@kernel.org>, Jiaxun Yang <jiaxun.yang@flygoat.com>, Akihiko Odaki <akihiko.odaki@daynix.com>, Sriram Yagnaraman <sriram.yagnaraman@ericsson.com>, Halil Pasic <pasic@linux.ibm.com>, Christian Borntraeger <borntraeger@linux.ibm.com>, Eric Farman <farman@linux.ibm.com>, Nina Schoetterl-Glausch <nsg@linux.ibm.com>, Mark Cave-Ayland <mark.cave-ayland@ilande.co.uk>
There is a newer version of this series
[PATCH 05/11] tests/functional: Implement fetch_asset() method for downloading assets
Posted by Thomas Huth 2 months ago
In the new python test framework, we cannot use the fetch_asset()
function from Avocado anymore, so we have to provide our own
implementation now instead. Thus add such a function based on the
urllib python module for this purpose.

Signed-off-by: Thomas Huth <thuth@redhat.com>
---
 tests/functional/qemu_test/__init__.py | 36 ++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/tests/functional/qemu_test/__init__.py b/tests/functional/qemu_test/__init__.py
index e73705d40a..77c3b14d34 100644
--- a/tests/functional/qemu_test/__init__.py
+++ b/tests/functional/qemu_test/__init__.py
@@ -11,6 +11,8 @@
 # This work is licensed under the terms of the GNU GPL, version 2 or
 # later.  See the COPYING file in the top-level directory.
 
+import hashlib
+import urllib.request
 import logging
 import os
 import pycotap
@@ -23,6 +25,7 @@
 import unittest
 
 from pathlib import Path
+from shutil import copyfileobj
 from qemu.machine import QEMUMachine
 from qemu.utils import (get_info_usernet_hostfwd_port, kvm_available,
                         tcg_available)
@@ -215,6 +218,39 @@ def setUp(self, bin_prefix):
         if not os.path.exists(self.workdir):
             os.makedirs(self.workdir)
 
+    def check_hash(self, file_name, expected_hash):
+        if not expected_hash:
+            return True
+        if len(expected_hash) == 40:
+            sum_prog = 'sha1sum'
+        elif len(expected_hash) == 64:
+            sum_prog = 'sha256sum'
+        elif len(expected_hash) == 128:
+            sum_prog = 'sha512sum'
+        else:
+            raise Exception("unknown hash type")
+        checksum = subprocess.check_output([sum_prog, file_name]).split()[0]
+        return expected_hash == checksum.decode("utf-8")
+
+    def fetch_asset(self, url, asset_hash):
+        cache_dir = os.path.expanduser("~/.cache/qemu/download")
+        if not os.path.exists(cache_dir):
+            os.makedirs(cache_dir)
+        fname = os.path.join(cache_dir,
+                             hashlib.sha256(url.encode("utf-8")).hexdigest())
+        if os.path.exists(fname) and self.check_hash(fname, asset_hash):
+            return fname
+        self.log.info("Downloading %s to %s...", url, fname)
+        dl_fname = fname + ".download"
+        with urllib.request.urlopen(url) as src:
+            with open(dl_fname, "wb+") as dst:
+                copyfileobj(src, dst)
+        if not self.check_hash(dl_fname, asset_hash):
+            os.remove(dl_fname)
+            raise Exception("Hash of " + url + " does not match")
+        os.rename(dl_fname, fname)
+        return fname
+
     def main():
         tr = pycotap.TAPTestRunner(message_log = pycotap.LogMode.LogToError,
                                    test_output_log = pycotap.LogMode.LogToError)
-- 
2.45.2
Re: [PATCH 05/11] tests/functional: Implement fetch_asset() method for downloading assets
Posted by Daniel P. Berrangé 2 months ago
On Tue, Jul 16, 2024 at 01:26:08PM +0200, Thomas Huth wrote:
> In the new python test framework, we cannot use the fetch_asset()
> function from Avocado anymore, so we have to provide our own
> implementation now instead. Thus add such a function based on the
> urllib python module for this purpose.
> 
> Signed-off-by: Thomas Huth <thuth@redhat.com>
> ---
>  tests/functional/qemu_test/__init__.py | 36 ++++++++++++++++++++++++++
>  1 file changed, 36 insertions(+)
> 
> diff --git a/tests/functional/qemu_test/__init__.py b/tests/functional/qemu_test/__init__.py
> index e73705d40a..77c3b14d34 100644
> --- a/tests/functional/qemu_test/__init__.py
> +++ b/tests/functional/qemu_test/__init__.py
> @@ -11,6 +11,8 @@
>  # This work is licensed under the terms of the GNU GPL, version 2 or
>  # later.  See the COPYING file in the top-level directory.
>  
> +import hashlib
> +import urllib.request
>  import logging
>  import os
>  import pycotap
> @@ -23,6 +25,7 @@
>  import unittest
>  
>  from pathlib import Path
> +from shutil import copyfileobj
>  from qemu.machine import QEMUMachine
>  from qemu.utils import (get_info_usernet_hostfwd_port, kvm_available,
>                          tcg_available)
> @@ -215,6 +218,39 @@ def setUp(self, bin_prefix):
>          if not os.path.exists(self.workdir):
>              os.makedirs(self.workdir)
>  
> +    def check_hash(self, file_name, expected_hash):
> +        if not expected_hash:
> +            return True
> +        if len(expected_hash) == 40:
> +            sum_prog = 'sha1sum'
> +        elif len(expected_hash) == 64:
> +            sum_prog = 'sha256sum'
> +        elif len(expected_hash) == 128:
> +            sum_prog = 'sha512sum'
> +        else:
> +            raise Exception("unknown hash type")
> +        checksum = subprocess.check_output([sum_prog, file_name]).split()[0]
> +        return expected_hash == checksum.decode("utf-8")
> +
> +    def fetch_asset(self, url, asset_hash):
> +        cache_dir = os.path.expanduser("~/.cache/qemu/download")
> +        if not os.path.exists(cache_dir):
> +            os.makedirs(cache_dir)
> +        fname = os.path.join(cache_dir,
> +                             hashlib.sha256(url.encode("utf-8")).hexdigest())
> +        if os.path.exists(fname) and self.check_hash(fname, asset_hash):
> +            return fname
> +        self.log.info("Downloading %s to %s...", url, fname)
> +        dl_fname = fname + ".download"
> +        with urllib.request.urlopen(url) as src:
> +            with open(dl_fname, "wb+") as dst:
> +                copyfileobj(src, dst)

For cleanliness we should probably wrap this and delete the file on
error, eg

   try:
     with open(dl_fname,....) as dst
        ....
   except:
     os.remove(dl_fname)
     raise

> +        if not self.check_hash(dl_fname, asset_hash):
> +            os.remove(dl_fname)
> +            raise Exception("Hash of " + url + " does not match")
> +        os.rename(dl_fname, fname)
> +        return fname
> +
>      def main():
>          tr = pycotap.TAPTestRunner(message_log = pycotap.LogMode.LogToError,
>                                     test_output_log = pycotap.LogMode.LogToError)
> -- 
> 2.45.2
> 

With regards,
Daniel
-- 
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|