mmgen_pexpect.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2018 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. errmsg(red('\nERROR. Expect {}{}{} timed out. Exiting'.format(quo,s,quo)))
  55. sys.exit(1)
  56. debug_pexpect_msg(p)
  57. if opt.verbose and type(s) != str:
  58. msg_r(' ==> {} '.format(ret))
  59. if ret == -1:
  60. errmsg('Error. Expect returned {}'.format(ret))
  61. sys.exit(1)
  62. else:
  63. if t == '':
  64. if not nonl and not silent: vmsg('')
  65. else:
  66. my_send(p,t,delay,s)
  67. return ret
  68. def debug_pexpect_msg(p):
  69. if opt.debug_pexpect:
  70. errmsg('\n{}{}{}'.format(red('BEFORE ['),p.before,red(']')))
  71. errmsg('{}{}{}'.format(red('MATCH ['),p.after,red(']')))
  72. data_dir = os.path.join('test','data_dir'+('','-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])
  73. class MMGenPexpect(object):
  74. NL = '\r\n'
  75. if g.platform == 'linux' and opt.popen_spawn:
  76. import atexit
  77. atexit.register(lambda: os.system('stty sane'))
  78. NL = '\n'
  79. def __init__(self,name,mmgen_cmd,cmd_args,desc,
  80. no_output=False,passthru_args=[],msg_only=False,no_msg=False,log_fd=None):
  81. cmd_args = ['--{}{}'.format(k.replace('_','-'),
  82. '='+getattr(opt,k) if getattr(opt,k) != True else ''
  83. ) for k in passthru_args if getattr(opt,k)] \
  84. + ['--data-dir='+data_dir] + cmd_args
  85. if g.platform == 'win': cmd,args = 'python3',[mmgen_cmd]+cmd_args
  86. else: cmd,args = mmgen_cmd,cmd_args
  87. for i in args:
  88. if type(i) not in (str,str):
  89. m1 = 'Error: missing input files in cmd line?:'
  90. m2 = '\nName: {}\nCmd: {}\nCmd args: {}'
  91. die(2,(m1+m2).format(name,cmd,args))
  92. if opt.popen_spawn:
  93. args = ['{q}{}{q}'.format(a,q="'" if ' ' in a else '') for a in args]
  94. cmd_str = '{} {}'.format(cmd,' '.join(args)).replace('\\','/')
  95. if opt.coverage:
  96. fs = 'python3 -m trace --count --coverdir={} --file={} {c}'
  97. cmd_str = fs.format(*init_coverage(),c=cmd_str)
  98. if opt.log:
  99. log_fd.write(cmd_str.encode()+'\n')
  100. if not no_msg:
  101. if opt.verbose or opt.print_cmdline or opt.exact_output:
  102. clr1,clr2,eol = ((green,cyan,'\n'),(nocolor,nocolor,' '))[bool(opt.print_cmdline)]
  103. msg_r(green('Testing: {}\n'.format(desc)))
  104. if not msg_only:
  105. s = repr(cmd_str) if g.platform == 'win' else cmd_str
  106. msg_r(clr1('Executing {}{}'.format(clr2(s),eol)))
  107. else:
  108. m = 'Testing {}: '.format(desc)
  109. msg_r(m)
  110. if msg_only: return
  111. if opt.direct_exec:
  112. msg('')
  113. from subprocess import call,check_output
  114. f = (call,check_output)[bool(no_output)]
  115. ret = f([cmd] + args)
  116. if f == call and ret != 0:
  117. die(1,red('ERROR: process returned a non-zero exit status ({})'.format(ret)))
  118. else:
  119. if opt.traceback:
  120. tc = 'scripts/traceback_run.py'
  121. cmd,args = tc,[cmd]+args
  122. cmd_str = tc + ' ' + cmd_str
  123. # Msg('\ncmd_str: {}'.format(cmd_str))
  124. if opt.popen_spawn:
  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,args)
  131. if opt.exact_output: self.p.logfile = sys.stdout
  132. def do_decrypt_ka_data(self,hp,pw,desc='key-address data',check=True):
  133. self.hash_preset(desc,hp)
  134. self.passphrase(desc,pw)
  135. self.expect('Check key-to-address validity? (y/N): ',('n','y')[check])
  136. def view_tx(self,view):
  137. self.expect('View.* transaction.*\? .*: ',view,regex=True)
  138. if view not in 'n\n':
  139. self.expect('to continue: ','\n')
  140. def do_comment(self,add_comment,has_label=False):
  141. p = ('Add a comment to transaction','Edit transaction comment')[has_label]
  142. self.expect('{}? (y/N): '.format(p),('n','y')[bool(add_comment)])
  143. if add_comment:
  144. self.expect('Comment: ',add_comment+'\n')
  145. def ok(self,exit_val=0):
  146. ret = self.p.wait()
  147. # Msg('expect: {} got: {}'.format(exit_val,ret))
  148. if ret != exit_val and not opt.coverage:
  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. my_expect(self.p,'symbols left: ','x')
  180. try:
  181. vmsg_r('SEND ')
  182. while self.p.expect('left: ',0.1) == 0:
  183. ch = rand_chars.pop(0)
  184. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  185. self.p.send(ch)
  186. except:
  187. vmsg('EOT')
  188. my_expect(self.p,'ENTER to continue: ','\n')
  189. def passphrase_new(self,desc,passphrase):
  190. my_expect(self.p,'Enter passphrase for {}: '.format(desc),passphrase+'\n')
  191. my_expect(self.p,'Repeat passphrase: ',passphrase+'\n')
  192. def passphrase(self,desc,passphrase,pwtype=''):
  193. if pwtype: pwtype += ' '
  194. my_expect(self.p,
  195. 'Enter {}passphrase for {}.*?: '.format(pwtype,desc),
  196. passphrase+'\n',regex=True)
  197. def hash_preset(self,desc,preset=''):
  198. my_expect(self.p,'Enter hash preset for {}'.format(desc))
  199. my_expect(self.p,'or hit ENTER .*?:',str(preset)+'\n',regex=True)
  200. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  201. s1 = '{} written to file '.format(desc)
  202. s2 = query + "Type uppercase 'YES' to confirm: "
  203. ret = my_expect(self.p,([s1,s2],s1)[overwrite_unlikely])
  204. if ret == 1:
  205. my_send(self.p,'YES\n')
  206. # if oo:
  207. outfile = self.expect_getend("Overwriting file '").rstrip("'")
  208. return outfile
  209. # else:
  210. # ret = my_expect(self.p,s1)
  211. self.expect(self.NL,nonl=True)
  212. outfile = self.p.before.strip().strip("'")
  213. if opt.debug_pexpect: rmsg('Outfile [{}]'.format(outfile))
  214. vmsg('{} file: {}'.format(desc,cyan(outfile.replace("'",''))))
  215. return outfile
  216. def no_overwrite(self):
  217. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  218. self.expect('Exiting at user request')
  219. def expect_getend(self,s,regex=False):
  220. ret = self.expect(s,regex=regex,nonl=True)
  221. debug_pexpect_msg(self.p)
  222. # end = self.readline().strip()
  223. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  224. self.expect(self.NL,nonl=True,silent=True)
  225. debug_pexpect_msg(self.p)
  226. end = self.p.before
  227. if not g.debug:
  228. vmsg(' ==> {}'.format(cyan(end)))
  229. return end
  230. def interactive(self):
  231. return self.p.interact() # interact() not available with popen_spawn
  232. def kill(self,signal):
  233. return self.p.kill(signal)
  234. def logfile(self,arg):
  235. self.p.logfile = arg
  236. def expect(self,*args,**kwargs):
  237. return my_expect(self.p,*args,**kwargs)
  238. def send(self,*args,**kwargs):
  239. return my_send(self.p,*args,**kwargs)
  240. # def readline(self):
  241. # return self.p.readline()
  242. # def readlines(self):
  243. # return [l.rstrip()+'\n' for l in self.p.readlines()]
  244. def read(self,n=None):
  245. return self.p.read(n)
  246. def close(self):
  247. if not opt.popen_spawn:
  248. self.p.close()