Best Python code snippet using autotest_python
fsdev_disks.py
Source:fsdev_disks.py  
...108                        'fs_opts': fsopts,109                        'fs_mkfs': fsmkfs,110                        'mounted': mstat})111    return hd_list112def mkfs_all_disks(job, disk_list, fs_type, fs_makeopt, fs_mnt_opt):113    """114    Prepare all the drives in 'disk_list' for testing. For each disk this means115    unmounting any mount points that use the disk, running mkfs with 'fs_type'116    as the file system type and 'fs_makeopt' as the 'mkfs' options, and finally117    remounting the freshly formatted drive using the flags in 'fs_mnt_opt'.118    """119    for disk in disk_list:120        # For now, ext4 isn't quite ready for prime time121        if fs_type == "ext4":122            fs_type = "ext4dev"123        # Grab the device and mount paths for the drive124        dev_path = os.path.join('/dev', disk["device"])125        mnt_path = disk['mountpt']126        # Create a file system instance127        try:128            fs = job.filesystem(device=dev_path, mountpoint=mnt_path)129        except Exception:130            raise Exception("Could not create a filesystem on '%s'" % dev_path)131        # Make sure the volume is unmounted132        if disk["mounted"]:133            try:134                fs.unmount(mnt_path)135            except Exception as info:136                raise Exception("umount failed: exception = %s, args = %s" %137                                (sys.exc_info()[0], info.args))138            except Exception:139                raise Exception("Could not unmount device ", dev_path)140        # Is the drive already formatted with the right file system?141        skip_mkfs = match_fs(disk, dev_path, fs_type, fs_makeopt)142        # Next step is to create a fresh file system (if we need to)143        try:144            if not skip_mkfs:145                fs.mkfs(fstype=fs_type, args=fs_makeopt)146        except Exception:147            raise Exception("Could not 'mkfs " + "-t " + fs_type + " " +148                            fs_makeopt + " " + dev_path + "'")149        # Mount the drive with the appropriate FS options150        try:151            opts = ""152            if fs_mnt_opt != "":153                opts += " -o " + fs_mnt_opt154            fs.mount(mountpoint=mnt_path, fstype=fs_type, args=opts)155        except NameError as info:156            raise Exception("mount name error: %s" % info)157        except Exception as info:158            raise Exception("mount failed: exception = %s, args = %s" %159                            (type(info), info.args))160        # If we skipped mkfs we need to wipe the partition clean161        if skip_mkfs:162            fs.wipe()163        # Record the new file system type and options in the disk list164        disk["mounted"] = True165        disk["fs_type"] = fs_type166        disk["fs_mkfs"] = fs_makeopt167        disk["fs_opts"] = fs_mnt_opt168    # Try to wipe the file system slate clean169    utils.drop_caches()170# XXX(gps): Remove this code once refactoring is complete to get rid of these171# nasty test description strings.172def _legacy_str_to_test_flags(fs_desc_string):173    """Convert a legacy FS_LIST string into a partition.FsOptions instance."""174    match = re.search('(.*?)/(.*?)/(.*?)/(.*)$', fs_desc_string.strip())175    if not match:176        raise ValueError('unrecognized FS list entry %r' % fs_desc_string)177    flags_obj = partition.FsOptions(fstype=match.group(1).strip(),178                                    mkfs_flags=match.group(2).strip(),179                                    mount_options=match.group(3).strip(),180                                    fs_tag=match.group(4).strip())181    return flags_obj182def prepare_disks(job, fs_desc, disk1_only=False, disk_list=None):183    """184    Prepare drive(s) to contain the file system type / options given in the185    description line 'fs_desc'. When 'disk_list' is not None, we prepare all186    the drives in that list; otherwise we pick the first available data drive187    (which is usually hdc3) and prepare just that one drive.188    Args:189      fs_desc: A partition.FsOptions instance describing the test -OR- a190          legacy string describing the same in '/' separated format:191              'fstype / mkfs opts / mount opts / short name'.192      disk1_only: Boolean, defaults to False.  If True, only test the first193          disk.194      disk_list: A list of disks to prepare.  If None is given we default to195          asking get_disk_list().196    Returns:197      (mount path of the first disk, short name of the test, list of disks)198      OR (None, '', None) if no fs_desc was given.199    """200    # Special case - do nothing if caller passes no description.201    if not fs_desc:202        return (None, '', None)203    if not isinstance(fs_desc, partition.FsOptions):204        fs_desc = _legacy_str_to_test_flags(fs_desc)205    # If no disk list was given, we'll get it ourselves206    if not disk_list:207        disk_list = get_disk_list()208    # Make sure we have the appropriate 'mkfs' binary for the file system209    mkfs_bin = 'mkfs.' + fs_desc.fstype210    if fs_desc.fstype == 'ext4':211        mkfs_bin = 'mkfs.ext4dev'212    try:213        utils.system('which ' + mkfs_bin)214    except Exception:215        try:216            mkfs_bin = os.path.join(job.toolsdir, mkfs_bin)217            utils.system('cp -ufp %s /sbin' % mkfs_bin)218        except Exception:219            raise error.TestError('No mkfs binary available for ' +220                                  fs_desc.fstype)221    # For 'ext4' we need to add '-E test_fs' to the mkfs options222    if fs_desc.fstype == 'ext4':223        fs_desc.mkfs_flags += ' -E test_fs'224    # If the caller only needs one drive, grab the first one only225    if disk1_only:226        disk_list = disk_list[0:1]227    # We have all the info we need to format the drives228    mkfs_all_disks(job, disk_list, fs_desc.fstype,229                   fs_desc.mkfs_flags, fs_desc.mount_options)230    # Return(mount path of the first disk, test tag value, disk_list)231    return (disk_list[0]['mountpt'], fs_desc.fs_tag, disk_list)232def restore_disks(job, restore=False, disk_list=None):233    """234    Restore ext2 on the drives in 'disk_list' if 'restore' is True; when235    disk_list is None, we do nothing.236    """237    if restore and disk_list is not None:238        prepare_disks(job, 'ext2 / -q -i20480 -m1 / / restore_ext2',239                           disk1_only=False,240                           disk_list=disk_list)241def wipe_disks(job, disk_list):242    """...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
