Best Python code snippet using autotest_python
remote.py
Source:remote.py
...109 :params num_attempts: Number of times to attempt hard reset erroring110 on the last attempt.111 :params halt: Halts the machine before hardresetting.112 :params **wait_for_restart_kwargs: keyword arguments passed to113 wait_for_restart()114 """115 server_info = get_install_server_info()116 if server_info.get('xmlrpc_url', None) is not None:117 ServerInterface = self.INSTALL_SERVER_MAPPING[server_info['type']]118 server_interface = ServerInterface(**server_info)119 try:120 old_boot_id = self.get_boot_id()121 except error.AutoservSSHTimeout:122 old_boot_id = 'unknown boot_id prior to RemoteHost.hardreset'123 def reboot():124 power_state = "reboot"125 if halt:126 self.halt()127 power_state = "on"128 server_interface.power_host(host=self, state=power_state)129 self.record("GOOD", None, "reboot.start", "hard reset")130 if wait:131 warning_msg = ('Machine failed to respond to hard reset '132 'attempt (%s/%s)')133 for attempt in xrange(num_attempts - 1):134 try:135 self.wait_for_restart(timeout, log_failure=False,136 old_boot_id=old_boot_id,137 **wait_for_restart_kwargs)138 except error.AutoservShutdownError:139 logging.warning(warning_msg, attempt + 1,140 num_attempts)141 # re-send the hard reset command142 server_interface.power_host(host=self,143 state=power_state)144 else:145 break146 else:147 # Run on num_attempts=1 or last retry148 try:149 self.wait_for_restart(timeout,150 old_boot_id=old_boot_id,151 **wait_for_restart_kwargs)152 except error.AutoservShutdownError:153 logging.warning(warning_msg, num_attempts,154 num_attempts)155 msg = "Host did not shutdown"156 raise error.AutoservShutdownError(msg)157 if self.job:158 self.job.disable_warnings("POWER_FAILURE")159 try:160 if wait:161 self.log_reboot(reboot)162 else:163 reboot()164 finally:165 if self.job:166 self.job.enable_warnings("POWER_FAILURE")167 else:168 raise error.AutoservUnsupportedError("Empty install server setup "169 "on global_config.ini")170 def _var_log_messages_path(self):171 """172 Find possible paths for a messages file.173 """174 for path in self.VAR_LOG_MESSAGES_PATHS:175 try:176 self.run('test -f %s' % path)177 logging.debug("Found remote path %s", path)178 return path179 except Exception:180 logging.debug("Remote path %s is missing", path)181 return None182 def job_start(self):183 """184 Abstract method, called the first time a remote host object185 is created for a specific host after a job starts.186 This method depends on the create_host factory being used to187 construct your host object. If you directly construct host objects188 you will need to call this method yourself (and enforce the189 single-call rule).190 """191 messages_file = self._var_log_messages_path()192 if messages_file is not None:193 try:194 self.run('rm -f %s' % self.VAR_LOG_MESSAGES_COPY_PATH)195 self.run('cp %s %s' % (messages_file,196 self.VAR_LOG_MESSAGES_COPY_PATH))197 except Exception, e:198 # Non-fatal error199 logging.info('Failed to copy %s at startup: %s',200 messages_file, e)201 else:202 logging.info("No remote messages path found, looked %s",203 self.VAR_LOG_MESSAGES_PATHS)204 def get_autodir(self):205 return self.autodir206 def set_autodir(self, autodir):207 """208 This method is called to make the host object aware of the209 where autotest is installed. Called in server/autotest.py210 after a successful install211 """212 self.autodir = autodir213 def sysrq_reboot(self):214 self.run('echo b > /proc/sysrq-trigger &')215 def halt(self, timeout=DEFAULT_HALT_TIMEOUT, wait=True):216 self.run('/sbin/halt')217 if wait:218 self.wait_down(timeout=timeout)219 def reboot(self, timeout=DEFAULT_REBOOT_TIMEOUT, label=LAST_BOOT_TAG,220 kernel_args=None, wait=True, fastsync=False,221 reboot_cmd=None, **dargs):222 """223 Reboot the remote host.224 Args:225 timeout - How long to wait for the reboot.226 label - The label we should boot into. If None, we will227 boot into the default kernel. If it's LAST_BOOT_TAG,228 we'll boot into whichever kernel was .boot'ed last229 (or the default kernel if we haven't .boot'ed in this230 job). If it's None, we'll boot into the default kernel.231 If it's something else, we'll boot into that.232 wait - Should we wait to see if the machine comes back up.233 fastsync - Don't wait for the sync to complete, just start one234 and move on. This is for cases where rebooting prompty235 is more important than data integrity and/or the236 machine may have disks that cause sync to never return.237 reboot_cmd - Reboot command to execute.238 """239 if self.job:240 if label == self.LAST_BOOT_TAG:241 label = self.job.last_boot_tag242 else:243 self.job.last_boot_tag = label244 self.reboot_setup(label=label, kernel_args=kernel_args, **dargs)245 if label or kernel_args:246 if not label:247 label = self.bootloader.get_default_title()248 self.bootloader.boot_once(label)249 if kernel_args:250 self.bootloader.add_args(label, kernel_args)251 # define a function for the reboot and run it in a group252 print "Reboot: initiating reboot"253 def reboot():254 self.record("GOOD", None, "reboot.start")255 try:256 current_boot_id = self.get_boot_id()257 # sync before starting the reboot, so that a long sync during258 # shutdown isn't timed out by wait_down's short timeout259 if not fastsync:260 self.run('sync; sync', timeout=timeout, ignore_status=True)261 if reboot_cmd:262 self.run(reboot_cmd)263 else:264 # Try several methods of rebooting in increasing harshness.265 self.run('(('266 ' sync &'267 ' sleep 5; reboot &'268 ' sleep 60; reboot -f &'269 ' sleep 10; reboot -nf &'270 ' sleep 10; telinit 6 &'271 ') </dev/null >/dev/null 2>&1 &)')272 except error.AutoservRunError:273 self.record("ABORT", None, "reboot.start",274 "reboot command failed")275 raise276 if wait:277 self.wait_for_restart(timeout, old_boot_id=current_boot_id,278 **dargs)279 # if this is a full reboot-and-wait, run the reboot inside a group280 if wait:281 self.log_reboot(reboot)282 else:283 reboot()284 def reboot_followup(self, *args, **dargs):285 super(RemoteHost, self).reboot_followup(*args, **dargs)286 if self.job:287 self.job.profilers.handle_reboot(self)288 def wait_for_restart(self, timeout=DEFAULT_REBOOT_TIMEOUT, **dargs):289 """290 Wait for the host to come back from a reboot. This wraps the291 generic wait_for_restart implementation in a reboot group.292 """293 def reboot_func():294 super(RemoteHost, self).wait_for_restart(timeout=timeout, **dargs)295 self.log_reboot(reboot_func)296 def cleanup(self):297 super(RemoteHost, self).cleanup()298 self.reboot()299 def get_tmp_dir(self, parent='/tmp'):300 """301 Return the pathname of a directory on the host suitable302 for temporary file storage.303 The directory and its content will be deleted automatically304 on the destruction of the Host object that was used to obtain305 it.306 """307 self.run("mkdir -p %s" % parent)308 template = os.path.join(parent, 'autoserv-XXXXXX')...
test_restart.py
Source:test_restart.py
...7import logging8import pytest9from requests import HTTPError, ConnectionError10log = logging.getLogger(__name__)11def wait_for_restart(jenkins):12 wait = 1513 count = 014 max_count = 3015 success = False16 msg = (17 'Jenkins has not restarted yet! (This is try %s of %s, '18 'waited %s seconds so far) '19 'Sleeping %s seconds and trying again...'20 )21 while count < max_count or not success:22 time.sleep(wait)23 try:24 jenkins.poll()25 log.info('Jenkins restarted successfully.')26 success = True27 break28 except HTTPError as ex:29 log.info(ex)30 except ConnectionError as ex:31 log.info(ex)32 log.info(msg, count + 1, max_count, count * wait, wait)33 count += 134 if not success:35 msg = ('Jenkins did not come back from safe restart! '36 'Waited {0} seconds altogether. This '37 'failure may cause other failures.')38 log.critical(msg.format(count*wait))39 pytest.fail(msg)40def test_safe_restart_wait(jenkins):41 jenkins.poll() # jenkins should be alive42 jenkins.safe_restart() # restart and wait for reboot (default)43 jenkins.poll() # jenkins should be alive again44def test_safe_restart_dont_wait(jenkins):45 jenkins.poll() # jenkins should be alive46 jenkins.safe_restart(wait_for_reboot=False)47 # Jenkins sleeps for 10 seconds before actually restarting48 time.sleep(11)49 with pytest.raises((HTTPError, ConnectionError)):50 # this is a 503: jenkins is still restarting51 jenkins.poll()52 # the test is now complete, but other tests cannot run until53 # jenkins has finished restarted. to avoid cascading failure54 # we have to wait for reboot to finish....
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!!