pexpect.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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/pexpect.py: 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):
  37. self.pexpect_spawn = pexpect_spawn
  38. self.req_exit_val = 0
  39. self.skip_ok = False
  40. self.sent_value = None
  41. if opt.direct_exec:
  42. msg('')
  43. from subprocess import run,DEVNULL
  44. run([args[0]] + args[1:],check=True,stdout=DEVNULL if no_output else None)
  45. else:
  46. timeout = int(opt.pexpect_timeout or 0) or (60,5)[bool(opt.debug_pexpect)]
  47. if pexpect_spawn:
  48. self.p = pexpect.spawn(args[0],args[1:],encoding='utf8',timeout=timeout,env=env)
  49. else:
  50. self.p = PopenSpawn(args,encoding='utf8',timeout=timeout,env=env)
  51. if opt.exact_output:
  52. self.p.logfile = sys.stdout
  53. def do_decrypt_ka_data(self,hp,pw,desc='key-address data',check=True,have_yes_opt=False):
  54. # self.hash_preset(desc,hp)
  55. self.passphrase(desc,pw)
  56. if not have_yes_opt:
  57. self.expect('Check key-to-address validity? (y/N): ',('n','y')[check])
  58. def view_tx(self,view):
  59. self.expect(r'View.* transaction.*\? .*: ',view,regex=True)
  60. if view not in 'n\n':
  61. self.expect('to continue: ','\n')
  62. def do_comment(self,add_comment,has_label=False):
  63. p = ('Add a comment to transaction','Edit transaction comment')[has_label]
  64. self.expect(f'{p}? (y/N): ',('n','y')[bool(add_comment)])
  65. if add_comment:
  66. self.expect('Comment: ',add_comment+'\n')
  67. def ok(self):
  68. if not self.pexpect_spawn:
  69. self.p.sendeof()
  70. self.p.read()
  71. ret = self.p.wait()
  72. if ret != self.req_exit_val and not opt.coverage:
  73. die(1,red(f'test.py: spawned program exited with value {ret}'))
  74. if opt.profile:
  75. return
  76. if not self.skip_ok:
  77. m = 'OK\n' if ret == 0 else f'OK[{ret}]\n'
  78. sys.stderr.write( green(m) if opt.exact_output or opt.verbose else ' '+m )
  79. return self
  80. def license(self):
  81. if 'MMGEN_NO_LICENSE' in os.environ: return
  82. self.expect("'w' for conditions and warranty info, or 'c' to continue: ",'c')
  83. def label(self,label='Test Label (UTF-8) α'):
  84. self.expect('Enter a wallet label, or hit ENTER for no label: ',label+'\n')
  85. def usr_rand(self,num_chars):
  86. if opt.usr_random:
  87. self.interactive()
  88. self.send('\n')
  89. else:
  90. rand_chars = list(getrandstr(num_chars,no_space=True))
  91. vmsg_r('SEND ')
  92. while rand_chars:
  93. ch = rand_chars.pop(0)
  94. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  95. ret = self.expect('left: ',ch,delay=0.005)
  96. self.expect('ENTER to continue: ','\n')
  97. def passphrase_new(self,desc,passphrase):
  98. self.expect(f'Enter passphrase for {desc}: ',passphrase+'\n')
  99. self.expect('Repeat passphrase: ',passphrase+'\n')
  100. def passphrase(self,desc,passphrase,pwtype=''):
  101. if pwtype: pwtype += ' '
  102. self.expect(f'Enter {pwtype}passphrase for {desc}.*?: ',passphrase+'\n',regex=True)
  103. def hash_preset(self,desc,preset=''):
  104. self.expect(f'Enter hash preset for {desc}')
  105. self.expect('or hit ENTER .*?:',str(preset)+'\n',regex=True)
  106. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  107. s1 = f'{desc} written to file '
  108. s2 = query + "Type uppercase 'YES' to confirm: "
  109. ret = self.expect(([s1,s2],s1)[overwrite_unlikely])
  110. if ret == 1:
  111. self.send('YES\n')
  112. return self.expect_getend("Overwriting file '").rstrip("'")
  113. self.expect(NL,nonl=True)
  114. outfile = self.p.before.strip().strip("'")
  115. if opt.debug_pexpect:
  116. rmsg(f'Outfile [{outfile}]')
  117. vmsg('{} file: {}'.format( desc, cyan(outfile.replace('"',"")) ))
  118. return outfile
  119. def hincog_create(self,hincog_bytes):
  120. ret = self.expect(['Create? (Y/n): ',"'YES' to confirm: "])
  121. if ret == 0:
  122. self.send('\n')
  123. self.expect('Enter file size: ',str(hincog_bytes)+'\n')
  124. else:
  125. self.send('YES\n')
  126. return ret
  127. def no_overwrite(self):
  128. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  129. self.expect('Exiting at user request')
  130. def expect_getend(self,s,regex=False):
  131. ret = self.expect(s,regex=regex,nonl=True)
  132. if opt.debug_pexpect:
  133. debug_pexpect_msg(self.p)
  134. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  135. self.expect(NL,nonl=True,silent=True)
  136. if opt.debug_pexpect:
  137. debug_pexpect_msg(self.p)
  138. end = self.p.before.rstrip()
  139. if not g.debug:
  140. vmsg(f' ==> {cyan(end)}')
  141. return end
  142. def interactive(self):
  143. return self.p.interact() # interact() not available with popen_spawn
  144. def kill(self,signal):
  145. return self.p.kill(signal)
  146. def match_expect_list(self,expect_list,greedy=False):
  147. res = strip_ansi_escapes(self.read()).replace('\r','')
  148. allrep = '.*' if greedy else '.*?'
  149. expect = (
  150. r'(\b|\s)' +
  151. fr'\s{allrep}\s'.join(s.replace(r'.',r'\.').replace(' ',r'\s+') for s in expect_list) +
  152. r'(\b|\s)' )
  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. delay = delay or (0,0.3)[bool(opt.buf_keypress)]
  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. die(2,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 (0,0.3)[bool(opt.buf_keypress)]
  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()