pexpect.py 7.5 KB

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