mmgen_pexpect.py 8.0 KB

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