Best Python code snippet using autotest_python
harness_beaker.py
Source:harness_beaker.py  
...74            raise error.HarnessError('Need valid hostname')75        # hack for flexible debug environment76        labc = not self.offline and self.labc_url or None77        self.bkr_proxy = BkrProxy(self.recipe_id, labc)78        self.setupInitSymlink()79    def parse_args(self, args, is_bootstrap):80        if not args:81            return82        for a in args.split(','):83            if a == 'offline':84                # use cached recipe and stay offline whole time85                self.offline = True86            elif a[:5] == 'cache':87                if len(a) > 5 and a[5] == '=':88                    # cache a different recipe instead89                    self.recipe_id = a[6:]90                # remotely retrieve recipe, but stay offline during run91                if not is_bootstrap:92                    self.offline = True93            elif a[:8] == 'quickcmd':94                if len(a) < 8 or a[8] != '=':95                    raise error.HarnessError("Bad use of 'quickcmd'")96                self.cmd = a[9:]97            else:98                raise error.HarnessError("Unknown beaker harness arg: %s" % a)99    def parse_quickcmd(self, args):100        # hack allow tests to quickly submit feedback through harness101        if not args:102            return103        if 'BEAKER_TASK_ID' not in os.environ:104            raise error.HarnessError("No BEAKER_TASK_ID set")105        task_id = os.environ['BEAKER_TASK_ID']106        # Commands are from tests and should be reported as results107        cmd, q_args = args.split(':')108        if cmd == 'submit_log':109            try:110                # rhts_submit_log has as args: -S -T -l111                # we just care about -l112                f = None113                arg_list = q_args.split(' ')114                while arg_list:115                    arg = arg_list.pop(0)116                    if arg == '-l':117                        f = arg_list.pop(0)118                        break119                if not f:120                    raise HarnessException("Argument -l not found in q_args "121                                           "'%s'" % q_args)122                self.bkr_proxy.task_upload_file(task_id, f)123            except Exception:124                logging.critical('ERROR: Failed to process quick cmd %s' % cmd)125        elif cmd == 'submit_result':126            def init_args(testname='Need/a/testname/here', status="None", logfile=None, score="0"):127                return testname, status, logfile, score128            try:129                # report_result has TESTNAME STATUS LOGFILE SCORE130                arg_list = q_args.split(' ')131                testname, status, logfile, score = init_args(*arg_list)132                resultid = self.bkr_proxy.task_result(task_id, status,133                                                      testname, score, '')134                if (logfile and os.path.isfile(logfile) and135                        os.path.getsize(logfile) != 0):136                    self.bkr_proxy.result_upload_file(task_id, resultid, logfile)137                # save the dmesg file138                dfile = '/tmp/beaker.dmesg'139                utils.system('dmesg -c > %s' % dfile)140                if os.path.getsize(dfile) != 0:141                    self.bkr_proxy.result_upload_file(task_id, resultid, dfile)142                # os.remove(dfile)143            except Exception:144                logging.critical('ERROR: Failed to process quick cmd %s' % cmd)145        elif cmd == 'reboot':146            # we are in a stub job.  Can't use self.job.reboot() :-(147            utils.system("sync; sync; reboot")148            self.run_pause()149            raise error.JobContinue("more to come")150        else:151            raise error.HarnessError("Bad sub-quickcmd: %s" % cmd)152    def bootstrap(self, fetchdir):153        '''How to kickstart autotest when you have no control file?154           You download the beaker XML, convert it to a control file155           and pass it back to autotest. Much like bootstrapping.. :-)156        '''157        # hack to sneakily pass results back to beaker without running158        # autotest.  Need to avoid calling get_recipe below159        if self.cmd:160            self.parse_quickcmd(self.cmd)161            return None162        recipe = self.init_recipe_from_beaker()163        # remove stale file164        if os.path.isfile(self.state_file):165            os.remove(self.state_file)166            self.tests = {}167        # sanity check168        if self.recipe_id != recipe.id:169            raise error.HarnessError('Recipe mismatch: machine %s.. != XML %s..' %170                                     (self.recipe_id, recipe.id))171        # create unique name172        control_file_name = recipe.job_id + '_' + recipe.id + '.control'173        control_file_path = fetchdir + '/' + control_file_name174        logging.debug('setting up control file - %s' % control_file_path)175        control_file = open(control_file_path, 'w')176        try:177            # convert recipe xml into control file178            for task in recipe.tasks:179                self.convert_task_to_control(fetchdir, control_file, task)180                # getting the task id later, will be hard, store it in file/memory181                self.write_processed_tests(self.get_test_name(task), task.id)182            control_file.close()183        except HarnessException:184            # hook to bail out on reservesys systems and not run autotest185            return None186        except Exception, ex:187            os.remove(control_file_path)188            raise error.HarnessError('beaker_harness: convert failed with -> %s' % ex)189        # autotest should find this under FETCHDIRTEST because it is unique190        return control_file_path191    def init_recipe_from_beaker(self):192        logging.debug('Contacting beaker to get task details')193        bxp = BeakerXMLParser()194        recipe_xml = self.get_recipe_from_LC()195        recipes_dict = bxp.parse_xml(recipe_xml)196        return self.find_recipe(recipes_dict)197    def init_task_params(self, task):198        logging.debug('PrepareTaskParams')199        if task is None:200            raise error.HarnessError('No valid task')201        for (name, value) in task.params.items():202            logging.debug('adding to os.environ: <%s=%s>', name, value)203            os.environ[name] = value204    def get_recipe_from_LC(self):205        logging.debug('trying to get recipe from LC:')206        try:207            recipe = self.bkr_proxy.get_recipe()208        except Exception, exc:209            raise error.HarnessError('Failed to retrieve xml: %s' % exc)210        return recipe211    def find_recipe(self, recipes_dict):212        if self.hostname in recipes_dict:213            return recipes_dict[self.hostname]214        for h in recipes_dict:215            if self.recipe_id == recipes_dict[h].id:216                return recipes_dict[h]217        raise error.HarnessError('No valid recipe for host %s' % self.hostname)218    # the block below was taken from standalone harness219    def setupInitSymlink(self):220        logging.debug('Symlinking init scripts')221        autodir = os.environ.get('AUTODIR')222        rc = os.path.join(autodir, 'tools/autotest')223        if os.path.isfile(rc) and os.path.islink(rc):224            # nothing to do225            return226        # see if system supports event.d versus inittab227        if os.path.exists('/etc/event.d'):228            # NB: assuming current runlevel is default229            initdefault = utils.system_output('/sbin/runlevel').split()[1]230        elif os.path.exists('/etc/inittab'):231            initdefault = utils.system_output('grep :initdefault: /etc/inittab')232            initdefault = initdefault.split(':')[1]233        else:...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!!
