Best Python code snippet using lisa_python
hv_module.py
Source:hv_module.py  
...48            raise SkippedException("This test case requires LIS to be installed")49        modinfo = node.tools[Modinfo]50        lis_driver = node.tools[LisDriver]51        lis_version = lis_driver.get_version()52        hv_modules = self._get_not_built_in_modules(node)53        for module in hv_modules:54            module_version = VersionInfo.parse(modinfo.get_version(module))55            assert_that(module_version).described_as(56                f"Version of {module} does not match LIS version"57            ).is_equal_to(lis_version)58    @TestCaseMetadata(59        description="""60        This test case will ensure all necessary hv_modules are present in61        initrd. This is achieved by62        1. Skipping any modules that are loaded directly in the kernel63        2. Find the path of initrd file64        3. Use lsinitrd tool to check whether a necessary module is missing65        """,66        priority=2,67    )68    def verify_initrd_modules(self, node: Node) -> None:69        # 1) Takes all of the necessary modules and removes70        #    those that are statically loaded into the kernel71        all_necessary_hv_modules_file_names = {72            "hv_storvsc": "hv_storvsc.ko",73            "hv_netvsc": "hv_netvsc.ko",74            "hv_vmbus": "hv_vmbus.ko",75            "hid_hyperv": "hid-hyperv.ko",76            "hyperv_keyboard": "hyperv-keyboard.ko",77        }78        skip_modules = self._get_built_in_modules(node)79        hv_modules_file_names = {80            k: v81            for (k, v) in all_necessary_hv_modules_file_names.items()82            if k not in skip_modules83        }84        # 2) Find the path of initrd85        uname = node.tools[Uname]86        kernel_version = uname.get_linux_information().kernel_version_raw87        find = node.tools[Find]88        initrd_possible_file_names = [89            f"initrd-{kernel_version}",90            f"initramfs-{kernel_version}.img",91            f"initrd.img-{kernel_version}",92        ]93        initrd_file_path = ""94        for file_name in initrd_possible_file_names:95            result = find.find_files(node.get_pure_path("/boot"), file_name, sudo=True)96            if result and result[0]:97                initrd_file_path = result[0]98                break99        # 3) Use lsinitrd to check whether a necessary module100        #    is missing.101        lsinitrd = node.tools[Lsinitrd]102        missing_modules = []103        for module in hv_modules_file_names:104            if not lsinitrd.has_module(105                module_file_name=hv_modules_file_names[module],106                initrd_file_path=initrd_file_path,107            ):108                missing_modules.append(module)109        assert_that(missing_modules).described_as(110            "Required Hyper-V modules are missing from initrd."111        ).is_length(0)112    def _get_built_in_modules(self, node: Node) -> List[str]:113        """114        Returns the hv_modules that are directly loaded into the kernel and115        therefore would not show up in lsmod or be needed in initrd.116        """117        hv_modules_configuration = {118            "hv_storvsc": "CONFIG_HYPERV_STORAGE",119            "hv_netvsc": "CONFIG_HYPERV_NET",120            "hv_vmbus": "CONFIG_HYPERV",121            "hv_utils": "CONFIG_HYPERV_UTILS",122            "hid_hyperv": "CONFIG_HID_HYPERV_MOUSE",123            "hv_balloon": "CONFIG_HYPERV_BALLOON",124            "hyperv_keyboard": "CONFIG_HYPERV_KEYBOARD",125        }126        modules = []127        for module in hv_modules_configuration:128            if node.tools[KernelConfig].is_built_in(hv_modules_configuration[module]):129                modules.append(module)130        return modules131    @TestCaseMetadata(132        description="""133        This test case will134        1. Verify the presence of all Hyper V drivers using lsmod135           to look for the drivers not directly loaded into the kernel.136        """,137        priority=1,138    )139    def verify_hyperv_modules(self, log: Logger, node: Node) -> None:140        hv_modules = self._get_not_built_in_modules(node)141        distro_version = node.os.information.version142        # Some versions of RHEL and CentOS have the LIS package installed143        #   which includes extra drivers144        if isinstance(node.os, Redhat):145            modprobe = node.tools[Modprobe]146            lis_installed = node.os.package_exists("microsoft-hyper-v")147            if lis_installed:148                hv_modules.append("pci_hyperv")149                modprobe.run("pci_hyperv", sudo=True)150            if (151                distro_version >= "7.3.0" or distro_version < "7.5.0"152            ) and lis_installed:153                hv_modules.append("mlx4_en")154                modprobe.run("mlx4_en", sudo=True)155        # Counts the Hyper V drivers loaded as modules156        missing_modules = []157        lsmod = node.tools[Lsmod]158        for module in hv_modules:159            if lsmod.module_exists(module):160                log.info(f"Module {module} present")161            else:162                log.error(f"Module {module} absent")163                missing_modules.append(module)164        assert_that(missing_modules).described_as(165            "Not all Hyper V drivers are present."166        ).is_length(0)167    @TestCaseMetadata(168        description="""169        This test case will reload hyper-v modules as a stress test.170        """,171        priority=1,172        requirement=simple_requirement(173            min_core_count=4,174        ),175    )176    def reload_hyperv_modules(self, case_name: str, log: Logger, node: Node) -> None:177        # Constants178        module = "hv_netvsc"179        loop_count = 100180        if isinstance(node.os, Redhat):181            try:182                log.debug("Checking LIS installation before reload.")183                node.tools[LisDriver]184            except Exception:185                log.debug("Updating LIS failed. Moving on to attempt reload.")186        if module not in self._get_not_built_in_modules(node):187            raise SkippedException(188                f"{module} is loaded statically into the "189                "kernel and therefore can not be reloaded"190            )191        result = node.execute(192            ("for i in $(seq 1 %i); do " % loop_count)193            + f"modprobe -r -v {module}; modprobe -v {module}; "194            "done; sleep 1; "195            "ip link set eth0 down; ip link set eth0 up; dhclient eth0",196            sudo=True,197            shell=True,198        )199        if "is in use" in result.stdout:200            raise SkippedException(201                f"Module {module} is in use so it cannot be reloaded"202            )203        assert_that(result.stdout.count("rmmod")).described_as(204            f"Expected {module} to be removed {loop_count} times"205        ).is_equal_to(loop_count)206        assert_that(result.stdout.count("insmod")).described_as(207            f"Expected {module} to be inserted {loop_count} times"208        ).is_equal_to(loop_count)209    def _get_not_built_in_modules(self, node: Node) -> List[str]:210        """211        Returns the hv_modules that are not directly loaded into the kernel and212        therefore would be expected to show up in lsmod.213        """214        hv_modules_configuration = {215            "hv_storvsc": "CONFIG_HYPERV_STORAGE",216            "hv_netvsc": "CONFIG_HYPERV_NET",217            "hv_vmbus": "CONFIG_HYPERV",218            "hv_utils": "CONFIG_HYPERV_UTILS",219            "hid_hyperv": "CONFIG_HID_HYPERV_MOUSE",220            "hv_balloon": "CONFIG_HYPERV_BALLOON",221            "hyperv_keyboard": "CONFIG_HYPERV_KEYBOARD",222        }223        modules = []...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!!
