mmgen_pexpect.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. data_dir = os.path.join('test','data_dir')
  81. add_spawn_args = ' '.join(['{} {}'.format('--'+k.replace('_','-'),
  82. getattr(opt,k) if getattr(opt,k) != True else ''
  83. ) for k in ('testnet','rpc_host','rpc_port','regtest','coin') if getattr(opt,k)]).split()
  84. add_spawn_args += ['--data-dir',data_dir]
  85. def __init__(self,name,mmgen_cmd,cmd_args,desc,no_output=False):
  86. cmd_args = self.add_spawn_args + cmd_args
  87. cmd = (('./','')[bool(opt.system)]+mmgen_cmd,'python')[g.platform=='win']
  88. args = (cmd_args,[mmgen_cmd]+cmd_args)[g.platform=='win']
  89. for i in args:
  90. if type(i) not in (str,unicode):
  91. m1 = 'Error: missing input files in cmd line?:'
  92. m2 = '\nName: {}\nCmd: {}\nCmd args: {}'
  93. die(2,(m1+m2).format(name,cmd,args))
  94. if opt.popen_spawn:
  95. args = [("'"+a+"'" if ' ' in a else a) for a in args]
  96. cmd_str = '{} {}'.format(cmd,' '.join(args))
  97. if opt.popen_spawn:
  98. cmd_str = cmd_str.replace('\\','/')
  99. if opt.log:
  100. log_fd.write(cmd_str+'\n')
  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. sys.stderr.write(green('Testing: {}\n'.format(desc)))
  104. sys.stderr.write(clr1('Executing {}{}'.format(clr2(cmd_str),eol)))
  105. else:
  106. m = 'Testing %s: ' % desc
  107. msg_r(m)
  108. if mmgen_cmd == '': return
  109. if opt.direct_exec:
  110. msg('')
  111. from subprocess import call,check_output
  112. f = (call,check_output)[bool(no_output)]
  113. ret = f([cmd] + args)
  114. if f == call and ret != 0:
  115. m = 'ERROR: process returned a non-zero exit status (%s)'
  116. die(1,red(m % ret))
  117. else:
  118. if opt.traceback:
  119. cmd,args = g.traceback_cmd,[cmd]+args
  120. cmd_str = g.traceback_cmd + ' ' + cmd_str
  121. if opt.popen_spawn:
  122. self.p = PopenSpawn(cmd_str)
  123. else:
  124. self.p = pexpect.spawn(cmd,args)
  125. if opt.exact_output: self.p.logfile = sys.stdout
  126. def ok(self,exit_val=0):
  127. ret = self.p.wait()
  128. if ret != exit_val:
  129. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  130. if opt.profile: return
  131. if opt.verbose or opt.exact_output:
  132. sys.stderr.write(green('OK\n'))
  133. else: msg(' OK')
  134. def cmp_or_die(self,s,t,skip_ok=False,exit_val=0):
  135. ret = self.p.wait()
  136. if ret != exit_val:
  137. die(1,red('test.py: spawned program exited with value {}'.format(ret)))
  138. if s == t:
  139. if not skip_ok: ok()
  140. else:
  141. sys.stderr.write(red(
  142. 'ERROR: recoded data:\n%s\ndiffers from original data:\n%s\n' %
  143. (repr(t),repr(s))))
  144. sys.exit(3)
  145. def license(self):
  146. if 'MMGEN_NO_LICENSE' in os.environ: return
  147. p = "'w' for conditions and warranty info, or 'c' to continue: "
  148. my_expect(self.p,p,'c')
  149. def label(self,label='Test Label'):
  150. p = 'Enter a wallet label, or hit ENTER for no label: '
  151. my_expect(self.p,p,label+'\n')
  152. def usr_rand_out(self,saved=False):
  153. m = '%suser-supplied entropy' % (('','saved ')[saved])
  154. my_expect(self.p,'Generating encryption key from OS random data plus ' + m)
  155. def usr_rand(self,num_chars):
  156. if opt.usr_random:
  157. self.interactive()
  158. my_send(self.p,'\n')
  159. else:
  160. rand_chars = list(getrandstr(num_chars,no_space=True))
  161. my_expect(self.p,'symbols left: ','x')
  162. try:
  163. vmsg_r('SEND ')
  164. while self.p.expect('left: ',0.1) == 0:
  165. ch = rand_chars.pop(0)
  166. msg_r(yellow(ch)+' ' if opt.verbose else '+')
  167. self.p.send(ch)
  168. except:
  169. vmsg('EOT')
  170. my_expect(self.p,'ENTER to continue: ','\n')
  171. def passphrase_new(self,desc,passphrase):
  172. my_expect(self.p,('Enter passphrase for %s: ' % desc), passphrase+'\n')
  173. my_expect(self.p,'Repeat passphrase: ', passphrase+'\n')
  174. def passphrase(self,desc,passphrase,pwtype=''):
  175. if pwtype: pwtype += ' '
  176. my_expect(self.p,('Enter %spassphrase for %s.*?: ' % (pwtype,desc)),
  177. passphrase+'\n',regex=True)
  178. def hash_preset(self,desc,preset=''):
  179. my_expect(self.p,('Enter hash preset for %s' % desc))
  180. my_expect(self.p,('or hit ENTER .*?:'), str(preset)+'\n',regex=True)
  181. def written_to_file(self,desc,overwrite_unlikely=False,query='Overwrite? ',oo=False):
  182. s1 = '%s written to file ' % desc
  183. s2 = query + "Type uppercase 'YES' to confirm: "
  184. ret = my_expect(self.p,([s1,s2],s1)[overwrite_unlikely])
  185. if ret == 1:
  186. my_send(self.p,'YES\n')
  187. # if oo:
  188. outfile = self.expect_getend("Overwriting file '").rstrip("'")
  189. return outfile
  190. # else:
  191. # ret = my_expect(self.p,s1)
  192. self.expect(self.NL,nonl=True)
  193. outfile = self.p.before.strip().strip("'")
  194. if opt.debug_pexpect: msgred('Outfile [%s]' % outfile)
  195. vmsg('%s file: %s' % (desc,cyan(outfile.replace("'",''))))
  196. return outfile
  197. def no_overwrite(self):
  198. self.expect("Overwrite? Type uppercase 'YES' to confirm: ",'\n')
  199. self.expect('Exiting at user request')
  200. def tx_view(self):
  201. my_expect(self.p,r'View .*?transaction.*? \(y\)es, \(N\)o, pager \(v\)iew.*?: ','\n',regex=True)
  202. def expect_getend(self,s,regex=False):
  203. ret = self.expect(s,regex=regex,nonl=True)
  204. debug_pexpect_msg(self.p)
  205. # end = self.readline().strip()
  206. # readline() of partial lines doesn't work with PopenSpawn, so do this instead:
  207. self.expect(self.NL,nonl=True,silent=True)
  208. debug_pexpect_msg(self.p)
  209. end = self.p.before
  210. vmsg(' ==> %s' % cyan(end))
  211. return end
  212. def interactive(self):
  213. return self.p.interact() # interact() not available with popen_spawn
  214. def logfile(self,arg):
  215. self.p.logfile = arg
  216. def expect(self,*args,**kwargs):
  217. return my_expect(self.p,*args,**kwargs)
  218. def send(self,*args,**kwargs):
  219. return my_send(self.p,*args,**kwargs)
  220. # def readline(self):
  221. # return self.p.readline()
  222. # def readlines(self):
  223. # return [l.rstrip()+'\n' for l in self.p.readlines()]
  224. def read(self,n=None):
  225. return self.p.read(n)
  226. def close(self):
  227. if not opt.popen_spawn:
  228. self.p.close()