pexpect.py 7.4 KB

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