term.py 4.5 KB

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