pexpect.py 7.6 KB

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