unit_tests.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  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/unit_tests.py: Unit tests for the MMGen suite
  20. """
  21. import sys,os,time,importlib,platform
  22. from include.tests_header import repo_root
  23. from include.common import end_msg
  24. from mmgen.common import *
  25. opts_data = {
  26. 'text': {
  27. 'desc': "Unit tests for the MMGen suite",
  28. 'usage':'[options] [test | test.subtest]...',
  29. 'options': """
  30. -h, --help Print this help message
  31. -a, --no-altcoin-deps Skip tests requiring altcoin daemons, libs or utils
  32. -A, --no-daemon-autostart Don't start and stop daemons automatically
  33. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  34. -f, --fast Speed up execution by reducing rounds on some tests
  35. -l, --list List available tests
  36. -n, --names Print command names instead of descriptions
  37. -N, --node-tools Select node-tools unit tests
  38. -q, --quiet Produce quieter output
  39. -x, --exclude=T Exclude tests 'T' (comma-separated)
  40. -v, --verbose Produce more verbose output
  41. """,
  42. 'notes': """
  43. If no test is specified, all available tests are run
  44. """
  45. }
  46. }
  47. sys.argv.insert(1,'--skip-cfg-file')
  48. opts.UserOpts._reset_ok += ('use_internal_keccak_module',)
  49. cmd_args = opts.init(opts_data)
  50. file_pfx = 'nt_' if opt.node_tools else 'ut_'
  51. all_tests = sorted(
  52. [fn[3:-3] for fn in os.listdir(os.path.join(repo_root,'test','unit_tests_d')) if fn[:3] == file_pfx])
  53. exclude = opt.exclude.split(',') if opt.exclude else []
  54. for e in exclude:
  55. if e not in all_tests:
  56. die(1,f'{e!r}: invalid parameter for --exclude (no such test)')
  57. start_time = int(time.time())
  58. if opt.list:
  59. Die(0,' '.join(all_tests))
  60. class UnitTestHelpers(object):
  61. @classmethod
  62. def process_bad_data(cls,data):
  63. if os.getenv('PYTHONOPTIMIZE'):
  64. ymsg('PYTHONOPTIMIZE set, skipping error handling tests')
  65. return
  66. import re
  67. desc_w = max(len(e[0]) for e in data)
  68. exc_w = max(len(e[1]) for e in data)
  69. m_exc = '{!r}: incorrect exception type (expected {!r})'
  70. m_err = '{!r}: incorrect error msg (should match {!r}'
  71. m_noraise = "\nillegal action 'bad {}' failed to raise exception {!r}"
  72. for (desc,exc_chk,emsg_chk,func) in data:
  73. try:
  74. vmsg_r(' bad {:{w}}'.format( desc+':', w=desc_w+1 ))
  75. func()
  76. except Exception as e:
  77. exc = type(e).__name__
  78. emsg = e.args[0]
  79. vmsg(' {:{w}} [{}]'.format( exc, emsg, w=exc_w ))
  80. assert exc == exc_chk, m_exc.format(exc,exc_chk)
  81. assert re.search(emsg_chk,emsg), m_err.format(emsg,emsg_chk)
  82. else:
  83. rdie(3,m_noraise.format(desc,exc_chk))
  84. tests_seen = []
  85. def run_test(test,subtest=None):
  86. modname = f'test.unit_tests_d.{file_pfx}{test}'
  87. mod = importlib.import_module(modname)
  88. def run_subtest(subtest):
  89. msg(f'Running unit subtest {test}.{subtest}')
  90. t = getattr(mod,'unit_tests')()
  91. ret = getattr(t,subtest)(test,UnitTestHelpers)
  92. if type(ret).__name__ == 'coroutine':
  93. ret = run_session(ret)
  94. if not ret:
  95. rdie(1,f'Unit subtest {subtest!r} failed')
  96. pass
  97. if test not in tests_seen:
  98. gmsg(f'Running unit test {test}')
  99. tests_seen.append(test)
  100. if subtest:
  101. run_subtest(subtest)
  102. else:
  103. if hasattr(mod,'unit_tests'): # new class-based API
  104. t = getattr(mod,'unit_tests')
  105. altcoin_deps = getattr(t,'altcoin_deps',())
  106. win_skip = getattr(t,'win_skip',())
  107. arm_skip = getattr(t,'arm_skip',())
  108. subtests = [k for k,v in t.__dict__.items() if type(v).__name__ == 'function']
  109. for subtest in subtests:
  110. if opt.no_altcoin_deps and subtest in altcoin_deps:
  111. qmsg(gray(f'Invoked with --no-altcoin-deps, so skipping {subtest!r}'))
  112. continue
  113. if g.platform == 'win' and subtest in win_skip:
  114. qmsg(gray(f'Skipping {subtest!r} for Windows platform'))
  115. continue
  116. elif platform.machine() == 'aarch64' and subtest in arm_skip:
  117. qmsg(gray(f'Skipping {subtest!r} for ARM platform'))
  118. continue
  119. run_subtest(subtest)
  120. else:
  121. if not mod.unit_test().run_test(test,UnitTestHelpers):
  122. rdie(1,'Unit test {test!r} failed')
  123. try:
  124. for test in (cmd_args or all_tests):
  125. if '.' in test:
  126. test,subtest = test.split('.')
  127. else:
  128. subtest = None
  129. if test not in all_tests:
  130. die(1,f'{test!r}: test not recognized')
  131. if test not in exclude:
  132. run_test(test,subtest=subtest)
  133. end_msg(int(time.time()) - start_time)
  134. except KeyboardInterrupt:
  135. die(1,green('\nExiting at user request'))