term.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python3
  2. import sys,os
  3. pn = os.path.abspath(os.path.dirname(sys.argv[0]))
  4. parpar = os.path.dirname(os.path.dirname(pn))
  5. os.chdir(parpar)
  6. sys.path[0] = os.curdir
  7. from mmgen.common import *
  8. opts_data = {
  9. 'text': {
  10. 'desc': 'Interactively test MMGen terminal functionality',
  11. 'usage':'',
  12. 'options': """
  13. -h, --help Print this help message
  14. """,
  15. 'notes': """
  16. """
  17. }
  18. }
  19. cmd_args = opts.init(opts_data)
  20. from mmgen.term import get_char,get_char_raw,get_terminal_size
  21. def cmsg(m):
  22. msg('\n'+cyan(m))
  23. def confirm(m):
  24. if not keypress_confirm(m):
  25. if keypress_confirm('Are you sure you want to exit test?'):
  26. die(1,'Exiting test at user request')
  27. else:
  28. msg('Continuing...')
  29. def tt_start():
  30. m = fmt("""
  31. We will now test MMGen’s terminal capabilities.
  32. This is a non-automated test and requires user interaction.
  33. Continue?
  34. """)
  35. confirm(m.strip())
  36. def tt_get_terminal_size():
  37. cmsg('Testing get_terminal_size():')
  38. msg('X' * get_terminal_size().width)
  39. confirm('Do the X’s exactly fill the width of the screen?')
  40. def tt_color():
  41. cmsg('Testing color:')
  42. confirm(blue('THIS TEXT') + ' should be blue. Is it?')
  43. def tt_license():
  44. cmsg('Testing do_license_msg() with pager')
  45. ymsg('Press "w" to test the pager, then "c" to continue')
  46. do_license_msg()
  47. def tt_my_raw_input():
  48. cmsg('Testing my_raw_input():')
  49. msg(fmt("""
  50. At the Ready? prompt type and hold down "y".
  51. Then Enter some text, followed by held-down ENTER.
  52. The held-down "y" and ENTER keys should be blocked, not affecting the output
  53. on screen or entered text.
  54. """))
  55. get_char_raw('Ready? ',num_chars=1)
  56. reply = my_raw_input('\nEnter text: ')
  57. confirm('Did you enter the text {!r}?'.format(reply))
  58. def tt_get_char(raw=False,one_char=False,sleep=0,immed_chars=''):
  59. fname = ('get_char','get_char_raw')[raw]
  60. fs = fmt("""
  61. Press some keys in quick succession.
  62. {}{}{}
  63. {}
  64. When you’re finished, use Ctrl-C to exit.
  65. """).strip()
  66. m1 = (
  67. 'You should experience a delay with quickly repeated entry.',
  68. 'Your entry should be repeated back to you immediately.'
  69. )[raw]
  70. m2 = (
  71. '',
  72. '\nA delay of {} seconds will added before each prompt'.format(sleep)
  73. )[bool(sleep)]
  74. m3 = (
  75. '',
  76. '\nThe characters {!r} will be repeated immediately, the others with delay.'.format(immed_chars)
  77. )[bool(immed_chars)]
  78. m4 = 'The F1-F12 keys will be ' + (
  79. 'blocked entirely.'
  80. if one_char and not raw else
  81. "echoed AS A SINGLE character '\\x1b'."
  82. if one_char else
  83. 'echoed as a FULL CONTROL SEQUENCE.'
  84. )
  85. if g.platform == 'win':
  86. m4 = 'The Escape and F1-F12 keys will be returned as single characters.'
  87. kwargs = {}
  88. if one_char:
  89. kwargs.update({'num_chars':1})
  90. if sleep:
  91. kwargs.update({'sleep':sleep})
  92. if immed_chars:
  93. kwargs.update({'immed_chars':immed_chars})
  94. cmsg('Testing {}({}):'.format(fname,','.join(['{}={!r}'.format(*i) for i in kwargs.items()])))
  95. msg(fs.format(m1,yellow(m2),yellow(m3),yellow(m4)))
  96. try:
  97. while True:
  98. ret = globals()[fname]('Enter a letter: ',**kwargs)
  99. msg('You typed {!r}'.format(ret))
  100. except KeyboardInterrupt:
  101. msg('\nDone')
  102. def tt_urand():
  103. cmsg('Testing _get_random_data_from_user():')
  104. from mmgen.crypto import _get_random_data_from_user
  105. ret = _get_random_data_from_user(10,desc='data',test_suite=True).decode()
  106. msg('USER ENTROPY (user input + keystroke timings):\n\n{}'.format(fmt(ret,' ')))
  107. times = ret.splitlines()[1:]
  108. avg_prec = sum(len(t.split('.')[1]) for t in times) // len(times)
  109. if avg_prec < g.min_time_precision:
  110. m = 'WARNING: Avg. time precision of only {} decimal points. User entropy quality is degraded!'
  111. ymsg(m.format(avg_prec))
  112. else:
  113. msg('Average time precision: {} decimal points - OK'.format(avg_prec))
  114. my_raw_input('Press ENTER to continue: ')
  115. def tt_txview():
  116. cmsg('Testing tx.view_with_prompt() (try each viewing option)')
  117. from mmgen.tx import MMGenTX
  118. fn = 'test/ref/0B8D5A[15.31789,14,tl=1320969600].rawtx'
  119. tx = MMGenTX(fn,offline=True)
  120. while True:
  121. tx.view_with_prompt('View data for transaction?',pause=False)
  122. if not keypress_confirm('Continue testing transaction view?',default_yes=True):
  123. break
  124. if g.platform == 'linux':
  125. import termios,atexit
  126. fd = sys.stdin.fileno()
  127. old = termios.tcgetattr(fd)
  128. atexit.register(lambda: termios.tcsetattr(fd,termios.TCSADRAIN,old))
  129. tt_start()
  130. tt_get_terminal_size()
  131. tt_color()
  132. tt_license()
  133. tt_my_raw_input()
  134. tt_urand()
  135. tt_txview()
  136. tt_get_char(one_char=True)
  137. tt_get_char(one_char=True,sleep=1)
  138. tt_get_char(one_char=True,raw=True)
  139. if g.platform == 'linux':
  140. tt_get_char(one_char=False)
  141. tt_get_char(one_char=False,immed_chars='asdf')
  142. tt_get_char(one_char=False,raw=True)
  143. else:
  144. tt_get_char(one_char=True,immed_chars='asdf')
  145. gmsg('\nTest completed')