Best Python code snippet using autotest_python
base_sysinfo.py
Source:base_sysinfo.py  
...117                utils.run('gzip -9 "%s"' % logf_path, ignore_status=True,118                          verbose=False)119class base_sysinfo(object):120    def __init__(self, job_resultsdir):121        self.sysinfodir = self._get_sysinfodir(job_resultsdir)122        # pull in the post-test logs to collect123        self.test_loggables = set()124        for cmd in _DEFAULT_COMMANDS_TO_LOG_PER_TEST:125            self.test_loggables.add(command(cmd))126        for filename in _DEFAULT_FILES_TO_LOG_PER_TEST:127            self.test_loggables.add(logfile(filename))128        # pull in the EXTRA post-boot logs to collect129        self.boot_loggables = set()130        for cmd in _DEFAULT_COMMANDS_TO_LOG_PER_BOOT:131            self.boot_loggables.add(command(cmd))132        for filename in _DEFAULT_FILES_TO_LOG_PER_BOOT:133            self.boot_loggables.add(logfile(filename))134        # pull in the pre test iteration logs to collect135        self.before_iteration_loggables = set()136        for cmd in _DEFAULT_COMMANDS_TO_LOG_BEFORE_ITERATION:137            self.before_iteration_loggables.add(138                command(cmd, logf=cmd.replace(" ", "_") + '.before'))139        for fname in _DEFAULT_FILES_TO_LOG_BEFORE_ITERATION:140            self.before_iteration_loggables.add(141                logfile(fname, logf=os.path.basename(fname) + '.before'))142        # pull in the post test iteration logs to collect143        self.after_iteration_loggables = set()144        for cmd in _DEFAULT_COMMANDS_TO_LOG_AFTER_ITERATION:145            self.after_iteration_loggables.add(146                command(cmd, logf=cmd.replace(" ", "_") + '.after'))147        for fname in _DEFAULT_FILES_TO_LOG_AFTER_ITERATION:148            self.after_iteration_loggables.add(149                logfile(fname, logf=os.path.basename(fname) + '.after'))150        # add in a couple of extra files and commands we want to grab151        self.test_loggables.add(command("df -mP", logf="df"))152        # We compress the dmesg because it can get large when kernels are153        # configured with a large buffer and some tests trigger OOMs or154        # other large "spam" that fill it up...155        self.test_loggables.add(command("dmesg -c", logf="dmesg",156                                        compress_log=True))157        self.boot_loggables.add(logfile("/proc/cmdline",158                                        log_in_keyval=True))159        # log /proc/mounts but with custom filename since we already160        # log the output of the "mount" command as the filename "mount"161        self.boot_loggables.add(logfile('/proc/mounts', logf='proc_mounts'))162        self.boot_loggables.add(command("uname -a", logf="uname",163                                        log_in_keyval=True))164        self.sm = software_manager.SoftwareManager()165    def __getstate__(self):166        ret = dict(self.__dict__)167        ret["sm"] = None168        return ret169    def serialize(self):170        return {"boot": self.boot_loggables, "test": self.test_loggables}171    def deserialize(self, serialized):172        self.boot_loggables = serialized["boot"]173        self.test_loggables = serialized["test"]174    @staticmethod175    def _get_sysinfodir(resultsdir):176        sysinfodir = os.path.join(resultsdir, "sysinfo")177        if not os.path.exists(sysinfodir):178            os.makedirs(sysinfodir)179        return sysinfodir180    def _get_reboot_count(self):181        if not glob.glob(os.path.join(self.sysinfodir, "*")):182            return -1183        else:184            return len(glob.glob(os.path.join(self.sysinfodir, "boot.*")))185    def _get_boot_subdir(self, next=False):186        reboot_count = self._get_reboot_count()187        if next:188            reboot_count += 1189        if reboot_count < 1:190            return self.sysinfodir191        else:192            boot_dir = "boot.%d" % (reboot_count - 1)193            return os.path.join(self.sysinfodir, boot_dir)194    def _get_iteration_subdir(self, test, iteration):195        iter_dir = "iteration.%d" % iteration196        logdir = os.path.join(self._get_sysinfodir(test.outputdir), iter_dir)197        if not os.path.exists(logdir):198            os.mkdir(logdir)199        return logdir200    @log.log_and_ignore_errors("post-reboot sysinfo error:")201    def log_per_reboot_data(self):202        """ Logging hook called whenever a job starts, and again after203        any reboot. """204        logdir = self._get_boot_subdir(next=True)205        if not os.path.exists(logdir):206            os.mkdir(logdir)207        for log in (self.test_loggables | self.boot_loggables):208            log.run(logdir)209        if _LOG_INSTALLED_PACKAGES:210            # also log any installed packages211            installed_path = os.path.join(logdir, "installed_packages")212            installed_packages = "\n".join(self.sm.list_all()) + "\n"213            utils.open_write_close(installed_path, installed_packages)214    @log.log_and_ignore_errors("pre-test sysinfo error:")215    def log_before_each_test(self, test):216        """ Logging hook called before a test starts. """217        if _LOG_INSTALLED_PACKAGES:218            self._installed_packages = self.sm.list_all()219            # Also log the list of installed packaged before each test starts220            test_sysinfodir = self._get_sysinfodir(test.outputdir)221            installed_path = os.path.join(test_sysinfodir, "installed_packages")222            installed_packages = "\n".join(self._installed_packages)223            utils.open_write_close(installed_path, installed_packages)224        if os.path.exists("/var/log/messages"):225            stat = os.stat("/var/log/messages")226            self._messages_size = stat.st_size227            self._messages_inode = stat.st_ino228        elif os.path.exists("/var/log/syslog"):229            stat = os.stat("/var/log/syslog")230            self._messages_size = stat.st_size231            self._messages_inode = stat.st_ino232    @log.log_and_ignore_errors("post-test sysinfo error:")233    def log_after_each_test(self, test):234        """ Logging hook called after a test finishs. """235        test_sysinfodir = self._get_sysinfodir(test.outputdir)236        # create a symlink in the test sysinfo dir to the current boot237        reboot_dir = self._get_boot_subdir()238        assert os.path.exists(reboot_dir)239        symlink_dest = os.path.join(test_sysinfodir, "reboot_current")240        symlink_src = utils.get_relative_path(reboot_dir,241                                              os.path.dirname(symlink_dest))242        try:243            os.symlink(symlink_src, symlink_dest)244        except Exception as e:245            raise Exception('%s: whilst linking %s to %s' % (e, symlink_src,246                                                             symlink_dest))247        # run all the standard logging commands248        for log in self.test_loggables:249            log.run(test_sysinfodir)...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!!
