mmgen_pexpect.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  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
  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('%sSEND %s%s' % (ls,es,yellow("'%s'"%t.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 %s' % 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 %s%s%s timed out. Exiting' % (quo,s,quo)))
  58. sys.exit(1)
  59. debug_pexpect_msg(p)
  60. if opt.debug or (opt.verbose and type(s) != str): msg_r(' ==> %s ' % ret)
  61. if ret == -1:
  62. errmsg('Error. Expect returned %s' % ret)
  63. sys.exit(1)
  64. else:
  65. if t == '':
  66. if not nonl and not silent: vmsg('')
  67. else:
  68. my_send(p,t,delay,s)
  69. return ret
  70. def debug_pexpect_msg(p):
  71. if opt.debug_pexpect:
  72. errmsg('\n{}{}{}'.format(red('BEFORE ['),p.before,red(']')))
  73. errmsg('{}{}{}'.format(red('MATCH ['),p.after,red(']')))
  74. class MMGenPexpect(object):
  75. NL = '\r\n'
  76. if g.platform == 'linux' and opt.popen_spawn:
  77. import atexit
  78. atexit.register(lambda: os.system('stty sane'))
  79. NL = '\n'
  80. def __init__(self,name,mmgen_cmd,cmd_args,desc,no_output=False,passthru_args=[],msg_only=False):
  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='+os.path.join('test','data_dir')] + cmd_args
  85. if g.platform == 'win': cmd,args = 'python',[mmgen_cmd]+cmd_args
  86. else: cmd,args = mmgen_cmd,cmd_args
  87. for i in args:
  88. if type(i) not in (str,unicode):
  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 = [(a,"'{}'".format(a))[' ' in a] for a in args]
  94. cmd_str = '{} {}'.format(cmd,' '.join(args)).replace('\\','/')
  95. if opt.log:
  96. log_fd.write(cmd_str+'\n')
  97. if opt.verbose or opt.print_cmdline or opt.exact_output:
  98. clr1,clr2,eol = ((green,cyan,'\n'),(nocolor,nocolor,' '))[bool(opt.print_cmdline)]
  99. sys.stderr.write(green('Testing: {}\n'.format(desc)))
  100. if not msg_only:
  101. sys.stderr.write(clr1('Executing {}{}'.format(clr2(cmd_str),eol)))
  102. else:
  103. m = 'Testing %s: ' % desc
  104. msg_r(m)
  105. if msg_only: return
  106. if opt.direct_exec:
  107. msg('')
  108. from subprocess import call,check_output
  109. f = (call,check_output)[bool(no_output)]
  110. ret = f([cmd] + args)
  111. if f == call and ret != 0:
  112. m = 'ERROR: process returned a non-zero exit status (%s)'
  113. die(1,red(m % ret))
  114. else:
  115. if opt.traceback:
  116. cmd,args = g.traceback_cmd,[cmd]+args
  117. cmd_str = g.traceback_cmd + ' ' + cmd_str
  118. # Msg('\ncmd_str: {}'.format(cmd_str))
  119. if opt.popen_spawn:
  120. self.p = PopenSpawn(cmd_str)
  121. else:
  122. self.p = pexpect.spawn(cmd,args)
  123. if opt.exact_output: self.p.logfile = sys.stdout
  124. def ok(self,exit_val=0):
  125. ret = self.p.wait()
  126. # Msg('expect: {} got: {}'.format(exit_val,ret))
  127. if ret != exit_val:
  128. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  129. if opt.profile: return
  130. if opt.verbose or opt.exact_output:
  131. sys.stderr.write(green('OK\n'))
  132. else: msg(' OK')
  133. def cmp_or_die(self,s,t,skip_ok=False,exit_val=0):
  134. ret = self.p.wait()
  135. if ret != exit_val:
  136. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  137. if s == t:
  138. if not skip_ok: ok()
  139. else:
  140. sys.stderr.write(red(
  141. 'ERROR: recoded data:\n%s\ndiffers from original data:\n%s\n' %
  142. (repr(t),repr(s))))
  143. sys.exit(3)
  144. def license(self):
  145. if 'MMGEN_NO_LICENSE' in os.environ: return
  146. p = "'w' for conditions and warranty info, or 'c' to continue: "
  147. my_expect(self.p,p,'c')
  148. def label(self,label='Test Label'):
  149. p = 'Enter a wallet label, or hit ENTER for no label: '
  150. my_expect(self.p,p,label+'\n')
  151. def usr_rand_out(self,saved=False):
  152. m = '%suser-supplied entropy' % (('','saved ')[saved])
  153. my_expect(self.p,'Generating encryption key from OS random data plus ' + m)
  154. def usr_rand(self,num_chars):
  155. if opt.usr_random:
  156. self.interactive()
  157. my_send(self.p,'\n')
  158. else:
  159. rand_chars = list(getrandstr(num_chars,no_space=True))
  160. my_expect(self.p,'symbols left: ','x')
  161. try:
  162. vmsg_r('SEND ')
  163. while self.p.expect('left: ',0.1) == 0:
  164. ch = rand_chars.pop(0)
  165. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  166. self.p.send(ch)
  167. except:
  168. vmsg('EOT')
  169. my_expect(self.p,'ENTER to continue: ','\n')
  170. def passphrase_new(self,desc,passphrase):
  171. my_expect(self.p,('Enter passphrase for %s: ' % desc), passphrase+'\n')
  172. my_expect(self.p,'Repeat passphrase: ', passphrase+'\n')
  173. def passphrase(self,desc,passphrase,pwtype=''):
  174. if pwtype: pwtype += ' '
  175. my_expect(self.p,('Enter %spassphrase for %s.*?: ' % (pwtype,desc)),
  176. passphrase+'\n',regex=True)
  177. def hash_preset(self,desc,preset=''):
  178. my_expect(self.p,('Enter hash preset for %s' % desc))
  179. my_expect(self.p,('or hit ENTER .*?:'), str(preset)+'\n',regex=True)
  180. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  181. s1 = '%s written to file ' % desc
  182. s2 = query + "Type uppercase 'YES' to confirm: "
  183. ret = my_expect(self.p,([s1,s2],s1)[overwrite_unlikely])
  184. if ret == 1:
  185. my_send(self.p,'YES\n')
  186. # if oo:
  187. outfile = self.expect_getend("Overwriting file '").rstrip("'")
  188. return outfile
  189. # else:
  190. # ret = my_expect(self.p,s1)
  191. self.expect(self.NL,nonl=True)
  192. outfile = self.p.before.strip().strip("'")
  193. if opt.debug_pexpect: msgred('Outfile [%s]' % outfile)
  194. vmsg('%s file: %s' % (desc,cyan(outfile.replace("'",''))))
  195. return outfile
  196. def no_overwrite(self):
  197. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  198. self.expect('Exiting at user request')
  199. def tx_view(self):
  200. my_expect(self.p,r'View .*?transaction.*? \(y\)es, \(N\)o, pager \(v\)iew.*?: ','\n',regex=True)
  201. def expect_getend(self,s,regex=False):
  202. ret = self.expect(s,regex=regex,nonl=True)
  203. debug_pexpect_msg(self.p)
  204. # end = self.readline().strip()
  205. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  206. self.expect(self.NL,nonl=True,silent=True)
  207. debug_pexpect_msg(self.p)
  208. end = self.p.before
  209. vmsg(' ==> %s' % cyan(end))
  210. return end
  211. def interactive(self):
  212. return self.p.interact() # interact() not available with popen_spawn
  213. def logfile(self,arg):
  214. self.p.logfile = arg
  215. def expect(self,*args,**kwargs):
  216. return my_expect(self.p,*args,**kwargs)
  217. def send(self,*args,**kwargs):
  218. return my_send(self.p,*args,**kwargs)
  219. # def readline(self):
  220. # return self.p.readline()
  221. # def readlines(self):
  222. # return [l.rstrip()+'\n' for l in self.p.readlines()]
  223. def read(self,n=None):
  224. return self.p.read(n)
  225. def close(self):
  226. if not opt.popen_spawn:
  227. self.p.close()