pexpect.py 7.6 KB

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