pexpect.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test.cmdtest_d.include.pexpect: pexpect implementation for MMGen Wallet cmdtest suite
  20. """
  21. import sys, time
  22. from mmgen.color import red, yellow, green, cyan
  23. from mmgen.util import msg, msg_r, rmsg, die
  24. from ...include.common import cfg, vmsg, vmsg_r, getrandstr, strip_ansi_escapes
  25. try:
  26. import pexpect
  27. from pexpect.popen_spawn import PopenSpawn
  28. except ImportError as e:
  29. die(2, red(f'‘pexpect’ module is missing. Cannnot run test suite ({e!r})'))
  30. def debug_pexpect_msg(p):
  31. msg('\n{}{}{}'.format(red('BEFORE ['), p.before, red(']')))
  32. msg('{}{}{}'.format(red('MATCH ['), p.after, red(']')))
  33. NL = '\n'
  34. class CmdTestPexpect:
  35. def __init__(
  36. self,
  37. args,
  38. no_output = False,
  39. spawn_env = None,
  40. pexpect_spawn = False,
  41. send_delay = None,
  42. timeout = None,
  43. silent = False,
  44. direct_exec = False):
  45. self.pexpect_spawn = pexpect_spawn
  46. self.send_delay = send_delay
  47. self.skip_ok = False
  48. self.sent_value = None
  49. self.spawn_env = spawn_env
  50. self.exit_val = None
  51. if direct_exec or cfg.direct_exec:
  52. from subprocess import Popen, DEVNULL
  53. redir = DEVNULL if (no_output or not cfg.exact_output) else None
  54. self.ep = Popen([args[0]] + args[1:], stderr=redir, env=spawn_env)
  55. else:
  56. timeout = int(
  57. timeout
  58. or cfg.pexpect_timeout
  59. or cfg.test_suite_pexpect_timeout) or (60, 5)[bool(cfg.debug_pexpect)]
  60. if pexpect_spawn:
  61. self.p = pexpect.spawn(args[0], args[1:], encoding='utf8', timeout=timeout, env=spawn_env)
  62. else:
  63. self.p = PopenSpawn(args, encoding='utf8', timeout=timeout, env=spawn_env)
  64. if cfg.exact_output and not silent:
  65. self.p.logfile = sys.stdout
  66. def do_decrypt_ka_data(
  67. self,
  68. pw,
  69. desc = 'key-address data',
  70. check = True,
  71. have_yes_opt = False):
  72. self.passphrase(desc, pw)
  73. if not have_yes_opt:
  74. self.expect('Check key-to-address validity? (y/N): ', ('n', 'y')[check])
  75. def view_tx(self, view):
  76. self.expect(r'View.* transaction.*\? .*: ', view, regex=True)
  77. match view:
  78. case 'v' if cfg.pexpect_spawn:
  79. self.expect('END', 'q')
  80. case 'v' | 'n' | '\n':
  81. pass
  82. case _:
  83. self.expect('to continue: ', '\n')
  84. def do_comment(self, add_comment, has_label=False):
  85. p = ('Add a comment to transaction', 'Edit transaction comment')[has_label]
  86. self.expect(f'{p}? (y/N): ', ('n', 'y')[bool(add_comment)])
  87. if add_comment:
  88. self.expect('Comment: ', add_comment+'\n')
  89. def ok(self, exit_val=None):
  90. if not self.pexpect_spawn:
  91. self.p.sendeof()
  92. self.p.read()
  93. ret = self.p.wait()
  94. if ret != (self.exit_val or exit_val or 0) and not cfg.coverage:
  95. die('TestSuiteSpawnedScriptException', f'Spawned script exited with value {ret}')
  96. if cfg.profile:
  97. return
  98. if not self.skip_ok:
  99. m = 'OK\n' if ret == 0 else f'OK[{ret}]\n'
  100. sys.stderr.write(green(m) if cfg.exact_output or cfg.verbose else ' '+m)
  101. return self
  102. def license(self):
  103. if self.spawn_env.get('MMGEN_NO_LICENSE'):
  104. return
  105. self.expect("'w' for conditions and warranty info, or 'c' to continue: ", 'c')
  106. def label(self, label='Test Label (UTF-8) α'):
  107. self.expect('Enter a wallet label, or hit ENTER for no label: ', label+'\n')
  108. def usr_rand(self, num_chars):
  109. if cfg.usr_random:
  110. self.interactive()
  111. self.send('\n')
  112. else:
  113. rand_chars = list(getrandstr(num_chars, no_space=True))
  114. vmsg_r('SEND ')
  115. while rand_chars:
  116. ch = rand_chars.pop(0)
  117. msg_r(yellow(ch)+' ' if cfg.verbose else '+')
  118. self.expect('left: ', ch, delay=0.005)
  119. self.expect('ENTER to continue: ', '\n')
  120. def passphrase_new(self, desc, passphrase):
  121. self.expect(f'Enter passphrase for {desc}: ', passphrase+'\n')
  122. self.expect('Repeat passphrase: ', passphrase+'\n')
  123. def passphrase(self, desc, passphrase, pwtype=''):
  124. if pwtype:
  125. pwtype += ' '
  126. self.expect(f'Enter {pwtype}passphrase for {desc}.*?: ', passphrase+'\n', regex=True)
  127. def hash_preset(self, desc, preset=''):
  128. self.expect(f'Enter hash preset for {desc}')
  129. self.expect('or hit ENTER .*?:', str(preset)+'\n', regex=True)
  130. def written_to_file(self, desc, overwrite_unlikely=False, query='Overwrite? '):
  131. s1 = f'{desc} written to file '
  132. s2 = query + "Type uppercase 'YES' to confirm: "
  133. ret = self.expect(([s1, s2], s1)[overwrite_unlikely])
  134. if ret == 1:
  135. self.send('YES\n')
  136. return self.expect_getend("Overwriting file '").rstrip("'")
  137. self.expect(NL, nonl=True)
  138. outfile = self.p.before.strip().strip("'")
  139. if cfg.debug_pexpect:
  140. rmsg(f'Outfile [{outfile}]')
  141. vmsg('{} file: {}'.format(desc, cyan(outfile.replace('"', ""))))
  142. return outfile
  143. def hincog_create(self, hincog_bytes):
  144. ret = self.expect(['Create? (Y/n): ', "'YES' to confirm: "])
  145. if ret == 0:
  146. self.send('\n')
  147. self.expect('Enter file size: ', str(hincog_bytes)+'\n')
  148. else:
  149. self.send('YES\n')
  150. return ret
  151. def no_overwrite(self):
  152. self.expect("Overwrite? Type uppercase 'YES' to confirm: ", '\n')
  153. self.expect('Exiting at user request')
  154. def expect_getend(self, s, regex=False):
  155. self.expect(s, regex=regex, nonl=True)
  156. if cfg.debug_pexpect:
  157. debug_pexpect_msg(self.p)
  158. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  159. self.expect(NL, nonl=True, silent=True)
  160. if cfg.debug_pexpect:
  161. debug_pexpect_msg(self.p)
  162. end = self.p.before.rstrip()
  163. if not cfg.debug:
  164. vmsg(f' ==> {cyan(end)}')
  165. return end
  166. def interactive(self):
  167. return self.p.interact() # interact() not available with popen_spawn
  168. def kill(self, signal):
  169. return self.p.kill(signal)
  170. def match_expect_list(self, expect_list, greedy=False):
  171. allrep = '.*' if greedy else '.*?'
  172. expect = (
  173. r'(\b|\s)' +
  174. fr'\s{allrep}\s'.join(s.replace(r'.', r'\.').replace(' ', r'\s+') for s in expect_list) +
  175. r'(\b|\s)')
  176. import re
  177. m = re.search(expect, self.read(strip_color=True), re.DOTALL)
  178. assert m, f'No match found for regular expression {expect!r}'
  179. return m
  180. def expect(self, s, t='', delay=None, regex=False, nonl=False, silent=False):
  181. if not silent:
  182. if cfg.verbose:
  183. msg_r('EXPECT ' + yellow(str(s)))
  184. elif not cfg.exact_output:
  185. msg_r('+')
  186. try:
  187. ret = (self.p.expect_exact, self.p.expect)[bool(regex)](s) if s else 0
  188. except pexpect.TIMEOUT as e:
  189. if cfg.debug_pexpect:
  190. raise
  191. m1 = f'\nERROR. Expect {s!r} timed out. Exiting\n'
  192. m2 = f'before: [{self.p.before}]\n'
  193. m3 = f'sent value: [{self.sent_value}]' if self.sent_value is not None else ''
  194. raise pexpect.TIMEOUT(m1+m2+m3) from e
  195. if cfg.debug_pexpect:
  196. debug_pexpect_msg(self.p)
  197. if cfg.verbose and not isinstance(s, str):
  198. msg_r(f' ==> {ret} ')
  199. if ret == -1:
  200. die(4, f'Error. Expect returned {ret}')
  201. else:
  202. if t:
  203. self.send(t, delay, s)
  204. else:
  205. if not nonl and not silent:
  206. vmsg('')
  207. return ret
  208. def send(self, t, delay=None, s=False):
  209. delay = delay or self.send_delay
  210. if delay:
  211. time.sleep(delay)
  212. if cfg.demo:
  213. time.sleep(0.5)
  214. ret = self.p.send(t) # returns num bytes written
  215. self.sent_value = t if ret else None
  216. if cfg.demo and delay:
  217. time.sleep(delay)
  218. if cfg.verbose:
  219. ls = '' if cfg.debug or not s else ' '
  220. es = '' if s else ' '
  221. yt = yellow('{!r}'.format(t.replace('\n', r'\n')))
  222. msg(f'{ls}SEND {es}{yt}')
  223. return ret
  224. def read(self, n=-1, strip_color=False):
  225. return strip_ansi_escapes(self.p.read(n)).replace('\r', '') if strip_color else self.p.read(n)
  226. def close(self):
  227. if self.pexpect_spawn:
  228. self.p.close()