term.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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_line_input():
  48. cmsg('Testing line_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 = line_input('\nEnter text: ')
  57. confirm(f'Did you enter the text {reply!r}?')
  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. f'\nA delay of {sleep} seconds will added before each prompt'
  73. )[bool(sleep)]
  74. m3 = (
  75. '',
  76. f'\nThe characters {immed_chars!r} will be repeated immediately, the others with delay.'
  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(
  95. fname,
  96. ','.join(f'{a}={b!r}' for a,b in kwargs.items())
  97. ))
  98. msg(fs.format( m1, yellow(m2), yellow(m3), yellow(m4) ))
  99. try:
  100. while True:
  101. ret = globals()[fname]('Enter a letter: ',**kwargs)
  102. msg(f'You typed {ret!r}')
  103. except KeyboardInterrupt:
  104. msg('\nDone')
  105. def tt_urand():
  106. cmsg('Testing _get_random_data_from_user():')
  107. from mmgen.crypto import _get_random_data_from_user
  108. ret = _get_random_data_from_user(10,desc='data').decode()
  109. msg(f'USER ENTROPY (user input + keystroke timings):\n\n{fmt(ret," ")}')
  110. times = ret.splitlines()[1:]
  111. avg_prec = sum(len(t.split('.')[1]) for t in times) // len(times)
  112. if avg_prec < g.min_time_precision:
  113. ymsg(f'WARNING: Avg. time precision of only {avg_prec} decimal points. User entropy quality is degraded!')
  114. else:
  115. msg(f'Average time precision: {avg_prec} decimal points - OK')
  116. line_input('Press ENTER to continue: ')
  117. def tt_txview():
  118. cmsg('Testing tx.view_with_prompt() (try each viewing option)')
  119. from mmgen.tx import MMGenTX
  120. fn = 'test/ref/0B8D5A[15.31789,14,tl=1320969600].rawtx'
  121. tx = MMGenTX.Unsigned(filename=fn,quiet_open=True)
  122. while True:
  123. tx.view_with_prompt('View data for transaction?',pause=False)
  124. set_vt100()
  125. if not keypress_confirm('Continue testing transaction view?',default_yes=True):
  126. break
  127. if g.platform == 'linux':
  128. import termios,atexit
  129. fd = sys.stdin.fileno()
  130. old = termios.tcgetattr(fd)
  131. atexit.register(lambda: termios.tcsetattr(fd,termios.TCSADRAIN,old))
  132. tt_start()
  133. tt_get_terminal_size()
  134. tt_color()
  135. tt_license()
  136. set_vt100()
  137. tt_line_input()
  138. tt_urand()
  139. tt_txview()
  140. tt_get_char(one_char=True)
  141. tt_get_char(one_char=True,sleep=1)
  142. tt_get_char(one_char=True,raw=True)
  143. if g.platform == 'linux':
  144. tt_get_char(one_char=False)
  145. tt_get_char(one_char=False,immed_chars='asdf')
  146. tt_get_char(one_char=False,raw=True)
  147. else:
  148. tt_get_char(one_char=True,immed_chars='asdf')
  149. gmsg('\nTest completed')