mmgen_pexpect.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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/mmgen_pexpect.py: pexpect implementation for MMGen test suites
  20. """
  21. from mmgen.common import *
  22. from mmgen.test import getrandstr,ok,init_coverage
  23. try:
  24. import pexpect
  25. from pexpect.popen_spawn import PopenSpawn
  26. except:
  27. die(2,red('Pexpect module is missing. Cannnot run test suite'))
  28. if opt.buf_keypress:
  29. send_delay = 0.3
  30. else:
  31. send_delay = 0
  32. os.environ['MMGEN_DISABLE_HOLD_PROTECT'] = '1'
  33. def my_send(p,t,delay=send_delay,s=False):
  34. if delay: time.sleep(delay)
  35. ret = p.send(t) # returns num bytes written
  36. if delay: time.sleep(delay)
  37. if opt.verbose:
  38. ls = (' ','')[bool(opt.debug or not s)]
  39. es = (' ','')[bool(s)]
  40. msg('{}SEND {}{}'.format(ls,es,yellow("'{}'".format(t.replace('\n',r'\n')))))
  41. return ret
  42. def my_expect(p,s,t='',delay=send_delay,regex=False,nonl=False,silent=False):
  43. quo = ('',"'")[type(s) == str]
  44. if not silent:
  45. if opt.verbose: msg_r('EXPECT {}'.format(yellow(quo+str(s)+quo)))
  46. elif not opt.exact_output: msg_r('+')
  47. try:
  48. if s == '': ret = 0
  49. else:
  50. f = (p.expect_exact,p.expect)[bool(regex)]
  51. ret = f(s,timeout=(60,5)[bool(opt.debug_pexpect)])
  52. except pexpect.TIMEOUT:
  53. if opt.debug_pexpect: raise
  54. rdie(1,red('\nERROR. Expect {}{}{} timed out. Exiting'.format(quo,s,quo)))
  55. debug_pexpect_msg(p)
  56. if opt.verbose and type(s) != str:
  57. msg_r(' ==> {} '.format(ret))
  58. if ret == -1:
  59. rdie(1,'Error. Expect returned {}'.format(ret))
  60. else:
  61. if t == '':
  62. if not nonl and not silent: vmsg('')
  63. else:
  64. my_send(p,t,delay,s)
  65. return ret
  66. def debug_pexpect_msg(p):
  67. if opt.debug_pexpect:
  68. msg('\n{}{}{}'.format(red('BEFORE ['),p.before,red(']')))
  69. msg('{}{}{}'.format(red('MATCH ['),p.after,red(']')))
  70. data_dir = os.path.join('test','data_dir'+('','-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])
  71. class MMGenPexpect(object):
  72. NL = '\r\n'
  73. if g.platform == 'linux' and opt.popen_spawn:
  74. import atexit
  75. atexit.register(lambda: os.system('stty sane'))
  76. NL = '\n'
  77. def __init__(self,name,mmgen_cmd,cmd_args,desc,
  78. no_output=False,passthru_args=[],msg_only=False,no_msg=False,log_fd=None):
  79. cmd_args = ['--{}{}'.format(k.replace('_','-'),
  80. '='+getattr(opt,k) if getattr(opt,k) != True else ''
  81. ) for k in passthru_args if getattr(opt,k)] \
  82. + ['--data-dir='+data_dir] + cmd_args
  83. if g.platform == 'win': cmd,args = 'python3',[mmgen_cmd]+cmd_args
  84. else: cmd,args = mmgen_cmd,cmd_args
  85. for i in args:
  86. if type(i) is not str:
  87. m1 = 'Error: missing input files in cmd line?:'
  88. m2 = '\nName: {}\nCmd: {}\nCmd args: {}'
  89. die(2,(m1+m2).format(name,cmd,args))
  90. # if opt.popen_spawn:
  91. if True:
  92. args = ['{q}{}{q}'.format(a,q="'" if ' ' in a else '') for a in args]
  93. cmd_str = '{} {}'.format(cmd,' '.join(args)).replace('\\','/')
  94. if opt.coverage:
  95. fs = 'python3 -m trace --count --coverdir={} --file={} {c}'
  96. cmd_str = fs.format(*init_coverage(),c=cmd_str)
  97. if opt.log:
  98. log_fd.write(cmd_str.encode()+'\n')
  99. if not no_msg:
  100. if opt.verbose or opt.print_cmdline or opt.exact_output:
  101. clr1,clr2,eol = ((green,cyan,'\n'),(nocolor,nocolor,' '))[bool(opt.print_cmdline)]
  102. msg_r(green('Testing: {}\n'.format(desc)))
  103. if not msg_only:
  104. s = repr(cmd_str) if g.platform == 'win' else cmd_str
  105. msg_r(clr1('Executing {}{}'.format(clr2(s),eol)))
  106. else:
  107. m = 'Testing {}: '.format(desc)
  108. msg_r(m)
  109. if msg_only: return
  110. if opt.direct_exec:
  111. msg('')
  112. from subprocess import call,check_output
  113. f = (call,check_output)[bool(no_output)]
  114. ret = f([cmd] + args)
  115. if f == call and ret != 0:
  116. die(1,red('ERROR: process returned a non-zero exit status ({})'.format(ret)))
  117. else:
  118. if opt.traceback:
  119. tc = 'scripts/traceback_run.py'
  120. cmd,args = tc,[cmd]+args
  121. cmd_str = tc + ' ' + cmd_str
  122. # Msg('\ncmd_str: {}'.format(cmd_str))
  123. if opt.popen_spawn:
  124. # NOTE: the following is outdated for Python 3
  125. # PopenSpawn() requires cmd string to be bytes. However, it autoconverts unicode
  126. # input to bytes, though this behavior seems to be undocumented. Setting 'encoding'
  127. # to 'UTF-8' will cause pexpect to reject non-unicode string input.
  128. self.p = PopenSpawn(cmd_str,encoding='utf8')
  129. else:
  130. self.p = pexpect.spawn(cmd_str,encoding='utf8')
  131. self.p.delaybeforesend = 0
  132. if opt.exact_output: self.p.logfile = sys.stdout
  133. def do_decrypt_ka_data(self,hp,pw,desc='key-address data',check=True):
  134. self.hash_preset(desc,hp)
  135. self.passphrase(desc,pw)
  136. self.expect('Check key-to-address validity? (y/N): ',('n','y')[check])
  137. def view_tx(self,view):
  138. self.expect('View.* transaction.*\? .*: ',view,regex=True)
  139. if view not in 'n\n':
  140. self.expect('to continue: ','\n')
  141. def do_comment(self,add_comment,has_label=False):
  142. p = ('Add a comment to transaction','Edit transaction comment')[has_label]
  143. self.expect('{}? (y/N): '.format(p),('n','y')[bool(add_comment)])
  144. if add_comment:
  145. self.expect('Comment: ',add_comment+'\n')
  146. def ok(self,exit_val=0):
  147. ret = self.p.wait()
  148. if ret not in (exit_val,None) and not opt.coverage: # Some cmds exit with None
  149. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  150. if opt.profile: return
  151. if opt.verbose or opt.exact_output:
  152. sys.stderr.write(green('OK\n'))
  153. else: msg(' OK')
  154. def cmp_or_die(self,s,t,skip_ok=False,exit_val=0):
  155. ret = self.p.wait()
  156. if ret != exit_val:
  157. rdie(1,'test.py: spawned program exited with value {}'.format(ret))
  158. if s == t:
  159. if not skip_ok: ok()
  160. else:
  161. fs = 'ERROR: recoded data:\n{}\ndiffers from original data:\n{}'
  162. rdie(3,fs.format(repr(t),repr(s)))
  163. def license(self):
  164. if 'MMGEN_NO_LICENSE' in os.environ: return
  165. p = "'w' for conditions and warranty info, or 'c' to continue: "
  166. my_expect(self.p,p,'c')
  167. def label(self,label='Test Label (UTF-8) α'):
  168. p = 'Enter a wallet label, or hit ENTER for no label: '
  169. my_expect(self.p,p,label+'\n')
  170. def usr_rand_out(self,saved=False):
  171. fs = 'Generating encryption key from OS random data plus {}user-supplied entropy'
  172. my_expect(self.p,fs.format(('','saved ')[saved]))
  173. def usr_rand(self,num_chars):
  174. if opt.usr_random:
  175. self.interactive()
  176. my_send(self.p,'\n')
  177. else:
  178. rand_chars = list(getrandstr(num_chars,no_space=True))
  179. vmsg_r('SEND ')
  180. while rand_chars:
  181. ch = rand_chars.pop(0)
  182. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  183. ret = my_expect(self.p,'left: ',ch,delay=0.005)
  184. my_expect(self.p,'ENTER to continue: ','\n')
  185. def passphrase_new(self,desc,passphrase):
  186. my_expect(self.p,'Enter passphrase for {}: '.format(desc),passphrase+'\n')
  187. my_expect(self.p,'Repeat passphrase: ',passphrase+'\n')
  188. def passphrase(self,desc,passphrase,pwtype=''):
  189. if pwtype: pwtype += ' '
  190. my_expect(self.p,
  191. 'Enter {}passphrase for {}.*?: '.format(pwtype,desc),
  192. passphrase+'\n',regex=True)
  193. def hash_preset(self,desc,preset=''):
  194. my_expect(self.p,'Enter hash preset for {}'.format(desc))
  195. my_expect(self.p,'or hit ENTER .*?:',str(preset)+'\n',regex=True)
  196. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  197. s1 = '{} written to file '.format(desc)
  198. s2 = query + "Type uppercase 'YES' to confirm: "
  199. ret = my_expect(self.p,([s1,s2],s1)[overwrite_unlikely])
  200. if ret == 1:
  201. my_send(self.p,'YES\n')
  202. # if oo:
  203. outfile = self.expect_getend("Overwriting file '").rstrip("'")
  204. return outfile
  205. # else:
  206. # ret = my_expect(self.p,s1)
  207. self.expect(self.NL,nonl=True)
  208. outfile = self.p.before.strip().strip("'")
  209. if opt.debug_pexpect: rmsg('Outfile [{}]'.format(outfile))
  210. vmsg('{} file: {}'.format(desc,cyan(outfile.replace("'",''))))
  211. return outfile
  212. def no_overwrite(self):
  213. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  214. self.expect('Exiting at user request')
  215. def expect_getend(self,s,regex=False):
  216. ret = self.expect(s,regex=regex,nonl=True)
  217. debug_pexpect_msg(self.p)
  218. # end = self.readline().strip()
  219. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  220. self.expect(self.NL,nonl=True,silent=True)
  221. debug_pexpect_msg(self.p)
  222. end = self.p.before
  223. if not g.debug:
  224. vmsg(' ==> {}'.format(cyan(end)))
  225. return end
  226. def interactive(self):
  227. return self.p.interact() # interact() not available with popen_spawn
  228. def kill(self,signal):
  229. return self.p.kill(signal)
  230. def logfile(self,arg):
  231. self.p.logfile = arg
  232. def expect(self,*args,**kwargs):
  233. return my_expect(self.p,*args,**kwargs)
  234. def send(self,*args,**kwargs):
  235. return my_send(self.p,*args,**kwargs)
  236. # def readline(self):
  237. # return self.p.readline()
  238. # def readlines(self):
  239. # return [l.rstrip()+'\n' for l in self.p.readlines()]
  240. def read(self,n=None):
  241. if n: return self.p.read(n)
  242. else: return self.p.read()
  243. def close(self):
  244. if not opt.popen_spawn:
  245. self.p.close()