pexpect.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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.include.pexpect: pexpect implementation for MMGen test suites
  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 .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 MMGenPexpect:
  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. direct_exec = False ):
  44. self.pexpect_spawn = pexpect_spawn
  45. self.send_delay = send_delay
  46. self.req_exit_val = 0
  47. self.skip_ok = False
  48. self.sent_value = None
  49. self.spawn_env = spawn_env
  50. if direct_exec or cfg.direct_exec:
  51. from subprocess import Popen,DEVNULL
  52. redir = DEVNULL if (no_output or not cfg.exact_output) else None
  53. self.ep = Popen([args[0]] + args[1:], stderr=redir, env=spawn_env )
  54. else:
  55. timeout = int(timeout or cfg.pexpect_timeout or 0) or (60,5)[bool(cfg.debug_pexpect)]
  56. if pexpect_spawn:
  57. self.p = pexpect.spawn(args[0],args[1:],encoding='utf8',timeout=timeout,env=spawn_env)
  58. else:
  59. self.p = PopenSpawn(args,encoding='utf8',timeout=timeout,env=spawn_env)
  60. if cfg.exact_output:
  61. self.p.logfile = sys.stdout
  62. def do_decrypt_ka_data(
  63. self,
  64. pw,
  65. desc = 'key-address data',
  66. check = True,
  67. have_yes_opt = False):
  68. self.passphrase(desc,pw)
  69. if not have_yes_opt:
  70. self.expect('Check key-to-address validity? (y/N): ',('n','y')[check])
  71. def view_tx(self,view):
  72. self.expect(r'View.* transaction.*\? .*: ',view,regex=True)
  73. if view not in 'n\n':
  74. self.expect('to continue: ','\n')
  75. def do_comment(self,add_comment,has_label=False):
  76. p = ('Add a comment to transaction','Edit transaction comment')[has_label]
  77. self.expect(f'{p}? (y/N): ',('n','y')[bool(add_comment)])
  78. if add_comment:
  79. self.expect('Comment: ',add_comment+'\n')
  80. def ok(self):
  81. if not self.pexpect_spawn:
  82. self.p.sendeof()
  83. self.p.read()
  84. ret = self.p.wait()
  85. if ret != self.req_exit_val and not cfg.coverage:
  86. die( 'TestSuiteSpawnedScriptException', f'Spawned script exited with value {ret}' )
  87. if cfg.profile:
  88. return
  89. if not self.skip_ok:
  90. m = 'OK\n' if ret == 0 else f'OK[{ret}]\n'
  91. sys.stderr.write( green(m) if cfg.exact_output or cfg.verbose else ' '+m )
  92. return self
  93. def license(self):
  94. if self.spawn_env.get('MMGEN_NO_LICENSE'):
  95. return
  96. self.expect("'w' for conditions and warranty info, or 'c' to continue: ",'c')
  97. def label(self,label='Test Label (UTF-8) α'):
  98. self.expect('Enter a wallet label, or hit ENTER for no label: ',label+'\n')
  99. def usr_rand(self,num_chars):
  100. if cfg.usr_random:
  101. self.interactive()
  102. self.send('\n')
  103. else:
  104. rand_chars = list(getrandstr(num_chars,no_space=True))
  105. vmsg_r('SEND ')
  106. while rand_chars:
  107. ch = rand_chars.pop(0)
  108. msg_r(yellow(ch)+' ' if cfg.verbose else '+')
  109. self.expect('left: ',ch,delay=0.005)
  110. self.expect('ENTER to continue: ','\n')
  111. def passphrase_new(self,desc,passphrase):
  112. self.expect(f'Enter passphrase for {desc}: ',passphrase+'\n')
  113. self.expect('Repeat passphrase: ',passphrase+'\n')
  114. def passphrase(self,desc,passphrase,pwtype=''):
  115. if pwtype:
  116. pwtype += ' '
  117. self.expect(f'Enter {pwtype}passphrase for {desc}.*?: ',passphrase+'\n',regex=True)
  118. def hash_preset(self,desc,preset=''):
  119. self.expect(f'Enter hash preset for {desc}')
  120. self.expect('or hit ENTER .*?:',str(preset)+'\n',regex=True)
  121. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? '):
  122. s1 = f'{desc} written to file '
  123. s2 = query + "Type uppercase 'YES' to confirm: "
  124. ret = self.expect(([s1,s2],s1)[overwrite_unlikely])
  125. if ret == 1:
  126. self.send('YES\n')
  127. return self.expect_getend("Overwriting file '").rstrip("'")
  128. self.expect(NL,nonl=True)
  129. outfile = self.p.before.strip().strip("'")
  130. if cfg.debug_pexpect:
  131. rmsg(f'Outfile [{outfile}]')
  132. vmsg('{} file: {}'.format( desc, cyan(outfile.replace('"',"")) ))
  133. return outfile
  134. def hincog_create(self,hincog_bytes):
  135. ret = self.expect(['Create? (Y/n): ',"'YES' to confirm: "])
  136. if ret == 0:
  137. self.send('\n')
  138. self.expect('Enter file size: ',str(hincog_bytes)+'\n')
  139. else:
  140. self.send('YES\n')
  141. return ret
  142. def no_overwrite(self):
  143. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  144. self.expect('Exiting at user request')
  145. def expect_getend(self,s,regex=False):
  146. self.expect(s,regex=regex,nonl=True)
  147. if cfg.debug_pexpect:
  148. debug_pexpect_msg(self.p)
  149. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  150. self.expect(NL,nonl=True,silent=True)
  151. if cfg.debug_pexpect:
  152. debug_pexpect_msg(self.p)
  153. end = self.p.before.rstrip()
  154. if not cfg.debug:
  155. vmsg(f' ==> {cyan(end)}')
  156. return end
  157. def interactive(self):
  158. return self.p.interact() # interact() not available with popen_spawn
  159. def kill(self,signal):
  160. return self.p.kill(signal)
  161. def match_expect_list(self,expect_list,greedy=False):
  162. allrep = '.*' if greedy else '.*?'
  163. expect = (
  164. r'(\b|\s)' +
  165. fr'\s{allrep}\s'.join(s.replace(r'.',r'\.').replace(' ',r'\s+') for s in expect_list) +
  166. r'(\b|\s)' )
  167. import re
  168. m = re.search( expect, self.read(strip_color=True), re.DOTALL )
  169. assert m, f'No match found for regular expression {expect!r}'
  170. return m
  171. def expect(self,s,t='',delay=None,regex=False,nonl=False,silent=False):
  172. if not silent:
  173. if cfg.verbose:
  174. msg_r('EXPECT ' + yellow(str(s)))
  175. elif not cfg.exact_output:
  176. msg_r('+')
  177. try:
  178. ret = (self.p.expect_exact,self.p.expect)[bool(regex)](s) if s else 0
  179. except pexpect.TIMEOUT as e:
  180. if cfg.debug_pexpect:
  181. raise
  182. m1 = f'\nERROR. Expect {s!r} timed out. Exiting\n'
  183. m2 = f'before: [{self.p.before}]\n'
  184. m3 = f'sent value: [{self.sent_value}]' if self.sent_value is not None else ''
  185. raise pexpect.TIMEOUT(m1+m2+m3) from e
  186. if cfg.debug_pexpect:
  187. debug_pexpect_msg(self.p)
  188. if cfg.verbose and not isinstance(s,str):
  189. msg_r(f' ==> {ret} ')
  190. if ret == -1:
  191. die(4,f'Error. Expect returned {ret}')
  192. else:
  193. if t:
  194. self.send(t,delay,s)
  195. else:
  196. if not nonl and not silent:
  197. vmsg('')
  198. return ret
  199. def send(self,t,delay=None,s=False):
  200. delay = delay or self.send_delay
  201. if delay:
  202. time.sleep(delay)
  203. ret = self.p.send(t) # returns num bytes written
  204. self.sent_value = t if ret else None
  205. if cfg.demo and delay:
  206. time.sleep(delay)
  207. if cfg.verbose:
  208. ls = '' if cfg.debug or not s else ' '
  209. es = '' if s else ' '
  210. yt = yellow('{!r}'.format( t.replace('\n',r'\n') ))
  211. msg(f'{ls}SEND {es}{yt}')
  212. return ret
  213. def read(self,n=-1,strip_color=False):
  214. return strip_ansi_escapes(self.p.read(n)).replace('\r','') if strip_color else self.p.read(n)
  215. def close(self):
  216. if self.pexpect_spawn:
  217. self.p.close()