mmgen_pexpect.py 9.5 KB

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