def test_format_line_decode_errors(fake_unicode_decode_error): """If no suitable codec can be found, it should return the input line.""" decode_patch = patch.object( formatting.codecs, "decode", side_effect=fake_unicode_decode_error, ) with decode_patch as patched_decode: assert formatting.format_line("sure thing") == "sure thing" assert_all_encodings("sure thing", patched_decode)
def test_unknown_returns_line(): """Let it fail if the shell cant display it if we can't decode.""" if sys.version_info >= (3, 0): starting = bytes("Everybody loves a 🍔!", "utf-8") else: starting = "Everybody loves a 🍔!" output = formatting.format_line(starting) if sys.version_info >= (3, 0): # py3 will correctly decode and return a str vs the bytes input assert "Everybody loves a" in output else: assert output == starting
def _try_for_unmatched_prompt(self, server, output, command, _from_login=False, _attempts_left=3): """On command timeout, send newlines to guess the missing shell prompt. Args: server: the sshc object output: the sshc.before after issuing command before the timeout command: the command issued that caused the initial timeout _from_login: if this is called from the login method, return the (connection, code) tuple, or return formatted_output() _attempts_left: internal integer to iterate over this function with Returns: format_output if it can find a new prompt, or -1 on error """ try: # prompt is usually in the last 30 chars of the last line of output new_prompt = format_line(output.splitlines()[-1][-30:]) except IndexError: # blank last line could cause an IndexError, should send a newline pass else: # escape regex characters replacements = ["\\", "/", ")", "(", "[", "]", "{", "}", " ", "$", "?", ">", "<", "^", ".", "*"] for char in replacements: new_prompt = new_prompt.replace(char, "\{}".format(char)) if new_prompt and new_prompt not in self.options["shell_prompts"]: self.options["shell_prompts"].append(new_prompt) try: server.sendline() server.expect( self.options["shell_prompts"] + self.options["extra_prompts"], 2, ) except (pexpect.TIMEOUT, pexpect.EOF): if _attempts_left: return self._try_for_unmatched_prompt( server, server.before, command, _from_login=_from_login, _attempts_left=(_attempts_left - 1), ) else: self._push_expect_forward(server) if _from_login: return (server, 1) else: return format_output(output, command) self.send_interrupt(server) if _from_login: # if we get here, we tried to guess the prompt by sending enter 3 # times, but still didn't return to that same shell. Something odd # is likely happening on the device that needs manual inspection return (None, -6) else: return -1
def test_unknown_returns_line(self): """Let it fail if the shell cant display it if we can't decode.""" starting = "Everybody loves a 🍔!" self.assertEqual(formatting.format_line(starting), starting)