Skip to contentSkip to conversation

Provide classes for building disk images with FS partitions

PATCH Superseded Simon Glass 2 participants 13 messages Feb 28 – Mar 2

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover Provide classes for building disk images with FS partitions

From: Simon Glass <[email protected]>

Refactor the test filesystem helper into a class-based design, reducing duplication and making it easier to create disk images for testing. Add a helper class for creating disk images with partition tables.

Convert a test over to use it. Provide a few other minor improvements as well.

Changes in v2:
- Split the quiet flag into a separate commit
- Fix fs_img to accept only a leaf name, always under persistent_data_dir
- Add new patch to split the quiet flag out of the previous patch
- Split the pylint fix into a separate commit
- Explain why setup_image() is left to later

Simon Glass (7):
test: fs_helper: Allow passing the image filename
test: fs_helper: Add a quiet flag to mk_fs()
test: Update comment for fs_helper.setup_image()
test: fs_helper: Drop the size_gran argument
test: Convert fs_helper to use a class
test: Add a helper class to create disk images
test: Convert test_efi_bootmgr to use FsHelper

 test/py/tests/fs_helper.py        | 310 +++++++++++++++++++++++++-----
 test/py/tests/test_efi_bootmgr.py |  38 ++--
 2 files changed, 273 insertions(+), 75 deletions(-)
Signature · 4 lines
2.43.0

base-commit: f6963fc232603007c661411fb31c57f1a9678a87
branch: testfs2
#1 lore raw

PATCH v2 1/7 test: fs_helper: Allow passing the image filename

From: Simon Glass <[email protected]>

The mk_fs() function always generates its own image filename from the prefix and fs_type. Some callers need to specify a custom leaf name while still keeping the image under the persistent-data directory.

Add an fs_img parameter that accepts a leaf filename. When provided, it is joined with persistent_data_dir instead of the default name.

---

Changes in v2:
- Split the quiet flag into a separate commit
- Fix fs_img to accept only a leaf name, always under persistent_data_dir

 test/py/tests/fs_helper.py | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
test/py/tests/fs_helper.py +7 -2
index b8a22b22806..bd9169b2a4d 100644
@@ -9,7 +9,8 @@ import re
 import os
 from subprocess import call, check_call, check_output, CalledProcessError
 
-def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000):
+def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
+          fs_img=None):
     """Create a file system volume
 
     Args:
@@ -19,11 +20,15 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000):
         prefix (str): Prefix string of volume's file name
         src_dir (str): Root directory to use, or None for none
         size_gran (int): Size granularity of file system image in bytes
+        fs_img (str or None): Leaf filename for image, or None to use a
+            default name. The image is always placed under
+            persistent_data_dir.
 
     Raises:
         CalledProcessError: if any error occurs when creating the filesystem
     """
-    fs_img = f'{prefix}.{fs_type}.img'
+    if not fs_img:
+        fs_img = f'{prefix}.{fs_type}.img'
     fs_img = os.path.join(config.persistent_data_dir, fs_img)
 
     if fs_type == 'fat12':
Signature · 1 line
2.43.0
Reviewed-by on v2 1/7
#2 lore raw

Re: [PATCH v2 1/7] test: fs_helper: Allow passing the image filename

Quoted 11 lines · Simon Glass

From: Simon Glass <[email protected]>

The mk_fs() function always generates its own image filename from the prefix and fs_type. Some callers need to specify a custom leaf name while still keeping the image under the persistent-data directory.

Add an fs_img parameter that accepts a leaf filename. When provided, it is joined with persistent_data_dir instead of the default name.

Signature · 1 line
Tom
#3 lore raw

PATCH v2 2/7 test: fs_helper: Add a quiet flag to mk_fs()

In reply to Simon Glass

From: Simon Glass <[email protected]>

In many cases callers only want to see warnings and errors from the filesystem-creation tools, not their normal output.

Add a quiet parameter to mk_fs() that suppresses the output of mkfs and switches mcopy from verbose to quiet mode.

---

Changes in v2:
- Add new patch to split the quiet flag out of the previous patch

 test/py/tests/fs_helper.py | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
test/py/tests/fs_helper.py +8 -3
index bd9169b2a4d..4b123ab0afd 100644
@@ -8,9 +8,10 @@
 import re
 import os
 from subprocess import call, check_call, check_output, CalledProcessError
+from subprocess import DEVNULL
 
 def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
-          fs_img=None):
+          fs_img=None, quiet=False):
     """Create a file system volume
 
     Args:
@@ -23,6 +24,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         fs_img (str or None): Leaf filename for image, or None to use a
             default name. The image is always placed under
             persistent_data_dir.
+        quiet (bool): Suppress non-error output
 
     Raises:
         CalledProcessError: if any error occurs when creating the filesystem
@@ -63,14 +65,17 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         check_call(f'rm -f {fs_img}', shell=True)
         check_call(f'truncate -s $(( {size_gran} * {count} )) {fs_img}',
                    shell=True)
-        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True)
+        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
+                   stdout=DEVNULL if quiet else None)
         if fs_type == 'ext4':
             sb_content = check_output(f'tune2fs -l {fs_img}',
                                       shell=True).decode()
             if 'metadata_csum' in sb_content:
                 check_call(f'tune2fs -O ^metadata_csum {fs_img}', shell=True)
         elif fs_lnxtype == 'vfat' and src_dir:
-            check_call(f'mcopy -i {fs_img} -vsmpQ {src_dir}/* ::/', shell=True)
+            flags = f"-smpQ{'' if quiet else 'v'}"
+            check_call(f'mcopy -i {fs_img} {flags} {src_dir}/* ::/',
+                       shell=True)
         elif fs_lnxtype == 'exfat' and src_dir:
             check_call(f'fattools cp {src_dir}/* {fs_img}', shell=True)
         return fs_img
Signature · 1 line
2.43.0
Reviewed-by on v2 2/7
#4 lore raw

Re: [PATCH v2 2/7] test: fs_helper: Add a quiet flag to mk_fs()

Quoted 9 lines · Simon Glass

From: Simon Glass <[email protected]>

In many cases callers only want to see warnings and errors from the filesystem-creation tools, not their normal output.

Add a quiet parameter to mk_fs() that suppresses the output of mkfs and switches mcopy from verbose to quiet mode.

Signature · 1 line
Tom
#5 lore raw

PATCH v2 3/7 test: Update comment for fs_helper.setup_image()

In reply to Simon Glass

From: Simon Glass <[email protected]>

This function actually allows creating two partitions now, so update its comment to match that.

---

(no changes since v1)

 test/py/tests/fs_helper.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
test/py/tests/fs_helper.py +1 -1
index 4b123ab0afd..47340295fbb 100644
@@ -85,7 +85,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
 
 def setup_image(ubman, devnum, part_type, img_size=20, second_part=False,
                 basename='mmc'):
-    """Create a disk image with a single partition
+    """Create a disk image with one or two partitions
 
     Args:
         ubman (ConsoleBase): Console to use
Signature · 1 line
2.43.0
#7 lore raw

PATCH v2 4/7 test: fs_helper: Drop the size_gran argument

In reply to Simon Glass

From: Simon Glass <[email protected]>

Nothing uses this argument, so make it a constant for now.

---

Changes in v2:
- Split the pylint fix into a separate commit

 test/py/tests/fs_helper.py | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
test/py/tests/fs_helper.py +7 -5
index 47340295fbb..72e18588288 100644
@@ -10,8 +10,11 @@ import os
 from subprocess import call, check_call, check_output, CalledProcessError
 from subprocess import DEVNULL
 
-def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
-          fs_img=None, quiet=False):
+# size_gran (int): Size granularity of file system image in bytes
+SIZE_GRAN = 1 << 20
+
+
+def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False):
     """Create a file system volume
 
     Args:
@@ -20,7 +23,6 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         size (int): Size of file system in bytes
         prefix (str): Prefix string of volume's file name
         src_dir (str): Root directory to use, or None for none
-        size_gran (int): Size granularity of file system image in bytes
         fs_img (str or None): Leaf filename for image, or None to use a
             default name. The image is always placed under
             persistent_data_dir.
@@ -55,7 +57,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
         elif fs_lnxtype != 'vfat' and fs_lnxtype != 'exfat':
             raise ValueError(f'src_dir not implemented for fs {fs_lnxtype}')
 
-    count = (size + size_gran - 1) // size_gran
+    count = (size + SIZE_GRAN - 1) // SIZE_GRAN
 
     # Some distributions do not add /sbin to the default PATH, where mkfs lives
     if '/sbin' not in os.environ["PATH"].split(os.pathsep):
@@ -63,7 +65,7 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
 
     try:
         check_call(f'rm -f {fs_img}', shell=True)
-        check_call(f'truncate -s $(( {size_gran} * {count} )) {fs_img}',
+        check_call(f'truncate -s $(( {SIZE_GRAN} * {count} )) {fs_img}',
                    shell=True)
         check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
                    stdout=DEVNULL if quiet else None)
Signature · 1 line
2.43.0
#8 lore raw

PATCH v2 5/7 test: Convert fs_helper to use a class

In reply to Simon Glass

From: Simon Glass <[email protected]>

It is somewhat inconvenient that callers to mk_fs() must create their own temporary directory. Convert it to a class so this can be handled automatically, using a context manager.

Rather than specifying the file size in bytes, use MB since it is rare to need a smaller file.

Update mk_fs() to use this new class.

---

(no changes since v1)

 test/py/tests/fs_helper.py | 209 +++++++++++++++++++++++++++----------
 1 file changed, 154 insertions(+), 55 deletions(-)
test/py/tests/fs_helper.py +154 -55
index 72e18588288..fac811f352e 100644
@@ -7,14 +7,158 @@
 
 import re
 import os
+import shutil
 from subprocess import call, check_call, check_output, CalledProcessError
 from subprocess import DEVNULL
+import tempfile
 
-# size_gran (int): Size granularity of file system image in bytes
-SIZE_GRAN = 1 << 20
 
+class FsHelper:
+    """Creating a filesystem containing test files
 
-def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False):
+    Usage:
+        with FsHelper(ubman.config, 'ext4', 10, 'mmc1') as fsh:
+            # create files in the self.srcdir directory
+            fsh.mk_fs()
+            # Now use the filesystem
+
+        # The filesystem and srcdir are erased after the 'with' statement.
+
+        To set the image filename:
+
+            with FsHelper(ubman.config, 'ext4', 10, 'mmc1') as fsh:
+                fsh.fs_img = 'myfile.img'
+                fsh.mk_fs()
+                ...
+
+        It is also possible to use an existing srcdir:
+
+            with FsHelper(ubman.config, 'fat32', 10, 'usb2') as fsh:
+                fsh.srcdir = src_dir
+                fsh.mk_fs()
+                ...
+
+    Properties:
+        fs_img (str): Filename for the filesystem image; this is set to a
+            default value but can be overwritten
+    """
+    def __init__(self, config, fs_type, size_mb, prefix):
+        """Set up a new object
+
+        Args:
+            config (u_boot_config): U-Boot configuration
+            fs_type (str): File system type: one of ext2, ext3, ext4, vfat,
+                fat12, fat16, fat32, exfat, fs_generic (which means vfat)
+            size_mb (int): Size of file system in MB
+            prefix (str): Prefix string of volume's file name
+        """
+        if ('fat' not in fs_type and 'ext' not in fs_type and
+             fs_type not in ['exfat', 'fs_generic']):
+            raise ValueError(f"Unsupported filesystem type '{fs_type}'")
+
+        self.config = config
+        self.fs_type = fs_type
+        self.size_mb = size_mb
+        self.prefix = prefix
+        self.quiet = True
+
+        # Use a default filename; the caller can adjust it
+        leaf = f'{prefix}.{fs_type}.img'
+        if config:
+            self.fs_img = os.path.join(config.persistent_data_dir, leaf)
+            if os.path.exists(self.fs_img):
+                os.remove(self.fs_img)
+        else:
+            self.fs_img = leaf
+
+        # Some distributions do not add /sbin to the default PATH, where mkfs
+        # lives
+        if '/sbin' not in os.environ["PATH"].split(os.pathsep):
+            os.environ["PATH"] += os.pathsep + '/sbin'
+
+        self.tmpdir = None
+        self.srcdir = None
+        self._do_cleanup = False
+
+    def _get_fs_args(self):
+        """Get the mkfs options and program to use
+
+        Returns:
+            tuple:
+                str: mkfs options, e.g. '-F 32' for fat32
+                str: mkfs program to use, e.g 'ext4' for ext4
+        """
+        if self.fs_type == 'fat12':
+            mkfs_opt = '-F 12'
+        elif self.fs_type == 'fat16':
+            mkfs_opt = '-F 16'
+        elif self.fs_type == 'fat32':
+            mkfs_opt = '-F 32'
+        elif self.fs_type.startswith('ext'):
+            mkfs_opt = f'-d {self.srcdir}'
+        else:
+            mkfs_opt = ''
+
+        if self.fs_type == 'exfat':
+            fs_lnxtype = 'exfat'
+        elif re.match('fat', self.fs_type) or self.fs_type == 'fs_generic':
+            fs_lnxtype = 'vfat'
+        else:
+            fs_lnxtype = self.fs_type
+        return mkfs_opt, fs_lnxtype
+
+    def mk_fs(self):
+        """Make a new filesystem and copy in the files"""
+        self.setup()
+        fs_img = self.fs_img
+        with open(fs_img, 'wb') as fsi:
+            fsi.truncate(self.size_mb << 20)
+        self._do_cleanup = True
+
+        mkfs_opt, fs_lnxtype = self._get_fs_args()
+        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
+                stdout=DEVNULL if self.quiet else None)
+
+        if self.fs_type.startswith('ext'):
+            # Disable metadata checksums which U-Boot does not support
+            check_call(f'tune2fs -O ^metadata_csum {fs_img}', shell=True)
+        elif fs_lnxtype == 'exfat' and self.srcdir:
+            check_call(f'fattools cp {self.srcdir}/* {fs_img}', shell=True)
+        elif self.srcdir and os.listdir(self.srcdir):
+            flags = f"-smpQ{'' if self.quiet else 'v'}"
+            check_call(f'mcopy -i {fs_img} {flags} {self.srcdir}/* ::/',
+                    shell=True)
+
+    def setup(self):
+        """Set up the srcdir ready to receive files"""
+        if not self.srcdir:
+            if self.config:
+                self.srcdir = os.path.join(self.config.persistent_data_dir,
+                                           f'{self.prefix}.{self.fs_type}.tmp')
+                if os.path.exists(self.srcdir):
+                    shutil.rmtree(self.srcdir)
+                os.mkdir(self.srcdir)
+            else:
+                self.tmpdir = tempfile.TemporaryDirectory('fs_helper')
+                self.srcdir = self.tmpdir.name
+
+    def cleanup(self):
+        """Remove created image"""
+        if self.tmpdir:
+            self.tmpdir.cleanup()
+        if self._do_cleanup:
+            os.remove(self.fs_img)
+
+    def __enter__(self):
+        self.setup()
+        return self
+
+    def __exit__(self, extype, value, traceback):
+        self.cleanup()
+
+
+def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
+          fs_img=None, quiet=False):
     """Create a file system volume
 
     Args:
@@ -31,59 +175,14 @@ def mk_fs(config, fs_type, size, prefix, src_dir=None, fs_img=None, quiet=False)
     Raises:
         CalledProcessError: if any error occurs when creating the filesystem
     """
-    if not fs_img:
-        fs_img = f'{prefix}.{fs_type}.img'
-    fs_img = os.path.join(config.persistent_data_dir, fs_img)
-
-    if fs_type == 'fat12':
-        mkfs_opt = '-F 12'
-    elif fs_type == 'fat16':
-        mkfs_opt = '-F 16'
-    elif fs_type == 'fat32':
-        mkfs_opt = '-F 32'
-    else:
-        mkfs_opt = ''
-
-    if fs_type == 'exfat':
-        fs_lnxtype = 'exfat'
-    elif re.match('fat', fs_type) or fs_type == 'fs_generic':
-        fs_lnxtype = 'vfat'
-    else:
-        fs_lnxtype = fs_type
-
-    if src_dir:
-        if fs_lnxtype == 'ext4':
-            mkfs_opt = mkfs_opt + ' -d ' + src_dir
-        elif fs_lnxtype != 'vfat' and fs_lnxtype != 'exfat':
-            raise ValueError(f'src_dir not implemented for fs {fs_lnxtype}')
-
-    count = (size + SIZE_GRAN - 1) // SIZE_GRAN
-
-    # Some distributions do not add /sbin to the default PATH, where mkfs lives
-    if '/sbin' not in os.environ["PATH"].split(os.pathsep):
-        os.environ["PATH"] += os.pathsep + '/sbin'
+    fsh = FsHelper(config, fs_type, size >> 20, prefix)
+    fsh.srcdir = src_dir
+    fsh.quiet = quiet
+    if fs_img:
+        fsh.fs_img = os.path.join(config.persistent_data_dir, fs_img)
+    fsh.mk_fs()
+    return fsh.fs_img
 
-    try:
-        check_call(f'rm -f {fs_img}', shell=True)
-        check_call(f'truncate -s $(( {SIZE_GRAN} * {count} )) {fs_img}',
-                   shell=True)
-        check_call(f'mkfs.{fs_lnxtype} {mkfs_opt} {fs_img}', shell=True,
-                   stdout=DEVNULL if quiet else None)
-        if fs_type == 'ext4':
-            sb_content = check_output(f'tune2fs -l {fs_img}',
-                                      shell=True).decode()
-            if 'metadata_csum' in sb_content:
-                check_call(f'tune2fs -O ^metadata_csum {fs_img}', shell=True)
-        elif fs_lnxtype == 'vfat' and src_dir:
-            flags = f"-smpQ{'' if quiet else 'v'}"
-            check_call(f'mcopy -i {fs_img} {flags} {src_dir}/* ::/',
-                       shell=True)
-        elif fs_lnxtype == 'exfat' and src_dir:
-            check_call(f'fattools cp {src_dir}/* {fs_img}', shell=True)
-        return fs_img
-    except CalledProcessError:
-        call(f'rm -f {fs_img}', shell=True)
-        raise
 
 def setup_image(ubman, devnum, part_type, img_size=20, second_part=False,
                 basename='mmc'):
Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH v2 5/7] test: Convert fs_helper to use a class

Quoted 5 lines · Simon Glass

From: Simon Glass <[email protected]>

It is somewhat inconvenient that callers to mk_fs() must create their own temporary directory. Convert it to a class so this can be handled automatically, using a context manager.

Instead how about:
Create a class around mk_fs (and later setup_image) to handle the common tasks of image creation. Many callers of fs_helper.mk_fs create their own scratch directories while users of fs_helper.setup_image rely on one being returned. Unify this by adding 'srcdir' as a field while converting to a class.

And I didn't try out a 'git show -w' to see if that makes it clear the underlying logic wasn't changed in mk_fs.

Signature · 1 line
Tom
#10 lore raw

PATCH v2 6/7 test: Add a helper class to create disk images

In reply to Simon Glass

From: Simon Glass <[email protected]>

Provide a way to create disk images which consist of multiple filesystem images.

Provide an option to use the current directory for images, instead of persistent-data directory. This makes it easy for C tests to locate the image.

The setup_image() function is used from a lot of places and that code itself needs some work, so this is left for a future series.

---

Changes in v2:
- Explain why setup_image() is left to later

 test/py/tests/fs_helper.py | 97 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 97 insertions(+)
test/py/tests/fs_helper.py +97 -0
index fac811f352e..0139a3ba523 100644
@@ -157,6 +157,103 @@ class FsHelper:
         self.cleanup()
 
 
+class DiskHelper:
+    """Helper class for creating disk images containing filesystems
+
+    Usage:
+        with DiskHelper(ubman.config, 0, 'mmc') as img, \
+                FsHelper(ubman.config, 'ext4', 1, 'mmc') as fsh:
+            # Write files to fsh.srcdir
+            ...
+
+            # Create the filesystem
+            fsh.mk_fs()
+
+            # Add this filesystem to the disk
+            img.add_fs(fsh, DiskHelper.VFAT)
+
+            # Add more filesystems as needed (add another 'with' clause)
+            ...
+
+            # Get the final disk image
+            data = img.create()
+    """
+
+    # Partition-type codes
+    VFAT  = 0xc
+    EXT4  = 0x83
+
+    def __init__(self, config, devnum, prefix, cur_dir=False):
+        """Set up a new disk image
+
+        Args:
+            config (u_boot_config): U-Boot configuration
+            devnum (int): Device number (for filename)
+            prefix (str): Prefix string of volume's file name
+            cur_dir (bool): True to put the file in the current directory,
+                instead of the persistent-data directory
+        """
+        self.fs_list = []
+        self.fname = os.path.join('' if cur_dir else config.persistent_data_dir,
+                                  f'{prefix}{devnum}.img')
+        self.remove_img = True
+        self._do_cleanup = False
+
+    def add_fs(self, fs_img, part_type, bootable=False):
+        """Add a new filesystem
+
+        Args:
+            fs_img (FsHelper): Filesystem to add
+            part_type (DiskHelper.VFAT or DiskHelper.EXT4): Partition type
+            bootable (bool): True to set the 'bootable' flag
+        """
+        self.fs_list.append([fs_img, part_type, bootable])
+
+    def create(self):
+        """Create the disk image
+
+        Create an image with a partition table and the filesystems
+        """
+        spec = ''
+        pos = 1   # Reserve 1MB for the partition table itself
+        for fsi, part_type, bootable in self.fs_list:
+            if spec:
+                spec += '\n'
+            spec += f'type={part_type:x}, size={fsi.size_mb}M, start={pos}M'
+            if bootable:
+                spec += ', bootable'
+            pos += fsi.size_mb
+
+        img_size = pos
+        try:
+            check_call(f'qemu-img create {self.fname} {img_size}M', shell=True)
+            self._do_cleanup = True
+            check_call(f'printf "{spec}" | sfdisk {self.fname}', shell=True)
+        except CalledProcessError:
+            os.remove(self.fname)
+            raise
+
+        pos = 1   # Reserve 1MB for the partition table itself
+        for fsi, part_type, bootable in self.fs_list:
+            check_call(
+                f'dd if={fsi.fs_img} of={self.fname} bs=1M seek={pos} conv=notrunc',
+                shell=True)
+            pos += fsi.size_mb
+        return self.fname
+
+    def cleanup(self):
+        """Remove created file"""
+        if self._do_cleanup:
+            os.remove(self.fname)
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, extype, value, traceback):
+        if self.remove_img:
+            self.cleanup()
+
+
 def mk_fs(config, fs_type, size, prefix, src_dir=None, size_gran = 0x100000,
           fs_img=None, quiet=False):
     """Create a file system volume
Signature · 1 line
2.43.0
#11 lore raw

Re: [PATCH v2 6/7] test: Add a helper class to create disk images

Quoted 8 lines · Simon Glass

From: Simon Glass <[email protected]>

Provide a way to create disk images which consist of multiple filesystem images.

Provide an option to use the current directory for images, instead of persistent-data directory. This makes it easy for C tests to locate the image.

This is something we don't want, however. We need to not be adding more files to the source directory as part of tests. This is a general bad practice.

And in the likely event that you're going to note that python is slow, please try your suggestion of 2019[1] and see about making U-Boot be a python library, and if that doesn't work, look for other ways to speed up python? Given all of the real time machine learning demos that are built upon Python, it seems like piping data around fast should be something that can be solved.

Quoted 2 lines

The setup_image() function is used from a lot of places and that code itself needs some work, so this is left for a future series.

You're back to editoralizing in commit messages, and since you do provide a helper for mk_fs you also simply could for setup_image.

[1]: https://lists.denx.de/pipermail/u-boot/2019-October/388732.html

Signature · 1 line
Tom
#12 lore raw

PATCH v2 7/7 test: Convert test_efi_bootmgr to use FsHelper

In reply to Simon Glass

From: Simon Glass <[email protected]>

As an example of how to use the helper, use it to simplify this test.

---

(no changes since v1)

 test/py/tests/test_efi_bootmgr.py | 38 ++++++++++++-------------------
 1 file changed, 14 insertions(+), 24 deletions(-)
test/py/tests/test_efi_bootmgr.py +14 -24
index 4c10cbdf17d..7d1f3f16d00 100644
@@ -5,7 +5,7 @@
 import shutil
 import pytest
 from subprocess import call, check_call, CalledProcessError
-from tests import fs_helper
+from tests.fs_helper import DiskHelper, FsHelper
 
 @pytest.mark.boardspec('sandbox')
 @pytest.mark.buildconfigspec('cmd_efidebug')
@@ -20,22 +20,19 @@ def test_efi_bootmgr(ubman):
     Args:
         ubman -- U-Boot console
     """
-    try:
-        efi_bootmgr_data, mnt = fs_helper.setup_image(ubman, 0, 0xc,
-                                                      basename='test_efi_bootmgr')
-
-        with open(mnt + '/initrd-1.img', 'w', encoding = 'ascii') as file:
-            file.write("initrd 1")
-
-        with open(mnt + '/initrd-2.img', 'w', encoding = 'ascii') as file:
-            file.write("initrd 2")
-
-        shutil.copyfile(ubman.config.build_dir + '/lib/efi_loader/initrddump.efi',
-                        mnt + '/initrddump.efi')
-
-        fsfile = fs_helper.mk_fs(ubman.config, 'vfat', 0x100000,
-                                 'test_efi_bootmgr', mnt)
-        check_call(f'dd if={fsfile} of={efi_bootmgr_data} bs=1M seek=1', shell=True)
+    with DiskHelper(ubman.config, 0, 'test_efi_bootmgr') as img, \
+            FsHelper(ubman.config, 'vfat', 1, 'test_efi_bootmgr') as fsh:
+        with open(f'{fsh.srcdir}/initrd-1.img', 'w', encoding = 'ascii') as outf:
+            outf.write("initrd 1")
+        with open(f'{fsh.srcdir}/initrd-2.img', 'w', encoding = 'ascii') as outf:
+            outf.write("initrd 2")
+        shutil.copyfile(
+            ubman.config.build_dir + '/lib/efi_loader/initrddump.efi',
+            f'{fsh.srcdir}/initrddump.efi')
+        fsh.mk_fs()
+
+        img.add_fs(fsh, DiskHelper.VFAT)
+        efi_bootmgr_data = img.create()
 
         ubman.run_command(cmd = f'host bind 0 {efi_bootmgr_data}')
 
@@ -61,10 +58,3 @@ def test_efi_bootmgr(ubman):
 
         ubman.run_command(cmd = 'efidebug boot rm 0001')
         ubman.run_command(cmd = 'efidebug boot rm 0002')
-    except CalledProcessError as err:
-        pytest.skip('Preparing test_efi_bootmgr image failed')
-        call('rm -f %s' % efi_bootmgr_data, shell=True)
-        return
-    finally:
-        call('rm -rf %s' % mnt, shell=True)
-        call('rm -f %s' % efi_bootmgr_data, shell=True)
Signature · 1 line
2.43.0