pexpect.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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,rdie
  25. from test.common import getrandstr
  26. try:
  27. import pexpect
  28. from pexpect.popen_spawn import PopenSpawn
  29. except:
  30. die(2,red('Pexpect module is missing. Cannnot run test suite'))
  31. def debug_pexpect_msg(p):
  32. if opt.debug_pexpect:
  33. msg('\n{}{}{}'.format(red('BEFORE ['),p.before,red(']')))
  34. msg('{}{}{}'.format(red('MATCH ['),p.after,red(']')))
  35. if g.platform == 'linux' and not opt.pexpect_spawn:
  36. import atexit
  37. atexit.register(lambda: os.system('stty sane'))
  38. NL = '\n'
  39. else:
  40. NL = '\r\n'
  41. class MMGenPexpect(object):
  42. def __init__(self,args,no_output=False):
  43. if opt.direct_exec:
  44. msg('')
  45. from subprocess import call,check_output
  46. f = (call,check_output)[bool(no_output)]
  47. ret = f([args[0]] + args[1:])
  48. if f == call and ret != 0:
  49. die(1,red('ERROR: process returned a non-zero exit status ({})'.format(ret)))
  50. else:
  51. if opt.pexpect_spawn:
  52. self.p = pexpect.spawn(args[0],args[1:],encoding='utf8')
  53. self.p.delaybeforesend = 0
  54. else:
  55. self.p = PopenSpawn(args,encoding='utf8')
  56. # self.p.delaybeforesend = 0 # TODO: try this here too
  57. if opt.exact_output: self.p.logfile = sys.stdout
  58. self.req_exit_val = 0
  59. self.skip_ok = False
  60. def do_decrypt_ka_data(self,hp,pw,desc='key-address data',check=True,have_yes_opt=False):
  61. # self.hash_preset(desc,hp)
  62. self.passphrase(desc,pw)
  63. if not have_yes_opt:
  64. self.expect('Check key-to-address validity? (y/N): ',('n','y')[check])
  65. def view_tx(self,view):
  66. self.expect('View.* transaction.*\? .*: ',view,regex=True)
  67. if view not in 'n\n':
  68. self.expect('to continue: ','\n')
  69. def do_comment(self,add_comment,has_label=False):
  70. p = ('Add a comment to transaction','Edit transaction comment')[has_label]
  71. self.expect('{}? (y/N): '.format(p),('n','y')[bool(add_comment)])
  72. if add_comment:
  73. self.expect('Comment: ',add_comment+'\n')
  74. def ok(self):
  75. ret = self.p.wait()
  76. if ret != self.req_exit_val and not opt.coverage:
  77. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  78. if opt.profile: return
  79. if not self.skip_ok:
  80. sys.stderr.write(green('OK\n') if opt.exact_output or opt.verbose else (' OK\n'))
  81. return self
  82. def license(self):
  83. if 'MMGEN_NO_LICENSE' in os.environ: return
  84. self.expect("'w' for conditions and warranty info, or 'c' to continue: ",'c')
  85. def label(self,label='Test Label (UTF-8) α'):
  86. self.expect('Enter a wallet label, or hit ENTER for no label: ',label+'\n')
  87. def usr_rand_out(self,saved=False):
  88. fs = 'Generating encryption key from OS random data plus {}user-supplied entropy'
  89. self.expect(fs.format(('','saved ')[saved]))
  90. def usr_rand(self,num_chars):
  91. if opt.usr_random:
  92. self.interactive()
  93. self.send('\n')
  94. else:
  95. rand_chars = list(getrandstr(num_chars,no_space=True))
  96. vmsg_r('SEND ')
  97. while rand_chars:
  98. ch = rand_chars.pop(0)
  99. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  100. ret = self.expect('left: ',ch,delay=0.005)
  101. self.expect('ENTER to continue: ','\n')
  102. def passphrase_new(self,desc,passphrase):
  103. self.expect('Enter passphrase for {}: '.format(desc),passphrase+'\n')
  104. self.expect('Repeat passphrase: ',passphrase+'\n')
  105. def passphrase(self,desc,passphrase,pwtype=''):
  106. if pwtype: pwtype += ' '
  107. self.expect('Enter {}passphrase for {}.*?: '.format(pwtype,desc),passphrase+'\n',regex=True)
  108. def hash_preset(self,desc,preset=''):
  109. self.expect('Enter hash preset for {}'.format(desc))
  110. self.expect('or hit ENTER .*?:',str(preset)+'\n',regex=True)
  111. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  112. s1 = '{} written to file '.format(desc)
  113. s2 = query + "Type uppercase 'YES' to confirm: "
  114. ret = self.expect(([s1,s2],s1)[overwrite_unlikely])
  115. if ret == 1:
  116. self.send('YES\n')
  117. return self.expect_getend("Overwriting file '").rstrip("'")
  118. self.expect(NL,nonl=True)
  119. outfile = self.p.before.strip().strip("'")
  120. if opt.debug_pexpect:
  121. rmsg('Outfile [{}]'.format(outfile))
  122. vmsg('{} file: {}'.format(desc,cyan(outfile.replace("'",''))))
  123. return outfile
  124. def no_overwrite(self):
  125. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  126. self.expect('Exiting at user request')
  127. def expect_getend(self,s,regex=False):
  128. ret = self.expect(s,regex=regex,nonl=True)
  129. debug_pexpect_msg(self.p)
  130. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  131. self.expect(NL,nonl=True,silent=True)
  132. debug_pexpect_msg(self.p)
  133. end = self.p.before
  134. if not g.debug:
  135. vmsg(' ==> {}'.format(cyan(end)))
  136. return end
  137. def interactive(self):
  138. return self.p.interact() # interact() not available with popen_spawn
  139. def kill(self,signal):
  140. return self.p.kill(signal)
  141. def expect(self,s,t='',delay=None,regex=False,nonl=False,silent=False):
  142. delay = delay or (0,0.3)[bool(opt.buf_keypress)]
  143. if not silent:
  144. if opt.verbose:
  145. quo = ('',"'")[type(s) == str]
  146. msg_r('EXPECT {}'.format(yellow(quo+str(s)+quo)))
  147. elif not opt.exact_output: msg_r('+')
  148. try:
  149. if s == '':
  150. ret = 0
  151. else:
  152. f = (self.p.expect_exact,self.p.expect)[bool(regex)]
  153. ret = f(s,timeout=(60,5)[bool(opt.debug_pexpect)])
  154. except pexpect.TIMEOUT:
  155. if opt.debug_pexpect: raise
  156. quo = ('',"'")[type(s) == str]
  157. rdie(1,red('\nERROR. Expect {}{}{} timed out. Exiting'.format(quo,s,quo)))
  158. debug_pexpect_msg(self.p)
  159. if opt.verbose and type(s) != str:
  160. msg_r(' ==> {} '.format(ret))
  161. if ret == -1:
  162. rdie(1,'Error. Expect returned {}'.format(ret))
  163. else:
  164. if t == '':
  165. if not nonl and not silent: vmsg('')
  166. else:
  167. self.send(t,delay,s)
  168. return ret
  169. def send(self,t,delay=None,s=False):
  170. delay = delay or (0,0.3)[bool(opt.buf_keypress)]
  171. if delay: time.sleep(delay)
  172. ret = self.p.send(t) # returns num bytes written
  173. if delay: time.sleep(delay)
  174. if opt.verbose:
  175. ls = (' ','')[bool(opt.debug or not s)]
  176. es = (' ','')[bool(s)]
  177. msg('{}SEND {}{}'.format(ls,es,yellow("'{}'".format(t.replace('\n',r'\n')))))
  178. return ret
  179. def read(self,n=-1):
  180. return self.p.read(n)
  181. def close(self):
  182. if opt.pexpect_spawn:
  183. self.p.close()