pexpect.py 7.3 KB

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