def _await_login(self): """Awaits the login prompt and logs the user in""" start = time.time() expectations = [self.prompt, self.login_prompt, TIMEOUT] if self.console_ready != "": expectations.append(self.console_ready) # We call console.expect with a short timeout here to detect if the # console is idle, which results in a timeout without any changes to # the before property. So we store the last before value we've seen. # Because pexpect keeps any read data in it's buffer when a timeout # occours, we can't lose any data this way. last_before = b'' while True: index, before, _, _ = self.console.expect( expectations, timeout=self.await_login_timeout) if index == 0: # we got a promt. no need for any further action to activate # this driver. self.status = 1 break elif index == 1: # we need to login self.console.sendline(self.username) index, _, _, _ = self.console.expect( [self.prompt, "Password: "******"Password entry needed but no password set") self._check_prompt() break elif index == 2: # expect hit a timeout while waiting for a match if before == last_before: # we did not receive anything during # self.await_login_timeout. # let's assume the target is idle and we can safely issue a # newline to check the state self.console.sendline("") elif index == 3: # we have just activated a console here # lets start over again and see if login or prompt will appear # now. self.console.sendline("") last_before = before if time.time() > start + self.login_timeout: raise TIMEOUT("Timeout of {} seconds exceeded during waiting for login".format(self.login_timeout)) # pylint: disable=line-too-long
def read_nonblocking(self, size=1, timeout=-1): """INTERNAL: Non blocking read.""" if len(self.chunk_buffer): return self.chunk_buffer.read(size) if self.stdout_eof and self.stderr_eof: assert self.child_output.qsize() == 0 return '' if timeout == -1: timeout = self.timeout try: handle, status, data = self.child_output.get(timeout=timeout) except Empty: raise TIMEOUT('Timeout exceeded in read_nonblocking().') if status == 'data': self.chunk_buffer.add(data) elif status == 'eof': self._set_eof(handle) raise EOF('End of file in read_nonblocking().') elif status == 'error': self._set_eof(handle) raise OSError(data) buf = self.chunk_buffer.read(size) if self.logfile is not None: self.logfile.write(buf) self.logfile.flush() if self.logfile_read is not None: self.logfile_read.write(buf) self.logfile_read.flush() return buf
def expect_delay(self, delay_time, timeout=30, resolution=0.25, require_input=0): """Wait for input to settle for a period not less than delay_time. resolution specifies the delay between tests. Raises timeout if we fail to settle down within timeout seconds. If require_input is greater than zero, we will not start counting for delay until after require_input bytes have been read. """ time_since_last_input = 0 end_time = time.time() + timeout if require_input: self.read_nonblocking(size=int(require_input), timeout=timeout) while True: if time.time() > end_time: raise TIMEOUT( 'Client has not stopped sending data within %r seconds' % timeout) try: self.read_nonblocking(size=READ_CHUNK_SIZE, timeout=resolution) time_since_last_input = 0 except TIMEOUT: time_since_last_input += resolution if time_since_last_input >= delay_time: return
def _read(self, size=1, timeout=10): ready, _, _ = select.select([self._clientsocket], [], [], timeout) if ready: # Collect some more data time.sleep(0.01) # Always read a page, regardless of size res = self._clientsocket.recv(4096) else: raise TIMEOUT("Timeout of %.2f seconds exceeded" % timeout) return res
def _await_prompt(self): """Awaits the prompt and enters the shell""" timeout = Timeout(float(self.login_timeout)) # We call console.expect with a short timeout here to detect if the # console is idle, which would result in a timeout without any changes # to the before property. So we store the last before value we've seen. # Because pexpect keeps any read data in it's buffer when a timeout # occours, we can't lose any data this way. last_before = None password_entered = False expectations = [self.prompt, self.autoboot, "Password: "******"Password entry needed but no password set") if password_entered: # we already sent the password, but got the pw prompt again raise Exception("Password was not correct") self.console.sendline(self.password) password_entered = True elif index == 3: # expect hit a timeout while waiting for a match if before == last_before: # we did not receive anything during the previous expect cycle # let's assume the target is idle and we can safely issue a # newline to check the state self.console.sendline("") if timeout.expired: raise TIMEOUT("Timeout of {} seconds exceeded during waiting for login" .format(self.login_timeout)) last_before = before self._check_prompt()
def _read(self, size=1, timeout=10): ready, _, _ = select.select([self._clientsocket], [], [], timeout) if ready: # Always read a page, regardless of size res = self._clientsocket.recv(4096) self.logger.debug( "Read %i bytes: %s, timeout %.2f, requested size %i", len(res), res, timeout, size) else: raise TIMEOUT("Timeout of %.2f seconds exceeded" % timeout) return res
def _read(self, size: int = 1, timeout: float = 0.0): """ Reads 'size' or more bytes from the serialport Keyword Arguments: size -- amount of bytes to read, defaults to 1 """ reading = max(size, self.serial.in_waiting) self.serial.timeout = timeout res = self.serial.read(reading) if not res: raise TIMEOUT("Timeout of %.2f seconds exceeded" % timeout) return res
def _read_with_or_without_timeout(self, timeout, size, buf): if not buf: try: buf = self._read_from_queue(timeout=timeout, size=size, buf=buf) except Empty: if not self._buf: raise TIMEOUT('read_nonblocking: timeout exceeded') else: buf = self._read_from_queue_until_end_or_size(buf, size) return buf
def expect_cursor_position(self, row, column, timeout=30, resolution=0.05): """Expect the cursor to seek to a given row and column. Polls, so this should be used only in cases where the cursor settles on the correct position (rather than just passing through).""" end_time = time.time() + timeout if self.term.cur_r == row and self.term.cur_c == column: return while True: self.read_nonblocking(self.maxread, timeout) if (row is None or self.term.cur_r == row) and (column is None or self.term.cur_c == column): return if time.time() > end_time: raise TIMEOUT()
def _read(self, size: int=1, timeout: int=0): """ Reads 'size' bytes from the serialport Keyword Arguments: size -- amount of bytes to read, defaults to 1024 """ self.logger.debug("Reading %s bytes with %s timeout", size, timeout) self.serial.timeout = timeout res = self.serial.read(size) self.logger.debug("Read bytes (%s) or timeout reached", res) if not res: raise TIMEOUT("Timeout exceeded") return res
def wait(self, timeout=None): """Wait until the child exits. If timeout is not specified this blocks indefinately. Otherwise, timeout specifies the number of seconds to wait.""" if self.exitstatus is not None: return if timeout is None: timeout = INFINITE else: timeout = 1000 * timeout ret = WaitForSingleObject(self.child_handle, timeout) if ret == WAIT_TIMEOUT: raise TIMEOUT('Timeout exceeded in wait().') self.exitstatus = GetExitCodeProcess(self.child_handle) return self.exitstatus
def _read(self, size: int=1, timeout: int=0): """ Reads 'size' or more bytes from the serialport Keyword Arguments: size -- amount of bytes to read, defaults to 1 """ reading = max(size, self.serial.in_waiting) self.logger.debug("Reading %s (min %s) bytes with %s timeout", reading, size, timeout) self.serial.timeout = timeout res = self.serial.read(reading) self.logger.debug("Read bytes (%s) or timeout reached", res) if not res: raise TIMEOUT("Timeout exceeded") return res
def expect_line_matching_list(self, pattern_list, timeout=-1, lineno=0): if timeout == -1: timeout = self.timeout end_time = time.time() + timeout try: incoming = self.buffer while True: for cre in pattern_list: if cre is EOF or cre is TIMEOUT: continue if lineno: line = self.term.dump_row(lineno - 1) match = cre.search(line) else: for line in self.term.dump_rows(): match = cre.search(line) if match is not None: break if match is None: continue self.buffer = '' self.before = incoming self.after = '' self.match = match self.match_index = pattern_list.index(cre) return self.match_index c = self.read_nonblocking(self.maxread, timeout) time.sleep(0.0001) incoming += c if timeout is not None: timeout = end_time - time.time() if timeout < 0: raise TIMEOUT( 'Timeout exceeded in expect_line_matching_list().') except EOF, e: self.buffer = '' self.before = incoming self.after = EOF if EOF in pattern_list: self.match = EOF self.match_index = pattern_list.index(EOF) return self.match_index else: self.match = None self.match_index = None raise EOF(str(e) + '\n' + str(self))
def responder(mock, responses, patterns, maxTime): log.debug('entering MOCK responder') print(patterns) #return the index relative to event_name response = responses.pop(0) log.debug('current response [%s]' % (response)) idx = 0 toBeMatched = True while toBeMatched and idx < len(patterns): search = '(.*)(%s)' % patterns[idx] log.debug("checking [%d] regexp: [%s]" % (idx, search)) if patterns[idx] == TIMEOUT: toBeMatched = False mock.before = response mock.after = TIMEOUT break match = re.match(search, response, re.DOTALL) if match: toBeMatched = False mock.before = match.group(1) mock.after = match.group(2) break idx += 1 if idx < len(patterns): log.debug('returning index [%d]' % idx) return idx else: mock.before = response mock.after = TIMEOUT raise TIMEOUT('wait time exceeded')
class spawn(pexpect_spawn): def __init__(self, command, term, timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None): assert isinstance( term, ANSI.term), 'pxtty should be passed a terminal instance' pexpect_spawn.__init__(self, command, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env) self.term = term self.logfiles_read.append(self.term) ## TODO: if we're set for local echo, also logfiles_send and logfiles_interact def expect_delay(self, delay_time, timeout=30, resolution=0.25, require_input=0): """Wait for input to settle for a period not less than delay_time. resolution specifies the delay between tests. Raises timeout if we fail to settle down within timeout seconds. If require_input is greater than zero, we will not start counting for delay until after require_input bytes have been read. """ time_since_last_input = 0 end_time = time.time() + timeout if require_input: self.read_nonblocking(size=int(require_input), timeout=timeout) while True: if time.time() > end_time: raise TIMEOUT( 'Client has not stopped sending data within %r seconds' % timeout) try: self.read_nonblocking(size=READ_CHUNK_SIZE, timeout=resolution) time_since_last_input = 0 except TIMEOUT: time_since_last_input += resolution if time_since_last_input >= delay_time: return def expect_cursor_position(self, row, column, timeout=30, resolution=0.05): """Expect the cursor to seek to a given row and column. Polls, so this should be used only in cases where the cursor settles on the correct position (rather than just passing through).""" end_time = time.time() + timeout if self.term.cur_r == row and self.term.cur_c == column: return while True: self.read_nonblocking(self.maxread, timeout) if (row is None or self.term.cur_r == row) and (column is None or self.term.cur_c == column): return if time.time() > end_time: raise TIMEOUT() def expect_line_matching(self, pattern, lineno=0, timeout=-1): """Expect a VT100 line to match pattern. If a lineno (which is indexed from 1) is given, expect that specific line to match; otherwise, any line can be a winner. WARNING: This consumes ALL of the incoming buffer. """ compiled_pattern_list = self.compile_pattern_list(pattern) return self.expect_line_matching_list(compiled_pattern_list, lineno=lineno, timeout=timeout) def expect_line_matching_list(self, pattern_list, timeout=-1, lineno=0): if timeout == -1: timeout = self.timeout end_time = time.time() + timeout try: incoming = self.buffer while True: for cre in pattern_list: if cre is EOF or cre is TIMEOUT: continue if lineno: line = self.term.dump_row(lineno - 1) match = cre.search(line) else: for line in self.term.dump_rows(): match = cre.search(line) if match is not None: break if match is None: continue self.buffer = '' self.before = incoming self.after = '' self.match = match self.match_index = pattern_list.index(cre) return self.match_index c = self.read_nonblocking(self.maxread, timeout) time.sleep(0.0001) incoming += c if timeout is not None: timeout = end_time - time.time() if timeout < 0: raise TIMEOUT( 'Timeout exceeded in expect_line_matching_list().') except EOF, e: self.buffer = '' self.before = incoming self.after = EOF if EOF in pattern_list: self.match = EOF self.match_index = pattern_list.index(EOF) return self.match_index else: self.match = None self.match_index = None raise EOF(str(e) + '\n' + str(self)) except TIMEOUT, e: self.before = incoming self.after = TIMEOUT if TIMEOUT in pattern_list: self.match = TIMEOUT self.match_index = pattern_list.index(TIMEOUT) return self.match_index else: self.match = None self.match_index = None raise TIMEOUT(str(e) + '\n' + str(self))
def _await_login(self): """Awaits the login prompt and logs the user in""" start = time.time() expectations = [self.prompt, self.login_prompt, TIMEOUT] if self.console_ready != "": expectations.append(self.console_ready) # Use console.expect with a short timeout in a loop increases the # chance to split a match into two consecutive chunks of the stream. # This may lead to a missed match. # Hopefully we will recover from all those situations by sending a # newline after self.await_login_timeout. # the returned 'before' of the expect will keep all characters. # thus we need to remember what we had seen. last_before = None while True: index, before, _, _ = self.console.expect( expectations, timeout=self.await_login_timeout) if index == 0: # we got a promt. no need for any further action to activate # this driver. self.status = 1 break elif index == 1: # we need to login self.console.sendline(self.username) index, _, _, _ = self.console.expect( [self.prompt, "Password: "******"Password entry needed but no password set") self._check_prompt() break elif index == 2: # expect hit a timeout while waiting for a match if before == last_before: # we did not receive anything during # self.await_login_timeout. # let's assume the target is idle and we can safely issue a # newline to check the state self.console.sendline("") elif index == 3: # we have just activated a console here # lets start over again and see if login or prompt will appear # now. self.console.sendline("") last_before = before if time.time() > start + self.login_timeout: raise TIMEOUT( "Timeout of {} seconds exceeded during waiting for login". format(self.login_timeout))